<?php
namespace Electronic;
use app\shared\model\Option;
use think\facade\Cache;
/**
* 绿米设备
*/
class Lvmi{
	//配置
	public $config;

	//接口URL
	protected $api_url='https://open-cn.aqara.com/';
    private $account;
	public function __construct($config=[]) {
        $this->account=isset($config['account'])?$config['account']:"15860162181";
        $config=Option::where(['module'=>'shared','name'=>'lvmiSysTemConfig'])->cache(120)->value('value');
        $config=json_decode($config,1);
        if(!$config){
           $config=[
                'appid'=>'875360681355575296526c0d',
                "keyid"=>'K.875360681456238593',
                'appKey'=>'7bgy7wozuvmisidrbe44hm7ecg40yeb1',
            ];  
        }else{
            if($config['appid']==0){
                $config=[
                    'appid'=>'875360681355575296526c0d',
                    "keyid"=>'K.875360681456238593',
                    'appKey'=>'7bgy7wozuvmisidrbe44hm7ecg40yeb1',
                ];
            }
        }
        $this->config = (object)$config;

    }
    //第一步
    //获取授权码
    public function getAuthCode($account=""){
        $aciton="v3.0/open/api";
        $url=$this->api_url.$aciton;
        $post['account']=$this->account;
        $post['accountType']=0;
        $post['accessTokenValidity']="10y";
        $header=self::headerParam();
        $params['intent']="config.auth.getAuthCode";
        $params['data']=$post;
        $res=self::httpRequest($url,'POST',$params,$header);
        if($res['code']==0){
            return ['code'=>0,'data'=>$res['result']['authCode']];
        }else{
            return ['code'=>1,'data'=>$res['message']];
        }
        //684873
    }
    //第二步
    //创建位置
    public  function positionCreate($authCode){
        $aciton="v3.0/open/api";
        $url=$this->api_url.$aciton;
        $post['parentPositionId']='';
        $post['positionName']=date('Y-m-d H:i:s');
        $post['description']=2;
        $ret=self::authGetToken($authCode);
        $token=isset($ret['data']['accessToken'])?$ret['data']['accessToken']:'';
        $header=self::headerParam($token);
        $params['intent']="config.position.create";
        $params['data']=$post;
        $res=self::httpRequest($url,'POST',$params,$header);
        if($ret['code']==0){
            return ['code'=>0,'data'=>$ret['data']];
        }else{
            return ['code'=>1,'msg'=>$res['message']];
        }
    }
    //控制设备
    /*
    [{"subjectId":"lumi1.54ef44c91988","resources":[{"resourceId":"14.7.111","value":1}]}]
     */
    public function controllerDevice($accessToken="",$post=[]){
        $aciton="v3.0/open/api";
        $url=$this->api_url.$aciton;
        $header=self::headerParam($accessToken);
        $params['intent']="write.resource.device";
        $params['data']=$post;
        $res=self::httpRequest($url,'POST',$params,$header);
        if($res['code']==0){
            return ['code'=>0,'data'=>$res['result']];
        }else{
            return ['code'=>1,'data'=>$res['message'],'post'=>$params,$header];
        }
    }
    public function authGetToken($authCode=""){
        $aciton="v3.0/open/api";
        $url=$this->api_url.$aciton;
        $post['account']=$this->account;
        $post['accountType']=0;
        $post['authCode']=$authCode;
        $header=self::headerParam();
        $params['intent']="config.auth.getToken";
        $params['data']=$post;

        $res=self::httpRequest($url,'POST',$params,$header);
        if($res['code']==0){
            return ['code'=>0,'data'=>$res['result']];
        }else{
            return ['code'=>1,'data'=>$res['message']];
        }
    }
    //随机字符串
    public function createNonceStr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";  
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {  
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
        } 
        return $str;
    }

    //公共参数
    public function headerParam($Accesstoken=""){
        if($Accesstoken){
            $params['Accesstoken']=$Accesstoken;
        }
        $params['Appid']=$this->config->appid;
        $params['Keyid']=$this->config->keyid;
        $params['Nonce']=time()*1000;
        $params['Time']=time()*1000;
        $params['Sign']=self::createSign($params);
        $params['AppKey']=$this->config->appKey;
        return $params;
    }
    /**
     * 生成签名
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function createSign($params=[]) {
            ksort($params);
            $string = http_build_query($params).$this->config->appKey;

            //签名步骤二：在string后加入KEY
            $string = strtolower($string);
            //签名步骤三：MD5加密
            $string = md5($string);
            //签名步骤四：所有字符转为大写
           // $result = strtoupper($string);
            return $string;
    }
    public function httpRequest($url="",$method="POST",$request=[],$header=[]){
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            if(!$header){
                $header=[
                    'Accesstoken'=>'',
                    'Appid'=>'',
                    'Keyid'=>'',
                    'Nonce'=>'',
                    'Time'=>'',
                    'Sign'=>'',
                ];
            }
            $header['Accesstoken']=isset($header['Accesstoken'])?$header['Accesstoken']:'';
            curl_setopt_array($curl, array(
              CURLOPT_URL => $url,
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => "",
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 30,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => $method,
              CURLOPT_POSTFIELDS => json_encode($request),
              CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
                "cache-control: no-cache",
                "Accesstoken:{$header['Accesstoken']}",
                "Appid:{$header['Appid']}",
                "Keyid:{$header['Keyid']}",
                "Nonce:{$header['Nonce']}",
                "Time:{$header['Time']}",
                "Sign:{$header['Sign']}",
                "AppKey:{$header['AppKey']}",
              ),
            ));
            $response = curl_exec($curl);
            $err = curl_error($curl);
            curl_close($curl);
            if ($err) {
              return ['code'=>1,'msg'=>"cURL Error #:" . $err];
            } else {
              return json_decode($response,1);
            }
    }
}