<?php

namespace app\common\controller;

use think\Controller;
use GuzzleHttp\Client;

class Tim extends Controller
{
	protected $sdkappid;
	protected $key;
	protected $api;
	protected $identifier = 'administrator';
    // 错误信息
    protected $_error = '';

	public function __construct(){
		vendor('autoload');
		$this->sdkappid = config('tim.sdkappid');
		$this->key = config('tim.key');
		$this->api = new \Tencent\TLSSigAPIv2($this->sdkappid, $this->key);
	}

	/**
	 * 获取签名
	 */
	public function getSig($identifier){
		return $this->api->genUserSig((string)$identifier);
	}

	/**
	 * 导入单个账号
	 */
	public function accountImport($user_id,$nickname,$head_photo='http://www.qq.com'){
		$usersig = $this->getSig($this->identifier);
		$url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid={$this->sdkappid}&identifier={$this->identifier}&usersig={$usersig}&random=99999999&contenttype=json";
		$data = [
			'Identifier' => (string)$user_id,
			'Nick' => $nickname,
			'FaceUrl' => $head_photo,
		];
		$client = new Client();
		$response = $client->request('POST',$url,['json'=>$data]);
		return json_decode($response->getBody()->getContents(),true);
	}

    /**
     * 导入用户账号
     */
    public function importUser($user){
        //导入腾讯im账号(先查询是否存在,不存在就导入)
        $portrait_get_res = $this->portraitGet('user_'.$user['id']);//查询
        if(!isset($portrait_get_res['ErrorCode'])){
            $this->setError('拉取资料接口报错');
            return false;
        }
        if($portrait_get_res['ErrorCode'] != 0 && $portrait_get_res['ErrorCode'] != 40003){
            $this->setError($portrait_get_res['ErrorInfo']);
            return false;
        }
        if($portrait_get_res['UserProfileItem'][0]['ResultCode'] == 40003){
            $import_res = $this->accountImport('user_'.$user['id'],$user['nickname'],$user['avatar']);//导入
            if(!isset($import_res['ErrorCode'])){
                $this->setError('导入账号失败');
                return false;
            }
            if($import_res['ErrorCode'] != 0){
                $this->setError($import_res['ErrorInfo']);
                return false;
            }
        }
        return true;
    }

    /**
     * 导入医生账号
     */
    public function importDoctor($doctor){
        //导入腾讯im账号(先查询是否存在,不存在就导入)
        $portrait_get_res = $this->portraitGet('doctor_'.$doctor['id']);//查询
        if(!isset($portrait_get_res['ErrorCode'])){
            $this->setError('拉取资料接口报错');
            return false;
        }
        if($portrait_get_res['ErrorCode'] != 0 && $portrait_get_res['ErrorCode'] != 40003){
            $this->setError($portrait_get_res['ErrorInfo']);
            return false;
        }
        if($portrait_get_res['UserProfileItem'][0]['ResultCode'] == 40003){
            $import_res = $this->accountImport('doctor_'.$doctor['id'],$doctor['nickname'],$doctor['avatar']);//导入
            if(!isset($import_res['ErrorCode'])){
                $this->setError('导入账号失败');
                return false;
            }
            if($import_res['ErrorCode'] != 0){
                $this->setError($import_res['ErrorInfo']);
                return false;
            }
        }
        return true;
    }

	/**
	 * 帐号删除
	 */
	public function accountDelete($user_id1){
		$usersig = $this->getSig($this->identifier);
		$url = "https://console.tim.qq.com/v4/im_open_login_svc/account_delete?sdkappid={$this->sdkappid}&identifier={$this->identifier}&usersig={$usersig}&random=99999999&contenttype=json";
		$data = [
			'DeleteItem' => [
				["UserID"=>(string)$user_id1],
			]
		];
        $client = new Client();
        $response = $client->request('POST',$url,['json'=>$data]);
		$res = json_decode($response->getBody()->getContents(),true);
		if(!isset($res['ErrorCode'])){
            $this->setError('帐号删除失败');
            return false;
		}
		if($res['ErrorCode'] != 0){
            $this->setError($res['ErrorInfo']);
            return false;
		}
		return true;
	}

	/**
	 * 拉取资料
	 */
	public function portraitGet($user_id){
		$usersig = $this->getSig($this->identifier);
		$url = "https://console.tim.qq.com/v4/profile/portrait_get?sdkappid={$this->sdkappid}&identifier={$this->identifier}&usersig={$usersig}&random=99999999&contenttype=json";
		$data = [
			'To_Account' => [(string)$user_id],
			'TagList' => ['Tag_Profile_IM_Nick'],
		];
        $client = new Client();
        $response = $client->request('POST',$url,['json'=>$data]);
		return json_decode($response->getBody()->getContents(),true);
	}

    /**
     * 设置资料
     */
    public function portraitSet($user_id,$profile_item){
        $usersig = $this->getSig($this->identifier);
        $url = "https://console.tim.qq.com/v4/profile/portrait_set?sdkappid={$this->sdkappid}&identifier={$this->identifier}&usersig={$usersig}&random=99999999&contenttype=json";
        $data = [
            "From_Account" => (string)$user_id,
            "ProfileItem" => $profile_item
        ];
        $client = new Client();
        $response = $client->request('POST',$url,['json'=>$data]);
        $res = json_decode($response->getBody()->getContents(),true);
        if(!isset($res['ErrorCode'])){
            $this->setError('设置资料失败');
            return false;
        }
        if($res['ErrorCode'] != 0){
            $this->setError($res['ErrorInfo']);
            return false;
        }
        return true;
    }

