<?php

namespace App\Http\Controllers\Callbacks;

use App\Events\ImSendMsg;
use App\Http\Controllers\Controller;
use App\Managers\IMManager;
use App\Models\User\UserModel;
use App\Services\IM\CustomElem;
use App\Utils\ImUtil;
use Illuminate\Http\Request;

class TencentIMController extends Controller
{
    protected $imManager;

    public function __construct(IMManager $imManager)
    {
        $this->imManager = $imManager;
    }

    /**
     * 单聊消息发送后
     * @param  Request  $request
     * @return array
     */
    public function singleMessageSent(Request $request)
    {
        $data = $request->all();

        $errorCode = 0;

        switch ($data['CallbackCommand']) {
            case 'C2C.CallbackBeforeSendMsg':
                $fromAccount = $data['From_Account'];
                $toAccount = $data['To_Account'];

                if (!$this->imManager->canIm($fromAccount, $toAccount)) {
                    $errorCode = 1;
                }
                break;
            case 'C2C.CallbackAfterSendMsg':
                $fromAccount = $data['From_Account'];
                $toAccount = $data['To_Account'];
                $msgRandom = $data['MsgRandom'];
                $msgTime = $data['MsgTime'];
                $msgSeq = $data['MsgSeq'];

                $discardedMsgType = array(
                    'EventReceiveSystemMsg',
                    'EventFriendApply',
                    'EventAgreeFriendApply',
                    'EventRefuseRefuseFriendApply',
                    'EventPairApply',
                    'EventAgreePairApply',
                    'EventRefuseRefusePairApply',
                    'EventBeContact',
                    'EventBeFriend'
                );
                $messageElem = $data['MsgBody'][0];
                $msgType = $messageElem['MsgType'];
                if ('TIMCustomElem' == $msgType) {
                    $customMsgType = $messageElem['Data']['MsgType'];
                    if (in_array($customMsgType, $discardedMsgType)) {
                        break;
                    }
                }

                event(new ImSendMsg($fromAccount, $toAccount, floor($msgTime / 1000), $data));

                $this->imManager->createUserLatestMessageByAccount(
                    $fromAccount,
                    $fromAccount,
                    $toAccount,
                    $msgTime,
                    $msgRandom,
                    $msgSeq,
                    $data,
                    true
                );
                $this->imManager->createUserLatestMessageByAccount(
                    $toAccount,
                    $fromAccount,
                    $toAccount,
                    $msgTime,
                    $msgRandom,
                    $msgSeq,
                    $data
                );
                break;
        }

        return [
            'ActionStatus' => 'OK',
            'ErrorInfo' => '',
            'ErrorCode' => $errorCode,
        ];


//        [2019-09-28 19:28:20] release.INFO: array (
//        'MsgBody' =>
//            array (
//                0 =>
//                    array (
//                        'MsgType' => 'TIMSoundElem',
//                        'MsgContent' =>
//                            array (
//                                'Size' => 62351,
//                                'Second' => 1,
//                                'Url' => 'https://1234-5678187359-1253735226.cos.ap-shanghai.myqcloud.com/abc123/c9be9d32c05bfb77b3edafa4312c6c7d',
//                                'Download_Flag' => 2,
//                            ),
//                    ),
//                1 =>
//                    array (
//                        'MsgType' => 'TIMTextElem',
//                        'MsgContent' =>
//                            array (
//                                'Text' => 'xxxx',
//                            ),
//                    ),
//                  2 =>
//                     array(
//                         "MsgType": "TIMCustomElem",
//                         "MsgContent": {
//        "Data": "message",
//        "Desc": "notification",
//        "Ext": "url",
//        "Sound": "dingdong.aiff"
//    }
//                     )
//            ),
//        'CallbackCommand' => 'C2C.CallbackAfterSendMsg',
//        'From_Account' => 'test',
//        'To_Account' => 'test1',
//        'MsgRandom' => 9499893,
//        'MsgSeq' => 1547306453,
//        'MsgTime' => 1569670099,
//        'ClientIP' => '183.159.197.167',
//        'OptPlatform' => 'RESTAPI',
//        'SdkAppid' => '1400263610',
//        'contenttype' => 'json',
//    )
    }

    /**
     * IM推送系统消息RPC
     * @param  Request  $request
     * @throws \Exception
     */
    public function sendSystemMessage(Request $request)
    {
        $data = $request->all();

        $uid = $data['toUid'];
        $type = $data['type'];

        switch ($type) {
            case 5:
                $fromAccount = "sys_notice_xcx";
                break;
            case 20:
                $fromAccount = "sys_notice_app";
                break;
            case 13:
            case 14:
            default:
                return;
        }

        $imUtil = new ImUtil();
        $sendUser = UserModel::whereUid($uid)->first(['uid', 'im_account']);
        if ($sendUser && $sendUser->im_account) {
            $message = new CustomElem('EventReceiveSystemMsg');
            $imUtil->sendMessage($fromAccount, $sendUser->im_account, $message->toArray());
        }
    }
}
