<?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) {
        return true;
        $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
            ],
        ];
        $tencentObj->toSend($data);

    }


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