<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/19
 * Time: 10:43
 */
class ModelVerifykp
{

    private $rKey = [
        0 => '18257284-7F5D-348D-AB09-299E5B7DD997',
        1 => '655A957D-157D-7C21-E3A7-9CAAFA835318',
        2 => 'F467CA93-D550-346D-6BCB-173995F7C83A',
        3 => 'BD32817A-99F9-2E26-5B33-15208F7B360A'
    ];


    /**
     * 验证该用户信息的合法性
     * @param $data
     * @return string
     */
    public function validateKP($data)
    {
        if(empty($data)) {
            return [];
        }

        //海外的需要判断是否是这两个个域名，*.100ko.com  *.kpzs.com
        $verifyurl = $data['verifyurl'];
        $tmpUrlArr = parse_url($verifyurl);
        $host = $tmpUrlArr['host'] ?? '';
        if(empty($host)) {
            oo::logs()->debug3('域名解析错误：'.$verifyurl, 'kpVerifyFail.php');
            return [];
        }
        $reg1  = "/.kpzs.com$/";
        $reg2 = "/.100ko.com$/";
        $ret1= preg_match($reg1, $host);

        if(!$ret1) {
            $ret2= preg_match($reg2, $host);
            if(!$ret2) {
                oo::logs()->debug3('域名验证不通过：'.$verifyurl, 'kpVerifyFail.php');
                return [];
            }
        }

        $imei = $data['imei'];
        $openid = $data['openid'];
        $tag = $data['tag'];
        $token = $data['token'];

        $response = oo::functions()->curl($verifyurl);
        $code = $response['code'] ?? 0;
        $r = $response['r'] ?? 'A';
        $sign = $response['sign'] ?? '';
        if(!$code) {
            oo::logs()->debug3('登录验证不通过：'.json_encode($response).' data:'.$verifyurl, 'kpVerifyFail.php');
            return [];
        }

        $result = $this->verify($code, $tag, $imei, $token, $r, $sign);
        if(!$result) {
            oo::logs()->debug3('验签失败:  openid: '.$openid.'code:'.$code.'  tag:'.$tag.' imei:'.$imei.'  token:'.$token.'  r:'.$r.'  sign：'.$sign, 'kpVerifyFail.php');
            return [];
        }
        return $data;
    }


    /**
     * 对参数进行处理
     * @param $data
     * @return string
     */
    private function dealUrlParam($data)
    {
        $urlParam = '';
        foreach ($data as $key => $v) {
            $urlParam .= '&'.$key .'='.$v;
        }
        $urlParam = ltrim($urlParam, '&');
        return $urlParam;
    }

    /**
     * 返回验签 SignMD5  规则 ：(code 值 tage 值 值 imei  小写值 token  小写值 R  对应的秘钥 Key)Md5
     * @param $data
     * @return string
     */
    protected function verify($code, $tag, $imei, $token ,$r, $sign)
    {
        if(!in_array($r, [0, 1, 2, 3]) || empty($sign)) {
            return false;
        }
        $imei = strtolower($imei);
        $token = strtolower($token);
        $rKey = $this->rKey[$r];
        $signTmp = md5($code.$tag.$imei.$token.$rKey);
        if($sign === $signTmp) {
            return true;
        }
        return false;
    }

}