    /**
     * 加好友
     */
    public function friendAdd($user_id1,$add_friend_item){
        $usersig = $this->getSig($this->identifier);
        $url = "https://console.tim.qq.com/v4/sns/friend_add?sdkappid={$this->sdkappid}&identifier={$this->identifier}&usersig={$usersig}&random=99999999&contenttype=json";
        $data = [
            "From_Account" => (string)$user_id1,
            "AddFriendItem" => $add_friend_item
        ];
        $client = new Client();
        $response = $client->request('POST',$url,['json'=>$data]);
        $res = json_decode($response->getBody()->getContents(),true);
        if(!isset($res['ErrorCode'])){
            $this->setError('加好友失败');
            return false;
        }
        if($res['ErrorCode'] != 0){
            $this->setError($res['ErrorInfo']);
            return false;
        }
        return true;
    }

	/**
	 * 拉取好友
	 */
	public function friendGet($user_id1){
		$usersig = $this->getSig($this->identifier);
		$url = "https://console.tim.qq.com/v4/sns/friend_get?sdkappid={$this->sdkappid}&identifier={$this->identifier}&usersig={$usersig}&random=99999999&contenttype=json";
		$data = [
			'From_Account' => (string)$user_id1,
			'StartIndex' => 0,
			'StandardSequence' => 0,
			'CustomSequence' => 0
		];
        $client = new Client();
        $response = $client->request('POST',$url,['json'=>$data]);
        return json_decode($response->getBody()->getContents(),true);
	}

	/**
	 * 删除好友
	 */
	public function friendDelete($user_id1,$user_id2){
		$usersig = $this->getSig($this->identifier);
		$url = "https://console.tim.qq.com/v4/sns/friend_delete?sdkappid={$this->sdkappid}&identifier={$this->identifier}&usersig={$usersig}&random=99999999&contenttype=json";
		$data = [
			'From_Account' => (string)$user_id1,
			'To_Account' => [(string)$user_id2],
			'DeleteType' => 'Delete_Type_Both',//双向删除好友
		];
        $client = new Client();
        $response = $client->request('POST',$url,['json'=>$data]);
		$res = json_decode($response->getBody()->getContents(),true);
		if(!isset($res['ErrorCode'])){
            $this->setError('删除好友失败');
            return false;
		}
		if($res['ErrorCode'] != 0){
            $this->setError($res['ErrorInfo']);
            return false;
		}
		return true;
	}

	/**
	 * 发送信息
	 */
	public function sendMsg($user_id1,$user_id2,$msg){
		$usersig = $this->getSig($this->identifier);
		$url = "https://console.tim.qq.com/v4/openim/sendmsg?sdkappid={$this->sdkappid}&identifier={$this->identifier}&usersig={$usersig}&random=99999999&contenttype=json";
		$data = [
			'SyncOtherMachine' => 1,
			'From_Account' => (string)$user_id1,
			'To_Account' => (string)$user_id2,
			'MsgLifeTime' => 60,
			'MsgRandom' => 1287657,
			'MsgTimeStamp' => 1557387418,
			'MsgBody' => [
				[
					"MsgType" => "TIMTextElem",
		            "MsgContent" => [
		                "Text" => (string)$msg
		            ]
				]
			]
		];
        $client = new Client();
        $response = $client->request('POST',$url,['json'=>$data]);
        $res = json_decode($response->getBody()->getContents(),true);
        if(!isset($res['ErrorCode'])){
            $this->setError('发送信息失败');
            return false;
        }
        if($res['ErrorCode'] != 0){
            $this->setError($res['ErrorInfo']);
            return false;
        }
        return true;
	}

    /**
     * 查询单聊消息
     */
    public function getRoamMsg($user_id1,$user_id2,$min_time,$max_time,$max_cnt=100){
        $usersig = $this->getSig($this->identifier);
        $url = "https://console.tim.qq.com/v4/openim/admin_getroammsg?sdkappid={$this->sdkappid}&identifier={$this->identifier}&usersig={$usersig}&random=99999999&contenttype=json";
        $data = [
            "From_Account" => (string)$user_id1,
            "To_Account" => (string)$user_id2,
            "MaxCnt" => $max_cnt,
            "MinTime" => $min_time,
            "MaxTime" => $max_time
        ];
        $client = new Client();
        $response = $client->request('POST',$url,['json'=>$data]);
        return json_decode($response->getBody()->getContents(),true);
    }

    /**
     * 查询单聊未读消息计数
     */
    public function getNoreadMsgNum($user_id1,$user_id2){
        $usersig = $this->getSig($this->identifier);
        $url = "https://console.tim.qq.com/v4/openim/get_c2c_unread_msg_num?sdkappid={$this->sdkappid}&identifier={$this->identifier}&usersig={$usersig}&random=99999999&contenttype=json";
        $data = [
            "To_Account" => (string)$user_id1,
            "Peer_Account" => [
                (string)$user_id2,
            ]
        ];
        $client = new Client();
        $response = $client->request('POST',$url,['json'=>$data]);
        return json_decode($response->getBody()->getContents(),true);
    }

    /**
     * 校验好友
     */
    public function friendCheck($user_id1,$friend_id_arr){
        $usersig = $this->getSig($this->identifier);
        $url = "https://console.tim.qq.com/v4/sns/friend_check?sdkappid={$this->sdkappid}&identifier={$this->identifier}&usersig={$usersig}&random=99999999&contenttype=json";
        $data = [
            "From_Account" => (string)$user_id1,
            "To_Account" => $friend_id_arr,
            "CheckType" => "CheckResult_Type_Both"
        ];
        $client = new Client();
        $response = $client->request('POST',$url,['json'=>$data]);
        return json_decode($response->getBody()->getContents(),true);
    }

    /**
     * 设置错误信息
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     */
    public function getError()
    {
        return $this->_error ? __($this->_error) : '';
    }
}