<?php

namespace Server\sso;

use App\Services\CloudService;
use App\Services\MicroService;

class SsoService extends MicroService
{
    public $codeArray=[
        0=>'请求成功',
        -1=>'缺少secret参数',
        -2=>'缺少code参数',
        -3=>'无效code',
        -4=>'secret未配置',
        -5=>'无效的secret',
        -6=>'用户不存在',
        -7=>'code已失效',
        -8=>'请求类型错误',
        -9=>'验签失败',
        -10=>'缺少sign签名',
    ];
    function __construct(){
        global $_W;
        parent::__construct('sso');       //请不要删除这一行
        $this->Unique=false;                //该服务是否区分不同平台
        $this->CompileDrive = "smarty";     //视图编译方式，可选smarty,blade
        $this->uniacid=$GLOBALS['_W']['uniacid'];
        session_start();
        $this->voidCode();
        $_W['framework']=$this->framework;
    }

    public function getCode(){
        global $_W;
        $key=$_W['uid'].$this->uniacid.'sso_code';

        $code=$this->checkCode($_SESSION[$key]);
        if(empty($code)){
            $code=$this->setCode($key,1);
            if(!$code) return false;
        }
        return $code;

    }
    public function getMasterCode(){
        global $_W;
        $key=$_W['uid'].$this->uniacid.'sso_code_master';

        $code=$this->checkCode($_SESSION[$key]);

        if(empty($code)){
            $code=$this->setCode($key,2);
            if(!$code) return false;
        }
        return $code;

    }
    private function setCode($key,$type){
        global $_W;
        $code=$this->getRandomString(18);

        $_SESSION[$key]=$code;
        $data=[
            'uniacid'    => $this->uniacid,
            'uid'        => $_W['uid'],
            'code'       => $code,
            'type'       => $type,
            'createtime' => time()
        ];
        $res=pdo_insert('sso_users_code',$data);
        if(!$res){
            return false;
        }
        return $code;
    }

    private function getRandomString($length = 5) {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $bytes = openssl_random_pseudo_bytes($length);
        $result = '';
        for ($i = 0; $i < $length; $i++) {
            $result .= $chars[ord($bytes[$i]) % strlen($chars)];
        }
        return $result;
    }

    protected function apiMessage($data,$code=-1,$status='error')
    {

        $params=[
            'code'=>$code,
            'message'=>$this->codeArray[$code],
            'status'=>$status
        ];
        if(!empty($data)) $params['data']=$data;

        $this->generateLog($params);

        echo json_encode($params);die;
    }
    private function voidCode()
    {
        $uniacid=$this->uniacid ?: 0;
        //获取当前设置的过期时间
        $setting=pdo_get('sso_setting',array('uniacid'=>$uniacid));
        if(empty($setting['expire'])){
            $setting['expire']=24;
        }

        $expireTime=time()-(intval($setting['expire'])*3600);

        $res=pdo_query("UPDATE ". tablename('sso_users_code')." SET `status` = 0 WHERE uniacid ={$uniacid} AND status=1 And createtime < {$expireTime}" );

        return $res;
    }

    protected function generateLog(array $params){
        global $_GPC;

        $data=[
            'uniacid'      => $this->uniacid,
            'ip'           => $_SERVER["REMOTE_ADDR"],
            'request_type' => $_SERVER['REQUEST_METHOD'],
            'status'       => $params['status'],
            'code'         => $params['code'],
            'content'      => !empty( $params['data'] ) ? serialize( $params['data'] ) : '',
            'data'         => serialize( $_GPC ),
            'createtime'   => time()
        ];
        pdo_insert('sso_logs',$data);
    }

    protected function getMasterSecret()
    {
        $activestate = CloudService::CloudActive();

        return md5(md5($activestate['siteid']).'ssoservice');
    }
    private function checkCode($code){
        $usersCode=pdo_get('sso_users_code',array('code'=>$code));

        if(empty($usersCode)) return '';

        return $code;
    }
}
