<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace app\index\controller;
use think\Controller;
use app\index\common\DataType;
class ApiDocs  extends Controller{
    private $dataType = array(
        DataType::TYPE_INTEGER => 'Integer',
        DataType::TYPE_STRING  => 'String',
        DataType::TYPE_BOOLEAN => 'Boolean',
        DataType::TYPE_ENUM    => 'Enum',
        DataType::TYPE_FLOAT   => 'Float',
        DataType::TYPE_FILE    => 'File',
        DataType::TYPE_MOBILE  => 'Mobile',
        DataType::TYPE_OBJECT  => 'Object',
        DataType::TYPE_ARRAY   => 'Array'
    );
    
    function _initialize() {
        if(!check_login() || !$this->isAdministrator()){
            exit(json_encode(array('code'=>500,'msg'=>'必须登录后，管理员才能操作','data'=>array())));
        }

        define('IS_GET', \think\Request::instance()->isGet());
        define('IS_POST', \think\Request::instance()->isPost());
        parent::_initialize();
    }
    function index() {
        $input = input();
        
        if($input['app_id']){
            $apiList = db('api_list')->where('app_id',$input['app_id'])->select();
            
            $this->assign('apiList',$apiList);
        }else{
            $apiList = db('api_app')->select();
            $this->assign('appList',$apiList);
        }
        
        
        return $this->fetch();
    }
    function isAdministrator(){
        $main_work_type = (int)session('main_work_type');
        $work_type      = session('work_type');

        $allWorkType = explode(',',trim($main_work_type.','.$work_type,','));
        if(in_array(SYSTEM_AUTH_ADMIN,$allWorkType)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 签名参数，将所有POST参数，按access token规则进行签名，以获得API的ACCESS-TOKEN
     * 只能在调试模式下调用，非debug模式不能调用。
     * 
     */
    public function signParams() {
        if(config('app_debug') === true){
            $params = input('post.');
            $appId = $params['app_id'];
            unset($params['app_id']);
            $appInfo = db('api_app')->where('app_id',$appId)->find();

            $appSecret = config('ext.app_secret');//$appInfo['app_secret'];
            ksort($params);
            $tokenStr = md5(arrayToParams($params).$appSecret);
            exit(json_encode(array('code'=>200,'msg'=>'','data'=>array('sign'=>$tokenStr))));
        }else{
            send_http_status(500);
            exit(json_encode(array('code'=>500,'msg'=>'AccessDeny!','data'=>array())));
        }
    }
    public function fieldsManage() {
        $hash = input('hash');
        $where['type'] = 0;
        if (!empty($hash)) {
            $where['hash'] = $hash;
        }
        $res = db('ApiFields')->where($where)->select();
        $this->assign('dataType', $this->dataType);
        $this->assign('list', $res);
        $this->assign('type', 0);
        //$this->display('index');
        return $this->fetch();
    }
    public function fieldEdit() {
        if( IS_GET ){
            $id = (int)input('id');
            $this->assign('dataType', $this->dataType);
            if ($id) {
                $detail = db('ApiFields')->where(array('id' => $id))->find();
                $this->assign('detail', $detail);
                $this->assign('dataType', $this->dataType);
            }else{
                $data['hash'] = input('hash');
                $this->assign('detail', $data);
            }
            return $this->fetch();
        }elseif( IS_POST ){
            $data = input('post.');
            if((int)$data['id']){
                $data['fieldName'] = $data['showName'];
                $res = db('ApiFields')->where(array('id' => $data['id']))->update($data);
            }else{
                $data['fieldName'] = $data['showName'];
                $res = db('ApiFields')->insert($data);
            }
            if( $res === false ){
                $this->ajaxError('操作失败');
            }else{
                $this->ajaxSuccess('操作成功');
            }
        }
        
        
        
    }
    public function fieldDel() {
        $id = input('id/d');

        \think\Db::startTrans();
        try{

            \think\Db::table("api_fields")->delete($id);

            \think\Db::commit();
            $this->ajaxSuccess('操作成功');
        }  catch (\Exception $e){
            \think\Db::rollback();
            $this->ajaxError('操作失败');
        }

    }
    public function apiManage(){
        $id = (int)input('id');
        
        if($id){
            $list = db('api_list')
                ->join("api_app"," api_app.id = api_list.app_id","left")
                ->field("api_list.*,api_app.app_name")
                ->order('api_list.id asc')->where('api_list.app_id',$id)->select();
        }else{
            $list = db('api_list')
                ->join("api_app"," api_app.id = api_list.app_id","left")
                ->field("api_list.*,api_app.app_name")
                ->order('api_list.id asc')->select();
        }
        $this->assign('list', $list);
        
        
        
        return $this->fetch();
    }
    public function apiEdit() {
        if( IS_GET ){
            $id = (int)input('id');
            $appList = db("ApiApp")->select();
            $this->assign('appList',$appList);
            if( $id ){
                $detail = db('ApiList')->where(array('id' => $id))->find();
                $this->assign('detail', $detail);
                
            }else{
                $data['hash'] = uniqid();
                $this->assign('detail', $data);
            }
            return $this->fetch('add');
        }elseif( IS_POST ){
            $data = input('post.');
            if((int)$data['id']){
                $res = db('ApiList')->where(array('id' => $data['id']))->update($data);
            }else{
                $res = db('ApiList')->insert($data);
            }
            if( $res === false ){
                $this->ajaxError('操作失败');
            }else{
                $this->ajaxSuccess('操作成功');
            }
        }
        
        
    }
    public function apiDel() {
        $id = input('id/d');
        $api = db('ApiList')->where('id',$id)->find();
        if($id && $api){
            \think\Db::startTrans();
            try{
                
                \think\Db::table("api_list")->where('id', $id)->delete();
                \think\Db::table("api_fields")->where('hash',$api['hash'])->delete();
                
                \think\Db::commit();
                $this->ajaxSuccess('操作成功');
            }  catch (\Exception $e){
                \think\Db::rollback();
                $this->ajaxError('操作失败');
            }
        }
    }
    public function appManage(){
        $list = db('ApiApp')->select();
        $this->assign('list', $list);
        return $this->fetch('applist');
    }
    public function appEdit() {
        if( IS_GET ){
            $id = (int)input('id');
            if( $id ){
                $detail = db('ApiApp')->where(array('id' => $id))->find();
                $this->assign('detail', $detail);
            }else{
                $data['app_id'] = get_rand_string(8, 1);
                $data['app_secret'] = get_rand_string(32);
                $this->assign('detail', $data);
            }
            return $this->fetch('appadd');
        }elseif( IS_POST ){
            $data = input('post.');
            if((int)$data['id']){
                $res = db('ApiApp')->where(array('id' => $data['id']))->update($data);
            }else{
                $res = db('ApiApp')->insert($data);
            }
            if( $res === false ){
                $this->ajaxError('操作失败');
            }else{
                $this->ajaxSuccess('操作成功');
            }
        }
    }
    public function appStatus(){
        if( IS_POST ){
            $status = input('post.status/d');
            $id = input('post.id/d');
            if( $id ){
                Model('ApiApp')->update(array('status'=>$status),array('id' => $id));
                $this->ajaxSuccess('操作成功');
            }else{
                $this->ajaxError('缺少参数');
            }
        }
        
        
    }
    public function appDel() {
        $id = input('id/d');
        $app = db('ApiApp')->where('id',$id)->find();
        if($id && $app){
            \think\Db::startTrans();
            try{
                \think\Db::table("api_app")->where('id',$id)->delete();
                $api = db('ApiApp')->where('app_id',$app['id'])->find();
                if($api){
                    \think\Db::table("api_list")->where('app_id', $id)->delete();
                    \think\Db::table("api_fields")->where('hash',$api['hash'])->delete();
                }
                \think\Db::commit();
                $this->ajaxSuccess('操作成功');
            }  catch (\Exception $e){
                \think\Db::rollback();
                $this->ajaxError('操作失败');
            }
        }
        
    }
    
    
    /**
     * Ajax正确返回，自动添加debug数据
     * @param $msg
     * @param array $data
     * @param int $code
     */
    public function ajaxSuccess( $msg, $code = 1, $data = array() ){
        $returnData = array(
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        );
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($returnData));
    }

    /**
     * Ajax错误返回，自动添加debug数据
     * @param $msg
     * @param array $data
     * @param int $code
     */
    public function ajaxError( $msg, $code = 0, $data = array() ){
        $returnData = array(
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        );
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($returnData));
    }
    
    

}