<?php
// +—————————————————————————————————————————————————————————————————————
// | Created by Yunbao
// +—————————————————————————————————————————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +—————————————————————————————————————————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +—————————————————————————————————————————————————————————————————————
// | Date: 2022-02-17
// +—————————————————————————————————————————————————————————————————————
/**
 * 直播列表
 */
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Db;

// 根据腾讯云sdk请求 创建直播拉流
use TencentCloud\Live\V20180801\Models\CreateLivePullStreamTaskRequest;
use TencentCloud\Live\V20180801\Models\DeleteLivePullStreamTaskRequest;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Live\V20180801\LiveClient;
use think\Exception;
use think\exception\PDOException;

class LiveingController extends AdminbaseController {
    protected function getLiveClass(){

        $liveclass=Db::name("live_class")->order('list_order asc, id desc')->column('id,name');

        return $liveclass;
    }
    
    protected function getTypes($k=''){
        $type=[
            '0'=>'普通房间',
            '1'=>'密码房间',
            '2'=>'门票房间',
            '3'=>'计时房间',
        ];
        
        if($k==''){
            return $type;
        }
        return $type[$k];
    }
    
    public function index(){
        $data = $this->request->param();
        $map=[];
        $map[]=['islive','=',1];
        $start_time=isset($data['start_time']) ? $data['start_time']: '';
        $end_time=isset($data['end_time']) ? $data['end_time']: '';
        
        if($start_time!=""){
           $map[]=['starttime','>=',strtotime($start_time)];
        }

        if($end_time!=""){
           $map[]=['starttime','<=',strtotime($end_time) + 60*60*24];
        }
        
        $uid=isset($data['uid']) ? $data['uid']: '';
        if($uid!=''){
            $lianguid=getLianguser($uid);
            if($lianguid){
                $map[]=['uid',['=',$uid],['in',$lianguid],'or'];
            }else{
                $map[]=['uid','=',$uid];
            }
        }
        
        $this->configpri=getConfigPri();
            

        $lists = Db::name("live")
                ->where($map)
                ->order("starttime DESC")
                ->paginate(20);
        
        $lists->each(function($v,$k){

             $v['userinfo']=getUserInfo($v['uid']);
             $where=[];
             $where['action']=1;
             $where['touid']=$v['uid'];
             $where['showid']=$v['showid'];
             /* 本场总收益 */
             $totalcoin=Db::name("user_coinrecord")->where($where)->sum('totalcoin');
             if(!$totalcoin){
                $totalcoin=0;
             }
             /* 送礼物总人数 */
             $total_nums=Db::name("user_coinrecord")->where($where)->group("uid")->count();
             if(!$total_nums){
                $total_nums=0;
             }
             /* 人均 */
             $total_average=0;
             if($totalcoin && $total_nums){
                $total_average=round($totalcoin/$total_nums,2);
             }
             
             /* 人数 */
            $nums=zSize('user_'.$v['stream']);
            
            $v['totalcoin']=$totalcoin;
            $v['total_nums']=$total_nums;
            $v['total_average']=$total_average;
            $v['nums']=$nums;
            
            if($v['isvideo']==0 && $this->configpri['cdn_switch']!=5){
                $v['pull']=PrivateKeyA('rtmp',$v['stream'],0);
            }
                
            return $v;           
        });
        
        $lists->appends($data);
        $page = $lists->render();

        $liveclass=$this->getLiveClass();
        $liveclass[0]='默认分类';

        $this->assign('lists', $lists);

        $this->assign("page", $page);
        
        $this->assign("liveclass", $liveclass);
        
        $this->assign("type", $this->getTypes());
        
        return $this->fetch();

    }

