<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use JWT;
use App\Services\Login\LoginService;
use App\Lib\UKEY;
class UkeyController extends Controller
{
    public function Bind(Request $request){
        $userid = $request->get('userid');//中间件产生的参数
        $pwd=request('pwd'); //密码
        $sfid=request('sfid'); //密码
        $s=app()->make(LoginService::class);
        $check=$s->CheckPwd(['userid'=>$userid,'password'=>$pwd]);
        if($check['status']){
            $u=DB::table('users')->where(['id'=>$userid])->update([
                'ukey_sfuid'=>$sfid,
            ]);
            if($u){
                return \Yz::Return(true,'绑定成功',[]);
            }else{
                return \Yz::echoError1("绑定失败");
            }
        }else{
            return \Yz::echoError1("密码验证失败");
        }
    }
    public function GetServeInfo(){
        $info =UKEY::GetServerInfo();
        return \Yz::Return(true,'获取成功',['serve_info'=>$info]);
    }
    public function UkeyLogin(){
        $cliCert=request('cliCert'); //客户端证书
        $sign=request('sign'); //签名值
        $oridata=request('oridata'); //随机数原文
        $ukey_userid=request('ukey_userid'); //ukey唯一标识
        $check=UKEY::CheckCert($cliCert);
        if($check==1){
            $checksign=UKEY::CheckSign($cliCert,$oridata,$sign);
            if($checksign){
                $user=DB::table('users')->where(['ukey_sfuid'=>$ukey_userid,'status'=>1])->get();
                if(count($user)>0){
                    $result=[];
                    $jwt= new JWT();
                    $accessTimeout = $jwt -> GetGetSecretTimeOut();
                    $refreshTimeout = $jwt -> GetRefreshTokenTimeOut();
                    $access_token = $jwt->BuildJWT('yz','access',$user[0]->id,$user[0]->group,$accessTimeout);
                    $refresh_token = $jwt->BuildJWT('yz','refresh',$user[0]->id,'',$refreshTimeout);
                    if(!empty($arr['mian7'])){
                        $mian7_token = $jwt->BuildJWT('yz','mian7',$user[0]->id,'',$jwt -> GetMian7TokenTimeOut());
                        $result['mian7_token']=$mian7_token;
                    }
                    DB::table('users')->where(['id'=>$user[0]->id,'status'=>1])->update(['token'=>md5($refresh_token)]);
                    $result['token']=$access_token;
                    $result['refresh_token']=$refresh_token;
                    return \Yz::Return(true,'验证成功',$result);
                }else{
                    return \Yz::echoError1("未找到关联此Ukey的有效用户");
                }

            }else{
                return \Yz::echoError1("验证客户端随机数签名失败");
            }
        }else{
            return \Yz::echoError1("证书验证失败".$check);
        }

    }
}
