<?php
namespace app\login\controller;
use app\login\model\Token as TokenModel;
use src\Dingtalk\Utils;
use think\Controller;
use think\Db;
use src\Dingtalk;
use think\Session;
class Index extends Controller
{
    public function check()
    {
        $token = input('post.token');

        $tokenModel = new TokenModel();
        $checkResult = $tokenModel->check($token);

        if ($checkResult == false) {

            return json(code([], $tokenModel->getErrCode(), $tokenModel->getError()));
        } else {
            return json(code(['bind_info' => json_decode($checkResult)]));
        }
    }
    public function config(){
        $Ding = new Dingtalk();
        $Token =new Dingtalk\Token();
        $token =$Token->get();
        $access_token=$Ding->config('access_token',$token);
        Session::set('access_token',$token);

        $ticket = $Token->jsapi();
        Session::set('jsapi_ticket',$ticket);
        $jsapi_ticket= $Ding->config('jsapi_ticket',$ticket);

        $config=$Ding->ddconfig();
//        if($config){
//            $data['config']=$config;
//            $data['status']=200;
//        }
        return json(code([$config], 0, 'ok'));
        //return json($data);
    }


    public  function getSsoToken(){
        $code = input('post.code');
        //var_dump($code);
        //$access_token= Session::get('access_token');

        $User =new Dingtalk\User();
        $userid =$User->code($code);
        //$userid='231115647';
        $token = md5(create_unique());
        $expireSecond = config('token_expire_second');
        $rs = cache('token',$token ,$expireSecond);
        if($userid===false){
            $data['status']=-10001;
            $data['errmsg']='登录失败';
        }else{
            $data['status']=0;
            $data['errmsg']='登录成功';
            $data['userid']=$userid;
            $data['token']=$token;
        }
//        return json($data);
        return json(code([$data], 0, 'ok'));
    }
//    public function create($uid)
//    {
//
//        $tokenModel = new TokenModel();
//        $token = $tokenModel->createToken($uid);
//        if ($token == false) {
//            return json(code([], $tokenModel->getErrCode(), $tokenModel->getError()));
//        } else {
//            return json(code(['token' => $token, 'expire_second' => config('token_expire_second')]));
//        }
//    }
}