    public function getLivePushUrl(){

        $uid = $_POST['uid'] ?? ''; // 从 POST 请求中获取 uid 值

        if (empty($uid)) {
            echo "请输入UID";
        } elseif (!is_numeric($uid)) {
            echo "UID必须是数字";
        } else {

            $tx_push = cmf_get_option('configpri')['tx_push'];
            $push_url = 'rtmp://' . $tx_push.'/live/'.$uid;

            $pull_key = cmf_get_option('configpri')['tx_play_key'];

            require CMF_ROOT . 'vendor/tencentcloud/vendor/autoload.php';

            try {
                // 为了保护密钥安全,建议将密钥设置在环境变量中或者配置文件中。
                // 硬编码密钥到代码中有可能随代码泄露而暴露,有安全隐患,并不推荐。
                // $cred = new Credential("SecretId", "SecretKey");
                $cred = new Credential("AKID575vicM9rU6iBiWJNi09HF8xhMxOk4Od",
                    "MiDkHwgOFpMpGf2KXcZIo9MYY5qnmhU5");

                // 实例化一个http选项,可选的,没有特殊需求可以跳过
                $httpProfile = new HttpProfile();
                $httpProfile->setEndpoint( "live.tencentcloudapi.com" );

                // 实例化一个client选项,可选的,没有特殊需求可以跳过
                $clientProfile = new ClientProfile();
                $clientProfile->setHttpProfile( $httpProfile );
                // 实例化要请求产品的client对象,clientProfile是可选的
                $client = new LiveClient( $cred, "ap-bangkok", $clientProfile );

                // 实例化一个请求对象,每个接口都会对应一个request对象
                $req = new CreateLivePullStreamTaskRequest();

                // https://umotool.com  推流域名
                $SourceUrls = ['https://umotool.com/live/'.$uid.'.flv'];

                $timestamp = time();
                //播放链接限制10分钟 60*10  一天 60*60*24
                $end_timestamp     = time() + 60*60*24;

                $txTime = strtoupper(base_convert($end_timestamp, 10, 16));
                $txSecret   = md5( $pull_key . $uid . $txTime );

                $params = array(
                    "SourceType" => "PullLivePushLive",
                    "SourceUrls" => $SourceUrls,
                    "DomainName" => 'https://umotool.com',
                    "PushArgs"   => 'txSecret='.$txSecret.'&txTime='.$txTime,
                    "AppName"    => 'live',
                    "StreamName" => $uid,
                    "StartTime"  => gmdate("Y-m-d\TH:i:s\Z", $timestamp),
                    "EndTime"    => gmdate("Y-m-d\TH:i:s\Z", $end_timestamp),
                    "Operator"   => 'tom001',
                );
//                print_r($params);die;

                $req->fromJsonString( json_encode( $params ) );
                // 返回的resp是一个CreateLivePullStreamTaskResponse的实例,与请求对象对应
                $resp   = $client->CreateLivePullStreamTask( $req );

                // 推流地址、播流地址、taskId
                $data['push'] = 'rtmp://push.umotool.com/live/'. $uid . '?' .$params['PushArgs'];
                $data['pull'] = 'https://umotool.com/live/'.$uid.'.flv?' .$params['PushArgs'];
                $data['TaskId'] = $resp->TaskId;

                echo json_encode( $data , JSON_UNESCAPED_UNICODE );

            }
            catch(TencentCloudSDKException $e) {
                echo $e;
            }

        }
    }



    public function xiabo()
    {
        $uid = $_POST['uid'];
        $TaskId = $_POST['TaskId'];
        if (empty($uid) || empty($TaskId)) {
            echo "请输入 TaskId";
        } elseif (!is_numeric($uid) || !is_numeric($TaskId)) {
            echo "TaskId 必须是数字";
        } else {

            try {
                // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
                // 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。密钥可前往官网控制台 https://console.tencentcloud.com/capi 进行获取
                $cred = new Credential("AKID575vicM9rU6iBiWJNi09HF8xhMxOk4Od",
                    "MiDkHwgOFpMpGf2KXcZIo9MYY5qnmhU5");
                // 实例化一个http选项,可选的,没有特殊需求可以跳过
                $httpProfile = new HttpProfile();
                $httpProfile->setEndpoint( "live.tencentcloudapi.com" );

                // 实例化一个client选项,可选的,没有特殊需求可以跳过
                $clientProfile = new ClientProfile();
                $clientProfile->setHttpProfile( $httpProfile );
                // 实例化要请求产品的client对象,clientProfile是可选的
                $client = new LiveClient( $cred, "ap-bangkok", $clientProfile );

                // 实例化一个请求对象,每个接口都会对应一个request对象
                $req = new DeleteLivePullStreamTaskRequest();

                $params = array(
                    "TaskId"   => $TaskId,
                    "Operator" => "tom001"
                );
                $req->fromJsonString( json_encode( $params ) );
                // 返回的resp是一个DeleteLivePullStreamTaskResponse的实例,与请求对象对应
                $resp = $client->DeleteLivePullStreamTask( $req );
                // 输出json格式的字符串回包
                $json = $resp->toJsonString();


                $data['uid'] = $uid;
                $data['TaskId'] = '已下播-'.$TaskId;
                $rs = DB::name('live')->update($data);


//                return $json;
                return json_decode( $json, 1 );

            } catch ( TencentCloudSDKException $e ) {
                return [ 'ode' => $e->getCode(), 'msg' => $e->getMessage() ];
            } catch ( PDOException  $e ) {
                return [ 'ode' => $e->getCode(), 'msg' => $e->getMessage() ];
            }catch ( Exception   $e ) {
                return [ 'ode' => $e->getCode(), 'msg' => $e->getMessage() ];
            }
        }
    }


