<?php

namespace Setting\Lib;

use Dever;

class Idcard
{
	static $AccessKeyId     = 'LTAI5t5k4M2gK6kctX6iq8CT';
    static $AccessKeySecret = 'hfFy8smTc9CKEThpqFTG32zJuHd3dS';
    static $AliHost         = 'http://ocr-api.cn-hangzhou.aliyuncs.com/?';

    //查询域名
    public function getIdcard_api(){
        $param = self::getCommonParams();
        $param['Action']  = 'RecognizeIdcard';
        $param['OutputFigure'] = 'false';
        $param['Url'] = Dever::input('url');
        $name = Dever::input('name');
        $idcard = Dever::input('idcard');
        $type = Dever::input('type');#1=正面，2=反面
        $param['Signature']  = self::getSignature($param); 
        $url = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
        foreach ($param as $k => $v) {
            $url .= '&' . $k . '=' . $v;
        }
        $data = Dever::load('setting/lib/idcard')->callInterface($url,$name,$idcard,$type);
        return $data;
    }
    // http://guanli.uat.churenyiliao.com/data/upload/8/2022/06/09/71698f0e0b574317363c8a61409585cd_w1.jpg
    // http%3A%2F%2Fguanli.uat.churenyiliao.com%2Fdata%2Fupload%2F9%2F2022%2F06%2F08%2Ffe5f8b472eb2fd76d144f926c0e2b725.jpg
     public function callInterface($url,$name,$idcard,$type){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($ch);
        curl_close($ch);
        $res =(array)(json_decode($res));
        if($res && isset($res['Data']) && $res['Data']){
            $data = (array)(json_decode($res['Data'],true));
            $rest = (array)($data['data']);
            if($type == 1){
            	if(isset($rest['face']) && $rest['face']){
            		foreach($rest as $k => $v){
            			return $v['data'];
            		}
            	}else{
            		Dever::alert('请上传正确的身份证正面图片');
            	}
            }elseif($type == 2){
            	if(isset($rest['back']) && $rest['back']){
            		foreach($rest as $k =>$v){
                        if (isset($v['data']['validPeriod'])) {
                            $date = explode('-',$v['data']['validPeriod']);
                            if($date[1] && $date[1] != '长期'){
                                $cdate = strtotime(str_replace('.','-',$date[1]));
                                if(time()>=$cdate){
                                    Dever::alert('身份证背面已过期');
                                }
                            }
                            
                        } else {
                            Dever::alert('请上传正确的身份证背面图片');
                        }

            			return $v['data'];
            		}
            	}else{
            		Dever::alert('请上传正确的身份证背面图片');
            	}
            }
           //  if(isset($rest['face']) && $rest['face']){
           //      foreach($rest as $k=>$v){
           //          if($name != $v['data']['name'] || $idcard != $v['data']['idNumber']){
           //              Dever::alert('姓名或身份证号不匹配');
           //          }
           //     }
           // }elseif(isset($rest['back']) && $rest['back']){
           //      foreach($rest as $k => $v){
           //          $date = explode('-',$v['data']['validPeriod']);
           //          $cdate = strtotime(str_replace('.','-',$date[1]));
           //          if(time()>=$cdate){
           //              Dever::alert('身份证背面已过期');
           //          }
           //      }
           // }
            // return $rest;
        }else{
             Dever::alert('身份证图片有误');
        } 
    }
    private static function getCommonParams(){
        date_default_timezone_set("GMT");
        $data = [
            'Format'           => 'JSON',
            'Version'          => '2021-07-07',
            'AccessKeyId'      => self::$AccessKeyId,
            'SignatureMethod'  => 'HMAC-SHA1',
            'Timestamp'        => date('Y-m-d') . 'T' . date('H:i:s') . 'Z',//'2021-08-09T08:27:00Z',//,
            'SignatureVersion' => '1.0',
            'SignatureNonce'   =>  uniqid(),//microtime(),//
            'Action'           => 'DescribeRegions',
        ];
        
        return $data;
    }

    private static function percentEncode($str)
    {
        // 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }

    //生成签名
    private function getSignature($parameters)
    {
        // 将参数Key按字典顺序排序
        ksort($parameters);
        // 生成规范化请求字符串
        $canonicalizedQueryString = '';
        foreach($parameters as $key => $value)
        {
            $canonicalizedQueryString .= '&' .self::percentEncode($key)
                . '=' . self::percentEncode($value);
        }
        // 生成用于计算签名的字符串 stringToSign
        $stringToSign = 'GET&%2F&' . self::percentEncode(substr($canonicalizedQueryString, 1));
        // 计算签名，注意accessKeySecret后面要加上字符'&'
        $signature = self::percentEncode(base64_encode(hash_hmac('sha1', $stringToSign, self::$AccessKeySecret . '&', true)));
        return $signature;
    }
}