<?php

namespace app\api\controller;

use think\facade\Db;
use think\facade\Lang;
use GatewayClient\Gateway;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Live\V20180801\LiveClient;
use TencentCloud\Live\V20180801\Models\DescribeLiveStreamStateRequest;
use AlibabaCloud\Client\AlibabaCloud;

/**
 * ============================================================================
 * DSKMS多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 虚拟订单控制器
 */
class MemberLive extends MobileMember {

    public function initialize() {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'home/lang/' . config('lang.default_lang') . '/live.lang.php');
    }

    /**
     * @api {POST} api/MemberLive/get_live_info 消息列表
     * @apiVersion 1.0.0
     * @apiGroup MemberLive
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     * 
     * @apiParam {Int} live_apply_id 直播id
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object} result.live_apply_info  直播信息
     * @apiSuccess {String} result.live_apply_info.live_apply_cover_image_url  直播图片封面地址
     * @apiSuccess {String} result.live_apply_info.live_apply_cover_video_url  直播视频封面地址
     * @apiSuccess {String} result.live_apply_info.live_apply_push_url  直播推流地址
     * @apiSuccess {String} result.live_apply_info.live_apply_play_url  直播拉流地址
     * @apiSuccess {String} result.live_apply_info.live_apply_user_avatar  主播头像
     * @apiSuccess {String} result.live_apply_info.live_apply_user_name  主播用户名
     * @apiSuccess {Int} result.live_apply_info.live_apply_fans  主播关注数
     * @apiSuccess {Int} result.live_apply_info.is_favorate  是否已关注
     * @apiSuccess {String} result.live_apply_info.instant_message_url  聊天websocket地址
     * @apiSuccess {Object} result.online_info  在线信息
     * @apiSuccess {Int} result.online_info.online_count  在线人数
     * @apiSuccess {String} result.online_info.online_list  在线列表
     * @apiSuccess {String} result.online_info.online_list.instant_message_from_avatar  在线用户头像
     * @apiSuccess {Int} result.online_info.online_list.instant_message_from_id  在线用户id
     * @apiSuccess {Int} result.online_info.online_list.instant_message_from_type  在线用户类型
     * @apiSuccess {String} result.online_info.online_list.instant_message_from_name  在线用户名称
     */
    public function get_live_info() {
        $live_apply_id = input('param.live_apply_id');
        if (!$live_apply_id) {
            ds_json_encode(10001, lang('param_error'));
        }

        //获取最近未结束的直播
        $live_apply_model = model('live_apply');
        $condition = array();
        $condition[] = array('live_apply_state', '=', 1);
        $condition[] = array('live_apply_end_time', '>', TIMESTAMP);
        $condition[] = array('live_apply_id', '=', $live_apply_id);
        $live_apply = $live_apply_model->getLiveApplyInfo($condition);
        if (!$live_apply) {
            ds_json_encode(10001, lang('live_not_exit'));
        }


        //判断当前流状态
        if (config('ds_config.video_type') == 'aliyun') {
            if (!config('ds_config.aliyun_live_push_domain')) {
                ds_json_encode(10001, lang('aliyun_live_push_domain_empty'));
            }
            if (!config('ds_config.aliyun_live_push_key')) {
                ds_json_encode(10001, lang('aliyun_live_push_key_empty'));
            }
            if (!config('ds_config.aliyun_live_play_domain')) {
                ds_json_encode(10001, lang('aliyun_live_play_domain_empty'));
            }
            if (!config('ds_config.aliyun_live_play_key')) {
                ds_json_encode(10001, lang('aliyun_live_play_key_empty'));
            }
            $regionId = 'cn-shanghai';
            AlibabaCloud::accessKeyClient(config('ds_config.aliyun_access_key_id'), config('ds_config.aliyun_access_key_secret'))
                    ->regionId($regionId)
                    ->asDefaultClient();

            try {
                $result = AlibabaCloud::rpc()
                        ->product('live')
                        // ->scheme('https') // https | http
                        ->version('2016-11-01')
                        ->action('DescribeLiveStreamsOnlineList')
                        ->method('POST')
                        ->host('live.aliyuncs.com')
                        ->options([
                            'query' => [
                                'RegionId' => $regionId,
                                'DomainName' => config('ds_config.aliyun_live_push_domain'),
                                'AppName' => "live",
                                'StreamName' => 'live_apply_' . $live_apply['live_apply_id'],
                                'PageSize' => "1",
                                'PageNum' => "1",
                                'QueryType' => "strict",
                            ],
                        ])
                        ->request();
                if (!$result->TotalNum) {
                    ds_json_encode(10001, '主播不在线：' . ($live_apply['live_apply_push_message'] ? $live_apply['live_apply_push_message'] : ''));
                }
            } catch (\Exception $e) {
                ds_json_encode(10001, $e->getMessage());
            }
        } else {
            if (!config('ds_config.live_push_domain')) {
                ds_json_encode(10001, lang('live_push_domain_empty'));
            }
            if (!config('ds_config.live_push_key')) {
                ds_json_encode(10001, lang('live_push_key_empty'));
            }
            if (!config('ds_config.live_play_domain')) {
                ds_json_encode(10001, lang('live_play_domain_empty'));
            }

            try {

                $cred = new Credential(config('ds_config.vod_tencent_secret_id'), config('ds_config.vod_tencent_secret_key'));
                $httpProfile = new HttpProfile();
                $httpProfile->setEndpoint("live.tencentcloudapi.com");

                $clientProfile = new ClientProfile();
                $clientProfile->setHttpProfile($httpProfile);
                $client = new LiveClient($cred, "", $clientProfile);

                $req = new DescribeLiveStreamStateRequest();

                $params = '{"AppName":"live","DomainName":"' . config('ds_config.live_push_domain') . '","StreamName":"' . 'live_apply_' . $live_apply['live_apply_id'] . '"}';
                $req->fromJsonString($params);


                $resp = $client->DescribeLiveStreamState($req);
            } catch (TencentCloudSDKException $e) {
                ds_json_encode(10001, $e->getMessage());
            }
            if ($resp->StreamState != 'active') {
                ds_json_encode(10001, lang('live_not_online') . ($live_apply['live_apply_push_message'] ? $live_apply['live_apply_push_message'] : ''));
            }
        }

        //生成推流url
        $live_apply['live_apply_push_url'] = model('live_apply')->getPushUrl('live_apply_' . $live_apply['live_apply_id'], $live_apply['live_apply_end_time']);
        //生成拉流url
        $live_apply['live_apply_play_url'] = model('live_apply')->getPlayUrl('live_apply_' . $live_apply['live_apply_id'], $live_apply['live_apply_end_time']);


        if ($live_apply['live_apply_play_time'] > TIMESTAMP) {
            ds_json_encode(10001, lang('live_not_begin'));
        }
        $extral_info = array();
        $live_apply['live_apply_cover_image_url'] = ds_get_pic(ATTACH_COMMON,config('ds_config.default_goods_image'));
        if ($live_apply['live_apply_cover_video']) {
            $live_apply['live_apply_cover_video_url'] = ds_get_pic( ATTACH_LIVE_APPLY . '/' . $live_apply['live_apply_user_id'] , $live_apply['live_apply_cover_video']);
        } elseif ($live_apply['live_apply_cover_image']) {
            $live_apply['live_apply_cover_image_url'] = ds_get_pic( ATTACH_LIVE_APPLY . '/' . $live_apply['live_apply_user_id'] , $live_apply['live_apply_cover_image']);
        }
        switch ($live_apply['live_apply_user_type']) {
            case 2:
                $store_model = model('store');
                $store_info = $store_model->getOneStore(array(array('store_id', '=', $live_apply['live_apply_user_id'])), 'store_id,store_collect,store_name,store_avatar');
                if (!$store_info) {
                    ds_json_encode(10001, lang('ds_store_is_not_exist'));
                }
                $live_apply['live_apply_user_avatar'] = get_store_logo($store_info['store_avatar']);
                $live_apply['live_apply_user_name'] = $store_info['store_name'];
                $live_apply['live_apply_fans'] = $store_info['store_collect'];
                $favorites_model = model('favorites');
                $c = (int) $favorites_model->getStoreFavoritesCountByStoreId($store_info['store_id'], $this->member_info['member_id']);
                $live_apply['is_favorate'] = $c > 0;
                break;
        }
        $online_info = false;
        if (config('ds_config.instant_message_register_url')) {
            // 设置GatewayWorker服务的Register服务ip和端口，请根据实际情况改成实际值(ip不能是0.0.0.0)
            try {
                Gateway::$registerAddress = config('ds_config.instant_message_register_url');
                $online_info = array(
                    'online_count' => Gateway::getClientIdCountByGroup('live_apply_' . $live_apply_id),
                    'online_list' => Gateway::getClientSessionsByGroup('live_apply_' . $live_apply_id),
                );
            } catch (\Exception $e) {
                $msg = $e->getMessage();
            }
        }
        $goods_commonid = Db::name('live_apply_goods')->where('live_apply_id', $live_apply_id)->column('goods_commonid');
        $goods_model = model('goods');
        if (!empty($goods_commonid)) {
            $goods_list = $goods_model->getGoodsUnionList(array(array('goodscommon.goods_commonid', 'in', $goods_commonid)), 'goods_id,goodscommon.goods_price,goodscommon.goods_name,goodscommon.goods_image', '', 'goodscommon.goods_commonid');
            foreach ($goods_list as $k => $v) {
                $goods_list[$k]['goods_image'] = goods_cthumb($v['goods_image']);
            }
            $live_apply['goods_list'] = $goods_list;
        }

        ds_json_encode(10000, '', array('live_apply_info' => array_merge($live_apply, $extral_info, array('instant_message_url' => config('ds_config.instant_message_gateway_url'))), 'online_info' => $online_info));
    }

    /**
     * @api {POST} api/MemberLive/get_live_info 消息列表
     * @apiVersion 1.0.0
     * @apiGroup MemberLive
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     * 
     * @apiParam {Int} live_apply_id 直播id
     * @apiParam {Int} client_id 客户端id
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    function join_live() {
        session('name');
        $live_apply_id = input('param.live_apply_id');
        $client_id = input('param.client_id');
        if (!config('ds_config.instant_message_register_url')) {
            ds_json_encode(10001, lang('instant_message_register_url_empty'));
        }
        $live_apply_model = model('live_apply');
        $condition = array();
        $condition[] = array('live_apply_state', '=', 1);
        $condition[] = array('live_apply_end_time', '>', TIMESTAMP);
        $condition[] = array('live_apply_id', '=', $live_apply_id);

        $live_apply = $live_apply_model->getLiveApplyInfo($condition);
        if (empty($live_apply)) {
            ds_json_encode(10001, lang('live_not_exit'));
        }

        // 设置GatewayWorker服务的Register服务ip和端口，请根据实际情况改成实际值(ip不能是0.0.0.0)
        try {
            Gateway::$registerAddress = config('ds_config.instant_message_register_url');
            // client_id与uid绑定
            Gateway::bindUid($client_id, '0:' . $this->member_info['member_id']);
            $online_item = array(
                'instant_message_from_avatar' => get_member_avatar_for_id($this->member_info['member_id']),
                'instant_message_from_id' => $this->member_info['member_id'],
                'instant_message_from_type' => 0,
                'instant_message_from_name' => $this->member_info['member_name']
            );
            Gateway::setSession($client_id, $online_item);
            // 加入某个群组（可调用多次加入多个群组）
            Gateway::joinGroup($client_id, 'live_apply_' . $live_apply_id);
            //更新在线人数
            Gateway::sendToGroup('live_apply_' . $live_apply_id, json_encode(array(
                'type' => 'join',
                'online_count' => Gateway::getClientIdCountByGroup('live_apply_' . $live_apply_id),
                'online_list' => Gateway::getClientSessionsByGroup('live_apply_' . $live_apply_id)
            )));
        } catch (\Exception $e) {
            ds_json_encode(10001, $e->getMessage());
        }
        Db::name('live_apply')->where('live_apply_id', $live_apply_id)->inc('live_apply_view_count')->update();
        ds_json_encode(10000, '');
    }

    /**
     * @api {POST} api/MemberLive/get_live_info 消息列表
     * @apiVersion 1.0.0
     * @apiGroup MemberLive
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     * 
     * @apiParam {Int} live_apply_id 直播id
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    function add_like() {
        $live_apply_id = input('param.live_apply_id');

        $live_apply_model = model('live_apply');
        $condition = array();
        $condition[] = array('live_apply_state', '=', 1);
        $condition[] = array('live_apply_end_time', '>', TIMESTAMP);
        $condition[] = array('live_apply_id', '=', $live_apply_id);

        $live_apply = $live_apply_model->getLiveApplyInfo($condition);
        if (empty($live_apply)) {
            ds_json_encode(10001, lang('live_not_exit'));
        }
        Db::name('live_apply')->where('live_apply_id', $live_apply_id)->inc('live_apply_like_count')->update();
        ds_json_encode(10000, '');
    }

    /**
     * @api {POST} api/MemberLive/get_live_info 消息列表
     * @apiVersion 1.0.0
     * @apiGroup MemberLive
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     * 
     * @apiParam {Int} live_apply_id 直播id
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    function add_gift() {
        $live_apply_id = input('param.live_apply_id');
        if (!config('ds_config.instant_message_register_url')) {
            ds_json_encode(10001, lang('instant_message_register_url_empty'));
        }
        $live_apply_model = model('live_apply');
        $condition = array();
        $condition[] = array('live_apply_state', '=', 1);
        $condition[] = array('live_apply_end_time', '>', TIMESTAMP);
        $condition[] = array('live_apply_id', '=', $live_apply_id);

        $live_apply = $live_apply_model->getLiveApplyInfo($condition);
        if (empty($live_apply)) {
            ds_json_encode(10001, lang('live_not_exit'));
        }
        if ($this->member_info['member_points'] < 100) {
            ds_json_encode(10001, lang('points_not_enough'));
        }
        $points_model = model('points');
        Db::startTrans();
        try {
            switch ($live_apply['live_apply_user_type']) {
                case 2:
                    $store_model = model('store');
                    $store_info = $store_model->getOneStore(array(array('store_id', '=', $live_apply['live_apply_user_id'])), 'member_id,member_name');
                    if (!$store_info) {
                        throw new \think\Exception(lang('ds_store_is_not_exist'), 10006);
                    }
                    $points_model->savePointslog('gift', array(
                        'pl_memberid' => $store_info['member_id'], 'pl_membername' => $store_info['member_name'], 'pl_desc' => $live_apply['live_apply_name'] . lang('live_present_rocket'), 'pl_points' => 100
                    ));
                    $points_model->savePointslog('gift', array(
                        'pl_memberid' => $this->member_info['member_id'], 'pl_membername' => $this->member_info['member_name'], 'pl_desc' => $live_apply['live_apply_name'] . lang('live_present_rocket'), 'pl_points' => -100
                    ));
                    break;
            }
        } catch (\Exception $e) {
            Db::rollback();
            ds_json_encode(10001, $e->getMessage());
        }
        Db::commit();
        // 设置GatewayWorker服务的Register服务ip和端口，请根据实际情况改成实际值(ip不能是0.0.0.0)
        try {
            Gateway::$registerAddress = config('ds_config.instant_message_register_url');

            Gateway::sendToGroup('live_apply_' . $live_apply_id, json_encode(array(
                'type' => 'gift',
                'gift_num' => 1,
                'member' => array(
                    'member_id' => $this->member_info['member_id'],
                    'member_name' => $this->member_info['member_name'],
                    'member_avatar' => get_member_avatar_for_id($this->member_info['member_id'])
                ),
                'online_count' => Gateway::getClientIdCountByGroup('live_apply_' . $live_apply_id),
                'online_list' => Gateway::getClientSessionsByGroup('live_apply_' . $live_apply_id)
            )));
        } catch (\Exception $e) {
            ds_json_encode(10001, $e->getMessage());
        }
        ds_json_encode(10000, '');
    }

    /**
     * @api {POST} api/MemberLive/get_live_info 消息列表
     * @apiVersion 1.0.0
     * @apiGroup MemberLive
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     * 
     * @apiParam {Int} live_apply_id 直播id
     * @apiParam {Int} client_id 客户端id
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    function leave_live() {
        $live_apply_id = input('param.live_apply_id');
        $client_id = input('param.client_id');
        if (!config('ds_config.instant_message_register_url')) {
            ds_json_encode(10001, lang('instant_message_register_url_empty'));
        }
        try {
            // 设置GatewayWorker服务的Register服务ip和端口，请根据实际情况改成实际值(ip不能是0.0.0.0)
            Gateway::$registerAddress = config('ds_config.instant_message_register_url');
            // client_id与uid绑定
            Gateway::unbindUid($client_id, '0:' . $this->member_info['member_id']);
            // 加入某个群组（可调用多次加入多个群组）
            Gateway::leaveGroup($client_id, 'live_apply_' . $live_apply_id);
            //更新在线人数
            Gateway::sendToGroup('live_apply_' . $live_apply_id, json_encode(array(
                'type' => 'leave',
                'online_count' => Gateway::getClientIdCountByGroup('live_apply_' . $live_apply_id),
                'online_list' => Gateway::getClientSessionsByGroup('live_apply_' . $live_apply_id),
            )));
        } catch (\Exception $e) {
            ds_json_encode(10001, $e->getMessage());
        }
        ds_json_encode(10000, '');
    }

}
