<?php

namespace app\common\library;

use getusersig\getusersig;
use tencentim\tencentim;

class Tenim
{

    /**
     * 发送消息给某人-接口调用
     */
    public function sendToUser() {
        $from_user = '2';// 发送者
        $to_user = '294';// 接收者
        $message = 'hello许犇';// 接收者
        if(!$from_user || !$to_user || !$message) $this->error("参数缺失!");
        $this->sendMessageToUser($from_user,$to_user,$message);
    }


    /**
     * 发送消息给某人
     */
    //https://console.tim.qq.com/v4/openim/sendmsg?sdkappid=88888888&identifier=admin&usersig=xxx&random=99999999&contenttype=json
    public function sendMessageToUser($from_user,$to_user,$message) {

        $random = rand(10000000,99999999);
        $usersig = $this->usersig("administrator");
        // 获取配置信息
        $config = config("tencent_im");
        $url = "https://console.tim.qq.com/v4/openim/sendmsg";
        $url .= "?sdkappid=".$config["sdkappid"];
        $url .= "&identifier=administrator";
        $url .= "&usersig=".$usersig;
        $url .= "&random=".$random;
        $url .= "&contenttype=json";
        $tencentObj = new tencentim($url);

        $data = [];
        $data["SyncOtherMachine"] = 1;
        $data["From_Account"] = (string)$from_user;
        $data["To_Account"] = (string)$to_user;
        $data["MsgRandom"] = rand(1000000,9999999);
        $data["MsgTimeStamp"] = time();

        $data["MsgBody"][] = [
            "MsgType" => "TIMTextElem",
            "MsgContent" => [
                "Text"=> $message
            ],
        ];
        $res = $tencentObj->toSend($data);

        if (empty($res['ActionStatus']) || $res['ActionStatus'] != 'OK') {
            $error = !empty($res['ErrorInfo']) ? 'im error:'.$res['ErrorInfo'] : 'im error';
            return $error;
        }

        return true;

    }

    /**
     * 发送自定义消息给某人
     */
    public function sendCustomMessageToUser($from_user,$to_user,$message) {

        $random = rand(10000000,99999999);
        $usersig = $this->usersig("administrator");
        // 获取配置信息
        $config = config("tencent_im");
        $url = "https://console.tim.qq.com/v4/openim/sendmsg";
        $url .= "?sdkappid=".$config["sdkappid"];
        $url .= "&identifier=administrator";
        $url .= "&usersig=".$usersig;
        $url .= "&random=".$random;
        $url .= "&contenttype=json";
        $tencentObj = new tencentim($url);

        $data = [];
        $data["SyncOtherMachine"] = 1;//1=消息同步至发送方,2=消息不同步至发送方
        $data["From_Account"] = (string)$from_user;
        $data["To_Account"] = (string)$to_user;
        $data["MsgRandom"] = rand(1000000,9999999);
        $data["MsgTimeStamp"] = time();

        $data["MsgBody"][] = [
            "MsgType" => "TIMCustomElem",
            "MsgContent" => [
                "Data" => json_encode($message),
                "Desc" => $message['name'],
                "Ext"  => $message['name'],
                "Sound"=> '',
            ],
        ];
        $data['CloudCustomData'] = $message['id'];
        $res = $tencentObj->toSend($data);

        if (empty($res['ActionStatus']) || $res['ActionStatus'] != 'OK') {
            $error = !empty($res['ErrorInfo']) ? 'im error:'.$res['ErrorInfo'] : 'im error';
            return $error;
        }

        return true;

    }

    //注册用户到im
    public function register($userid,$nickname,$avatar) {

        $random = rand(10000000,99999999);
        $usersig = $this->usersig("administrator");
        //dump($usersig);
        // 获取配置信息
        $config = config("tencent_im");
        $url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import";
        $url .= "?sdkappid=".$config["sdkappid"];
        $url .= "&identifier=administrator";
        $url .= "&usersig=".$usersig;
        $url .= "&random=".$random;
        $url .= "&contenttype=json";
        $tencentObj = new tencentim($url);

        $data = [
            'UserID' => $userid,
            'Nick'  => $nickname,
            'FaceUrl' => $avatar,
        ];

        $res = $tencentObj->toSend($data);

        if (empty($res['ActionStatus']) || $res['ActionStatus'] != 'OK') {
            $error = !empty($res['ErrorInfo']) ? 'im error:'.$res['ErrorInfo'] : 'im error';
            return $error;
        }

        return true;
    }

    //某个用户是否im在线
    //https://cloud.tencent.com/document/product/269/2566
    /*  QueryResult.Status
    返回的用户状态,目前支持的状态有:
    前台运行状态(Online):客户端登录后和即时通信 IM 后台有长连接
    后台运行状态(PushOnline):iOS 和 Android 进程被 kill 或因网络问题掉线,进入 PushOnline 状态,此时仍然可以接收消息的离线推送。客户端切到后台,但是进程未被手机操作系统 kill 掉时,此时状态仍是 Online
    未登录状态(Offline):客户端主动退出登录或者客户端自上一次登录起7天之内未登录过
    如果用户是多终端登录,则只要有一个终端的状态是 Online ,该字段值就是 Online
    */
    public function is_online($userid){
        $random = rand(10000000,99999999);
        $usersig = $this->usersig("administrator");
        //dump($usersig);
        // 获取配置信息
        $config = config("tencent_im");
        $url = "https://console.tim.qq.com/v4/openim/query_online_status";
        $url .= "?sdkappid=".$config["sdkappid"];
        $url .= "&identifier=administrator";
        $url .= "&usersig=".$usersig;
        $url .= "&random=".$random;
        $url .= "&contenttype=json";
        $tencentObj = new tencentim($url);

        $data = [
            'To_Account' => [$userid],
        ];

        $res = $tencentObj->toSend($data);

        if (!empty($res['ActionStatus']) && $res['ActionStatus'] == 'OK') {
            if(    isset($res['QueryResult'][0]['To_Account'])
                && isset($res['QueryResult'][0]['Status'])
                && $res['QueryResult'][0]['To_Account'] == $userid
                && $res['QueryResult'][0]['Status'] == 'Online'){
                return true;
            }
        }

        return false;
    }



    /**
     * 获取usersig签名-具体操作
     */
    public function usersig($user_id) {
        // 获取配置信息
        $config = config("tencent_im");
        $usersigObj = new getusersig($config["sdkappid"],$config["key"]);
        $usersig = $usersigObj->genUserSig($user_id);
        return $usersig;
    }
}