<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Exception;
use think\Log;
use Redis;

/**
 * 实时音视频回调
 */
class Tentrtc extends Api
{
    protected $noNeedLogin = ['callback'];
    protected $noNeedRight = ['*'];

    /**
     * 支付回调
     */
    public function callback()
    {
        try {
            $header = $this->request->header();
            $body = file_get_contents('php://input');
            // 获取body参数
            $aRequest = json_decode($body, true);

            // 签名验证
            if ($this->verifyRoomApiSign($body, $header['sign']) == false) {
                Log::write(sprintf('%s,腾讯云回调,签名验证失败:%s', __METHOD__, var_export($body, true)), 'error');
                $this->error('签名验证失败');
            }

            $roomId = $aRequest['EventInfo']['RoomId'];

            switch ($aRequest['EventType']) {
                case 103:// 进入房间
                    $redis = new Redis();
                    $redisconfig = config("redis");
                    $redis->connect($redisconfig["host"], $redisconfig["port"]);
                    if ($redisconfig['redis_pwd']) {
                        $redis->auth($redisconfig['redis_pwd']);
                    }
                    if($redisconfig['redis_selectdb'] > 0){
                        $redis->select($redisconfig['redis_selectdb']);
                    }

                    $userId = $aRequest['EventInfo']['UserId'];
                    $redis->hSet("online_" . $roomId, $userId, $userId);

                    // 记录在线用户在房间情况
                    $redis->hSet("livingUser",$userId,$roomId);

                    // 更新房间在线状态
                    $partyInfo = $redis->get("party_" . $roomId);
                    if ($partyInfo) {
                        $partyInfo = json_decode($partyInfo, true);
                        if ($partyInfo["is_online"] != 1) {
                            $partyInfo["is_online"] = 1;
                            $redis->set("party_" . $roomId, json_encode($partyInfo));
                            \app\common\model\Party::update(["is_online" => 1], ["id" => $roomId]);
                        }
                    }

                    // 更新房间在线状态
                    $liveInfo = $redis->get("live_" . $roomId);
                    if ($liveInfo) {
                        $liveInfo = json_decode($liveInfo, true);
                        if ($liveInfo["is_online"] != 1) {
                            $liveInfo["is_online"] = 1;
                            $redis->set("live_" . $roomId, json_encode($liveInfo));
                            \app\common\model\Party::update(["is_online" => 1], ["id" => $roomId]);
                        }
                    }
                    break;
                case 104: // 退出房间
                    $redis = new Redis();
                    $redisconfig = config("redis");
                    $redis->connect($redisconfig["host"], $redisconfig["port"]);
                    if ($redisconfig['redis_pwd']) {
                        $redis->auth($redisconfig['redis_pwd']);
                    }
                    if($redisconfig['redis_selectdb'] > 0){
                        $redis->select($redisconfig['redis_selectdb']);
                    }

                    $userId = $aRequest['EventInfo']['UserId'];
                    $redis->HDel("online_" . $roomId, $userId);

                    // 扣除在线用户在房间情况
                    $redis->hDel("livingUser",$userId);

                    // 更新房间在线状态
                    $partyInfo = $redis->get("party_" . $roomId);
                    if ($partyInfo) {
                        $partyInfo = json_decode($partyInfo, true);
                        $memCount = count($redis->hGetAll("online_" . $roomId));
                        if ($memCount <= 0) {
                            $partyInfo["is_online"] = 0;
                            $redis->set("party_" . $roomId, json_encode($partyInfo));
                            \app\common\model\Party::update(["is_online" => 0], ["id" => $roomId]);
                        }
                    }

                    $liveInfo = $redis->get("live_" . $roomId);
                    if ($liveInfo) {
                        $liveInfo = json_decode($liveInfo, true);
                        $memCount = count($redis->hGetAll("online_" . $roomId));
                        if ($memCount <= 0) {
                            $liveInfo["is_online"] = 0;
                            $redis->set("live_" . $roomId, json_encode($liveInfo));
                            \app\common\model\Party::update(["is_online" => 0], ["id" => $roomId]);
                        }
                    }
                    break;
                default:
                    break;
            }

            json(0);
            exit;

        } catch (Exception $e) {
            Log::write(sprintf('%s:系统错误: %s IN: %s LINE: %s', __METHOD__, $e->getMessage(), $e->getFile(), $e->getLine()), 'error');

            $this->error(['code' => 9999, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 实时音视频验签
     */
    private function verifyRoomApiSign($aInput, $headerSign)
    {
        $callbackKey = 'c527c7078f47ba4d';


        $sign = hash_hmac('sha256', $aInput, $callbackKey, true);
        $sign = rtrim(base64_encode($sign));
        if ($sign == $headerSign) {
            return true;
        } else {
            return false;
        }
    }
}