<?php

/**
 * 短视频
 * 2020-4-14 16:42:02
 * junshi
 */

include LIB_PATH . 'ali' . DS . 'VodUploadSDK-PHP_1.0.2' . DS . 'voduploadsdk' . DS . "Autoloader.php";

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Vod\Vod;

class shortVideoController extends baseController
{

//    private $accessKeyId = "LTAI4FnPVdHKfMcxaUqGRDwL";              //AccessKey ID
//    private $accessKeySecret = "xnBhmM83XcmzSs8qpT4PfjxnQdmjXm";    //Access Key Secret
//    private $storageLocation = "https://outin-d58902357e2f11eaaa0d00163e1c9256.oss-cn-shanghai.aliyuncs.com";    //储存位置

    private $accessKeyId = "LTAI4GHQCn28XEt3UWWZSzft";              //AccessKey ID
    private $accessKeySecret = "eDHpZUNmsgXl0LD6TGjtTcjpo3vpAC";    //Access Key Secret

    /**
     * 发布短视频
     * parameter
     * filePath     视频文件
     * coverPath    封面文件
     * title        视频描述
     * address      当前位置
     */
    public function uploadShortVideoAction()
    {

        //获取参数，参数验证
        $request = Request::unmeaning()->all();
        $shortVideoModule = new shortVideoModule();
        $parameter = $shortVideoModule->uploadVideo($request);
        //获取视频信息
        $video_info = $this->getPlayInfo($request["videoId"]);
        if (!$video_info){
            returnFail([],getcodestr(9002),9002);
        }
        $filePath = $video_info->PlayInfoList->PlayInfo[0]->PlayURL;    //播放地址
        $coverPath = $video_info->VideoBase->CoverURL;                  //封面图地址
        $title = $video_info->VideoBase->Title;                         //标题

        //组装数据完整
        $shortVideoModule = new shortVideoModule();
        $user_info = $shortVideoModule->getUserInfoByToken();
        $data_insert = [
            "user_number" => $user_info["number"],          //用户编号
            "title" => $title,                              //动态标题与描述
            "img" => $coverPath,                            //封面图链接
            "url" => $filePath,                             //链接地址
            "span" => $parameter["span"],                   //标签
            "status" => 1,                                  //是否有效，默认有效
            "address" => $parameter["address"],             //当前位置
            "play" => 0,                                    //播放量0
            "create_time" => date("Y-m-d H:i:s"),   //创建时间
        ];

        //上传数据，返回结果
        $result = $shortVideoModule->insert($data_insert,false);
        if ($result) {
            returnSuccess([], getcodestr(200), 200);
        } else {
            returnSuccess([], getcodestr(10001), 10001);
        }
    }

