<?php
 /** 
 * 人脸识别
 * @Copyright (C) 2018 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Common\Vendor;
class Face{    
    private $_aid      = 'S107'; //开放平台系统编号
    private $_akey     = 'S107-00000037';//万店掌开放平台分配给第三方的开发者key   
    private $_asid     = 'c7a01e0d804a9ce872f91fef595a8164';    
    private $_sm       = 'sha1';//签名算法 md5,sha1    
    private $_version  = 'v1';//版本号    
    private $api_url   = 'http://openapi.ovopark.com/m.api';//api 地址    
    public $orgid      = 85;//企业id    
    public $departno   = 0;//分组id(即groupid)    
    private $_requestMode = 'post';//请求方式post,get
    /**
     * 构造函数
     * @param array $config = array();
     */
    public function __construct($config){
        $this->config = !empty($this->config) && !empty($config)? array_merge($this->config, $config):!empty($config)?$config:$this->config;
        $this->_aid  = isset($this->config['_aid'])?$this->config['_aid']:$this->_aid;
        $this->_akey = isset($this->config['_akey'])?$this->config['_akey']:$this->_akey;
        $this->_asid = isset($this->config['_asid'])?$this->config['_asid']:$this->_asid;
    }
    /**
     * 添加用户
     * 开发者注册会员至万店掌人脸平台
     * @param array $user 用户数据
     * @return bool|mixed|string 返回请求结果
     */
    public function addUser($user = array()){
        $return =array('status'=>0,'info'=>'');
        if(empty($user)){$return['info']='参数错误';return $return;}
        $_post['_mt'] = 'open.face.addUser';//公共参数        
        // $_post['DataUser'] = json_encode($user);//业务参数
        $_post['DataUser'] = json_encode($user,JSON_UNESCAPED_SLASHES);//业务参数
        $data = $this->makeRequest($_post);//发起post请求
        return $data;
    }
    /**
     * 查询分组
     * 开发者查询人脸分组信息
     */
    public function queryGroup(){
        $_post = array(
            '_mt'=> 'open.face.queryGroup',//公共参数
            'orgid'=> $this->orgid//业务参数
        );
        $data = $this->makeRequest($_post);//发起post请求
        return $data;
    }
    /**
     * 查询人脸设备
     * 开发者查询人脸设备列表信息
     */
    public function queryDevice(){
        //业务参数
        $_post = array(
            '_mt'=> 'open.face.queryDevice',//公共参数
            'orgid'=> $this->orgid
        );
        $data = $this->makeRequest($_post);//发起post请求
        return $data;
    }
    /**
     * 绑定人脸设备
     * 开发者绑定人脸设备和分组的关系
     * @param int $deviceId  设备ID
     * @param int $groupid  分组ID
     * @return array|mixed|string
     */
    public function bindingDevice($deviceId=0,$groupid=0){        
        $return =array('status'=>0,'info'=>'');
        if(empty($deviceId)){$return['info']='参数错误';return $return;}
        //业务参数
        $_post = array(
            '_mt'=> 'open.face.bindingDevice',//公共参数
            'orgid'=> $this->orgid,
            'groupid'=> $this->departno,
            'deviceId'=>$deviceId
        );
        if($groupid){
            $_post['groupid'] = $groupid;
        }
        $data = $this->makeRequest($_post);//发起post请求
        return $data;
    }
    /**
     * 更新用户
     * 开发者更新会员至万店掌人脸平台
     * @param array $user 用户数据
     * @return array 返回请求结果
     */
    public function updateUser($user = array()){        
        $user['_mt'] = 'open.face.updateUser';//公共参数
        //业务参数
        if( !$user['orgid'] ){
            $user['orgid'] = $this->orgid;
        }
        if( !$user['departno'] ){
            $user['departno'] = $this->departno;
        }
        //是否验证手机号
        if( !$user['checkrepeat'] ){
            $user['checkrepeat'] = 0;
        }
        $data = $this->makeRequest($user);//发起post请求
        return $data;
    }
    /**
     * 添加分组
     * 开发者添加人脸分组信息
     * @param string $group_name 分组名称
     * @return array|mixed|string
     */
    public function addGroup($group_name=''){
        $return =array('status'=>0,'info'=>'');
        if(empty($group_name)){$return['info']='参数错误';return $return;}
        //业务参数
        $_post = array(
             '_mt'      => 'open.face.addGroup',
             'groupname'=> $group_name,//分组名称
             'orgid'    => $this->orgid
        );
        $data = $this->makeRequest($_post);//发起post请求
        return $data;
    }
    /**
     * 接口回调
     */
    public function notify($_data=''){
        $return =array('status'=>0,'info'=>'');
        if(empty($_data))$_data=I('post.');
        if(empty($_data)){$return['info']='参数错误';$this->ajaxReturn($return);}
        //做业务逻辑处理
        // $_data=array ( 'result' => '"SUCCESS"', 'stat' => '{"cid":"a:f52876|t:1743583|s:1539653638898","code":"0","codename":"SUCCESS","systime":1539653638898}', 'data' => '{"_aid":"S107","_akey":"S107-00000037","_format":"json","_mt":"open.face.queryUserCallBack","_requestMode":"post","_sig":"CBA2AC05D5E81B559220AFA78D2CE0B9","_sm":"md5","_timestamp":"20181016093358","_version":"v1","age":"26","arriveTime":"20181016093358","deviceId":"1746","deviceMac":"D47C44900354","deviceName":"D47C44900354","emotion":"neutral","ethnicity":"Asian","faceId":"41185","gender":"false","glass":"Normal","groupid":"9697","memberType":"0","mobilephone":"","orgid":"85","skinstatus":"health","thirdpicurl":"http://ovopark.oss-cn-hangzhou.aliyuncs.com/2018/10/16/1539653636384885.jpeg","userid":"39","username":"39","wdzpicurl":"http://ovopark.oss-cn-hangzhou.aliyuncs.com/2018/10/16/1539653638488709.jpeg"}', );
        // file_put_contents('uploads/PAY-fa'.I('get.method').date("YmdHis").'.txt',var_export($_data,true));
        // $result=$_data['result'];
        // file_put_contents('uploads/PAY-fc'.I('get.method').date("YmdHis").'.txt',var_export($_data,true));
        $stat=$datas=array();
        $stat=json_decode(strip_tags(htmlspecialchars_decode($_data['stat'])),true);
        $datas=json_decode(strip_tags(htmlspecialchars_decode($_data['data'])),true);
      $shop_id='';
        if(!empty($datas['userid'])){
            $updata=array();
            $updata['orgid']=$datas['orgid'];
            $updata['departno']=$datas['groupid'];
            $updata['userid']=$datas['userid'];
            $updata['thirdpicurl']=$datas['wdzpicurl'];
            $this->updateUser($updata);//更新存储照片信息
            if(is_int($datas['userid'])==false){
                $datas['userid']=intval($datas['userid']);
            }
            D('Common/Face')->up_customer($datas);//更新顾客信息
            $return = array('status'=>1,'info'=>'success');
        }else{//顾客
            if($stat['code']=='100014' || $stat['code']=='100036')
            {
                $userid=D('Common/Face')->add_customer($datas);
                if($userid){
                    if(empty($datas['groupid'])){
                        $shop_info=D('Common/Face')->get_shop_info($datas['deviceId']);
                        if($shop_info){
                            $shop_id=$shop_info['id'];
                            $group_data=$this->addGroup($shop_info['name']);
                            if($group_data['stat']['code']==0){
                                $return_bind=$this->bindingDevice($datas['deviceId'],$group_data['data']['id']);
                                if($return_bind['stat']['code']!=0){
                                    $return['info']=$return_bind['result'];
                                    $this->ajaxReturn($return);
                                }
                                $add_data=array();
                                $add_data['departno']=$datas['groupid']=$group_data['data']['id'];
                            }else{
                                $return['info']=$datas['result'];
                                $this->ajaxReturn($return);
                            }
                        }else{
                            $return['info']="设备未绑定";
                            $this->ajaxReturn($return);
                        }
                    }else{
                        $add_data=array();
                        if(is_int($datas['groupid'])){
                            $add_data['departno']=$datas['groupid'];
                        }else{
                            $add_data['departno']=intval($datas['groupid']);
                        }
                    }
                    $add_data['orgid']=$this->orgid;
                    $add_data['userid']=$userid;
                    $add_data['thirdpicurl']=$datas['wdzpicurl'];
                    $add_data['membertype']='0';
                    $add_data['checkrepeat']=0;
                    $adddata=array();
                    $adddata[]=$add_data;
                    $return_add=$this->addUser($adddata);
                    if($return_add['stat']['code']!=0){
                        $return['info']=$return_add['result'];
                        $this->ajaxReturn($return);
                    }
                    // file_put_contents('uploads/PAY-fc'.I('get.method').date("YmdHis").'.txt',var_export($return_add,true));
                    $return = array('status'=>1,'info'=>'success');
                }
            }
        }
        if(empty($shop_id) && $datas['groupid']){
            $shop_id=idtoname($datas['groupid'],'Shops','id','group_id');
        }
        if($shop_id){
            $content="欢迎光临";
            $paramdata=array('type'=>5,'txt'=>$content);
            $ids=getpushids(6,$shop_id);
            if(!empty($ids[1]))$result = pushSend($ids[1],$content,'app',1,$paramdata);
            if(!empty($ids[2]))$result = pushSend($ids[2],$content,'app',2,$paramdata);
        }
        $this->ajaxReturn($return);
    }
    /**
     * 请求调用api
     * data:业务数据
     * @return bool
     */
    private function makeRequest($data,$url=''){
        $timestamp=time_format(NOW_TIME,'Ymdhis');
        $base=array(
            '_aid'=>$this->_aid,
            '_akey'=>$this->_akey,
            '_sm'=>$this->_sm,
            '_requestMode'=>$this->_requestMode,
            '_version'=>$this->_version,
            '_timestamp'=>$timestamp,
            'orgid'=>$this->orgid,
            '_format'=>'json',
        );
        $param =array_merge($base,$data);
        $param["_sig"]=$this->generateSign($param);
        $request=$this->api_url;
        $request = curlget($request,$param,'POST');
        $request = trim($request);
        $request = json_decode($request,true);
        return $request;
    }
    //生成签名
    protected function generateSign($params){
        $stringToBeSigned = $this->paramsToString($params);
        $sign=$this->_sm=='md5'?md5($stringToBeSigned):sha1($stringToBeSigned);
		return strtoupper($sign);
	}
    //验签
	protected function verifySign($params){
	    $sign = $params["_sig"];unset($params["_sig"]);
        $stringToBeSigned = $this->paramsToString($params);       
        $backsign=$this->_sm=='md5'?md5($stringToBeSigned):sha1($stringToBeSigned);
        $backsign=strtoupper($backsign);
        if(!empty($sign)){return $sign == $backsign;}
        return false;
	}
    //组合待签名字符
    protected function paramsToString($parameter){
        if(!$parameter){return false;}
        ksort($parameter);//数组升序排序
        $parameter_str = '';
        //把数组转为连续连接的字符串
        foreach($parameter as $name=>$val){
            $parameter_str .= $name.$val;
        }
        //签名前后需要加上 _asid;
        return $this->_asid.$parameter_str.$this->_asid;
    }
    //json返回
    private function ajaxReturn($data){
        echo json_encode($data);exit;
    }
}
?>