    public function del(){
        
        $uid = $this->request->param('uid', 0, 'intval');
        
        $rs = DB::name('live')->where("uid={$uid}")->delete();
        if(!$rs){
            $this->error("删除失败!");
        }
		
	
        
        $this->success("删除成功!",url("liveing/index"));
            
    }
    
    public function add(){
        
        $this->assign("liveclass", $this->getLiveClass());
        
        $this->assign("type", $this->getTypes());
        
        return $this->fetch();
    }
    
    public function addPost(){
        if ($this->request->isPost()) {
            
            $data = $this->request->param();
            
            $nowtime=time();
            $uid=$data['uid'];
            
            $userinfo=DB::name('user')->field("ishot")->where(["id"=>$uid,"user_type"=>2])->find();
            if(!$userinfo){
                $this->error('用户不存在');
            }
            
            $liveinfo=DB::name('live')->field('uid,islive')->where(["uid"=>$uid])->find();
            if($liveinfo['islive']==1){
                $this->error('该用户正在直播');
            }
            
            $TaskId=$data['TaskId'];
            $pull=urldecode($data['pull']);
            $push=urldecode($data['push']);
            $type=$data['type'];
            $type_val=$data['type_val'];
            $anyway=$data['anyway'];
            $liveclassid=$data['liveclassid'];
            $stream=$uid.'_'.$nowtime;
            $title='';


            
            $data2=array(
                "uid"=>$uid,
                "showid"=>$nowtime,
                "starttime"=>$nowtime,
                "title"=>$title,
                "province"=>'',
                "city"=>'好像在火星',
                "stream"=>$stream,
                "thumb"=>'',
                "TaskId"=>$TaskId,
                "pull"=>$pull,
                "push"=>$push,
                "lng"=>'',
                "lat"=>'',
                "type"=>$type,
                "type_val"=>$type_val,
                "isvideo"=>1,
                "islive"=>1,
                "anyway"=>$anyway,
                "liveclassid"=>$liveclassid,

            );
            
            if($liveinfo){
                $rs = DB::name('live')->update($data2);
            }else{
                $rs = DB::name('live')->insertGetId($data2);
            }

            if($rs===false){
                $this->error("添加失败!");
            }
			
	
            
            $this->success("添加成功!");
            
        }           
    }
    
    public function edit(){
        $uid   = $this->request->param('uid', 0, 'intval');
        
        $data=Db::name('live')
            ->where("uid={$uid}")
            ->find();
        if(!$data){
            $this->error("信息错误");
        }
        
        $this->assign('data', $data);
        
        $this->assign("liveclass", $this->getLiveClass());
        
        $this->assign("type", $this->getTypes());
        
        return $this->fetch();


    }
    
    public function editPost(){
        if ($this->request->isPost()) {
            
            $data = $this->request->param();
            
            $data['pull']=urldecode($data['pull']);
            $data['push']=urldecode($data['push']);


            
            $rs = DB::name('live')->update($data);
            if($rs===false){
                $this->error("修改失败!");
            }
		
            
            $this->success("修改成功!");
        }
    }
        
}