    /**
     * 上传本地视频
     * parameter:
     * filePath         视频本地路径
     * title            标题
     * fileName         文件名称
     * mediaExt         文件格式
     * cateId           类型
     * tags             标签
     * description      描述
     * coverURL         封面图
     * templateGroupId  模板组ID
     * isShowWatermark  水印
     * storageLocation  存储位置
     * userData         用户数据
     * appId            appId
     * workflowId       工作流ID
     */
    public function uploadLocalVideo($filePath, $coverPath)
    {
        try {

            $uploader = new AliyunVodUploader($this->accessKeyId, $this->accessKeySecret);
            $uploadVideoRequest = new UploadVideoRequest($filePath, 'uploadLocalVideo' . time());
            $uploadVideoRequest->setCateId(time() . rand(1000, 9999));
            if (!empty($coverPath)) {
                $uploadVideoRequest->setCoverURL($coverPath);
            }
            //回调用户信息
            $userData = array(
                "MessageCallback" => array("CallbackURL" => "https://demo.sample.com/ProcessMessageCallback"),
                "Extend" => array("localId" => "xxx", "test" => "www")
            );
            //上传视频
            $uploadVideoRequest->setUserData(json_encode($userData));
            $res = $uploader->uploadLocalVideo($uploadVideoRequest);
            return $res;
        } catch (Exception $e) {
            $error = "uploadLocalVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n";
            printf($error, $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
        }
    }

    /**
     * 上传本地图片
     */
    function uploadLocalImage($filePath)
    {
        try {
            $uploader = new AliyunVodUploader($this->accessKeyId, $this->accessKeySecret);
            $uploadImageRequest = new UploadImageRequest($filePath, 'uploadLocalImage' . time());
            $uploadImageRequest->setCateId(time() . rand(1000, 9999));
            $res = $uploader->uploadLocalImage($uploadImageRequest);
            return $res;
        } catch (Exception $e) {
            printf("uploadLocalImage Failed, ErrorMessage: %s\n", $e->getMessage());
        }
    }

    /**
     * 获取音乐类型
     */
    public function getMusicTypeAction()
    {
        $type = (new musicTypeModule())->getAllBySort();
        returnSuccess($type, getcodestr(200), 200);
    }

    /**
     * 获取音乐列表
     */
    public function getMusicListAction()
    {
        $type = $this->common->Post("type");
        $where = !empty($type) ? "status = 1 and type = '{$type}'" : "status = 1";
        $music = (new musicModule())->getAllBySort($where);
        returnSuccess($music, getcodestr(200), 200);
    }

    /**
     * 获取音乐信息
     */
    public function getMusicAction()
    {
        $id = $this->common->Post("id");
        $where = "id = {$id} and status = 1";
        $music = (new musicModule())->where($where)->one();
        if ($music) {
            returnSuccess($music, getcodestr(200), 200);
        } else {
            returnFail([], getcodestr(9001), 9001);
        }
    }

    /**
     * 获取用户动态或小视频列表
     * parameter
     * user_number 用户编号
     * page        页数
     * limit       每页显示
     */
    public function getUserReleaseAction()
    {
        //获取数据
        $request = Request::unsetRoute()->all();
        $shortVideoModule = new shortVideoModule();
        $res = $shortVideoModule->getUserRelease($request);
        returnSuccess($res, getcodestr(200), 200);

    }

    /**
     * 增加视频浏览记录
     * parameter
     * user 用户编号
     * video 视频id
     */
    public function addVideoPlayAction()
    {
        //获取参数
        $request = Request::unsetRoute()->all();
        $shortVideoModule = new shortVideoModule();
        $user_info = $shortVideoModule->getUserInfoByToken();
        //增加记录
        $shortVideoModule->addVideoPlay($request, $user_info);
    }

    /**
     * 短视频推荐（用户刷短视频时候的推荐）
     */
    public function pushVideoAction()
    {
        //获取数据
        $request = Request::unsetRoute()->all();
        $shortVideoModule = new shortVideoModule();
        $xin = (new commonModule())->getUserInfoByToken();
        $number = !empty($xin) ? $xin["number"] : "";
        $res = $shortVideoModule->pushVideo($request,$number);
        returnSuccess($res, getcodestr(200), 200);
    }

    /**
     * 视频标签列表
     */
    public function getVideoSpanListAction()
    {
        $video_span = (new videoSpanModule())->getAllBySort();
        returnSuccess($video_span, getcodestr(200), 200);
    }

    /**
     * 获取短视频评论接口
     */
    public function getUserSayAction(){
        $request = Request::unsetRoute()->all();
        if(empty($request['video_id'])){
            returnFail(config('code')['2010'],config('code')['9009'],9009);
        }
        $data = new commonModule('');
    }

    //==========短视频sdk==========//

    //初始化client
    public function initVodClient($accessKeyId, $accessKeySecret) {
        $regionId = 'cn-shanghai';  // 点播服务接入区域
        $profile = DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
        return new DefaultAcsClient($profile);
    }

    /**
     * 获取视频上传地址和凭证
     * request：title 标题 封面图地址 coverUrl
     * junshi
     * 2020-8-29 12:00:28
    */
    public function createUploadVideoAction(){

        //获取参数信息
        $title = $this->common->Post("title");
        $coverUrl = $this->common->Post("coverURL");
        $file_name = $this->common->Post("fileName");
        //验参组装用户数据
        if (empty($title)){
            returnFail([],getcodestr(9005),9005);
        }
//        if (empty($coverUrl)){
//            returnFail([],getcodestr(9004),9004);
//        }
        if (empty($file_name)){
            returnFail([],getcodestr(9010),9010);
        }
        //上传
        $client = $this->initVodClient($this->accessKeyId, $this->accessKeySecret);
        $request = new \vod\Request\V20170321\CreateUploadVideoRequest();
        $request->setTitle($title);
        $request->setFileName($file_name);
        $request->setCoverURL($coverUrl);
        $request->setAcceptFormat('JSON');
        $req = $client->getAcsResponse($request);
        $data = [
            "uploadAddress" => $req->UploadAddress,
            "videoId" => $req->VideoId,
            "requestId" => $req->RequestId,
            "uploadAuth" => $req->UploadAuth,
        ];
        returnSuccess($data);
    }

    /**
     * 刷新视频上传凭证
     * @param client 发送请求客户端
     * @return RefreshUploadVideoResponse 刷新视频上传凭证响应数据
     */
    public function refreshUploadVideoAction() {
        $client = $this->initVodClient($this->accessKeyId, $this->accessKeySecret);
        $videoId = $this->common->Post("videoId");
        if (empty($videoId)){
            returnFail([],getcodestr(9011),9011);
        }
        $request = new \vod\Request\V20170321\RefreshUploadVideoRequest();
        $request->setVideoId($videoId);
        $request->setAcceptFormat('JSON');
        $req = $client->getAcsResponse($request);
        $data = [
            "uploadAddress" => $req->UploadAddress,
            "videoId" => $req->VideoId,
            "requestId" => $req->RequestId,
            "uploadAuth" => $req->UploadAuth,
        ];
        returnSuccess($data);
    }

    /**
     * 获取图片上传地址和凭证
     * @param client 发送请求客户端
     * @return CreateUploadImageResponse 获取图片上传地址和凭证响应数据
     */
    public function createUploadImageAction() {
        $client = $this->initVodClient($this->accessKeyId, $this->accessKeySecret);
        $imageType = $this->common->Post("imageType");
//        $imageExt = $this->common->Post("imageExt");
        $request = new \vod\Request\V20170321\CreateUploadImageRequest();
        $request->setImageType($imageType);
        $request->setImageExt("png");
        $request->setAcceptFormat('JSON');
        $req = $client->getAcsResponse($request);
        $data = [
            "imageURL" => $req->ImageURL,
            "imageId" => $req->ImageId,
            "uploadAddress" => $req->UploadAddress,
            "uploadAuth" => $req->UploadAuth,
        ];
        returnSuccess($data);
    }

    //获取视频信息
    public function getPlayInfo($videoId) {
        $client = $this->initVodClient($this->accessKeyId, $this->accessKeySecret);
        $request = new \vod\Request\V20170321\GetPlayInfoRequest();
        $request->setVideoId($videoId);
        $request->setAuthTimeout(3600*24);
        $request->setAcceptFormat('JSON');
        $req = $client->getAcsResponse($request);
        return $req;
    }

    //获取播放凭证
    public function getPlayAuth() {
        $client = $this->initVodClient($this->accessKeyId, $this->accessKeySecret);
        $videoId = "b0a6708f4c4b41dfad4065f4005c4469";
        $request = new \vod\Request\V20170321\GetVideoPlayAuthRequest();
        $request->setVideoId($videoId);
        $request->setAuthInfoTimeout(3000);
        $request->setAcceptFormat('JSON');
        $response = $client->getAcsResponse($request);
        return $response;
    }

}