<?php

namespace App\Http\Controllers\Api\Client;
use App\Model\AliOssModel;
use App\Model\BaiduOssModel;
use Illuminate\Validation\Rule;
use App\Exceptions\FormException;
use App\Model\MediaModel;
use App\Model\QiniuModel;
use App\Tool\SrsHookValidate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Qiniu\Config;
use Qiniu\Storage\FormUploader;

class MediaController extends Controller
{
    private $bucketList = [
        'develop'  => 'dev-offcncloud',
        'test'     => 'test-offcncloud-test',
        'master'   => 'test-offcncloud',
    ];

    protected $domain = [
        'develop'   => 'qcoenfz67.bkt.clouddn.com',
        'test'      => 'test-vod-mam.offcncloud.com',
        'master'    => 'vod-mam.eoffcn.com'
    ];

    const OSS_ALI = 'ALI';
    const OSS_QI_QIU = 'QI_NIU';
    const OSS_BAIDU = 'BAIDU';

    /**
     * 获取媒资ID
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ControllerException
     */
    public function index(Request $request){

        $result = handler_drive(function () use ($request) {
            $i = 0;
            do {
                $media_id = "mda-".generateRandomNum(16);
                $media = MediaModel::find($media_id);
                $i ++;
            } while ($i < 3 && !empty($media) );
            if ($i == 3){
                return 0;
            }
            return ["mediaID" => $media_id];
        });
        if (!$result){
            return error("mediaID重复生成次数太多");
        }
        return success($result);
    }

    /**
     * 获取上传媒资token
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ControllerException
     * @throws \App\Exceptions\DatabaseException
     */
    public function getUploadMediaToken(Request $request){

        $result = handler_drive(function () use ($request) {
            $branch = empty(getenv('branch')) ? 'test' : getenv('branch');

            SrsHookValidate::srsHookCallback($request,[
               'key'    => '',
               'platform' => Rule::in(['QI_NIU', 'ALI','BAIDU'])
            ],null,[
                'platform.in'      => '系统暂不支持 '.$request->platform.' 平台',
            ]);

            $key = $request->key??null;
            switch ($request->platform){
                case self::OSS_ALI:
                    $data = AliOssModel::getAilOssToken($request);
                    break;
                case self::OSS_QI_QIU:
                    $token = QiniuModel::uploadToken($this->bucketList[$branch],$key);
                    $domain = $this->domain[$branch];
                    $data =  ["token" => $token,'domain' => $domain];
                    break;
                case self::OSS_BAIDU:
                    $data = BaiduOssModel::getBaiduOssToken($request);
                    $domain = BaiduOssModel::getDomain();
                    $data["domain"] = $domain;
                    break;
                default:
                    $token = QiniuModel::uploadToken($this->bucketList[$branch],$key);
                    $domain = $this->domain[$branch];
                    $data =  ["token" => $token,'domain' => $domain];
            }
//            $token = QiniuModel::uploadToken($this->bucketList[$branch],$key);
//            $domain = $this->domain[$branch];
            return $data;
        });
        return success($result);
    }

    /**
     * 视频上传成功之后，回调重新上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ControllerException
     */
    public function hookRestoreMedia(Request $request){

        $id = handler_drive(function () use ($request) {
            SrsHookValidate::srsHookCallback($request,array_merge([
                'media_name'  => 'required',
                'media_type'  => 'required',
                'media_id'    => 'required',
                'access_key'  => '',
                'secret_key'  => '',
                'media_url'   => 'required',
                'description' => '',
                'start_time'  => 'required|date',
                'end_time'    => 'required|date|after_or_equal:start_time',
                'duration'    => '',
                'replace'     => '',
                'is_fake'     => '',
            ],config('app.client_request_parameters')),null,[
                'start_time.date'    => '开始时间格式错误',
                'start_time.required'=> '开始时间不能为空',
                'end_time.required'  => '结束时间不能为空',
                'end_time.date'      => '结束时间格式错误',
                'end_time.after_or_equal' => '结束时间不能小于开始时间'
            ]);

            $request->merge([
                'status' => "1",
            ]);
            $request->replace($request->all());

            //$request->replace(array_merge($request->all(),['status'=>"1"]));
            $id = MediaModel::hookRestoreMedia($request);

            return $id;
        });
        return success($id);
    }

    /**
     * 更新媒资信息
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ControllerException
     */
    public function updatehookMedia(Request $request,$id){


        $id = handler_drive(function () use($request,$id){

            SrsHookValidate::srsHookCallback($request,[
                'media_name'    => 'required',
                'media_type'    => 'required',
//                'media_id'      => 'required',
                'access_key'    => '',
                'secret_key'    => '',
                'media_url'     => 'required',
                'description'   => '',
//                'start_time'  => 'required|date',
//                'end_time'    => 'required|date|after_or_equal:start_time',
            ]);

            MediaModel::updatehookMedia($request,$id);

            return $id;
        });
        return success($id);
    }

    /**
     * 获取媒资列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ControllerException
     */
    public function mediaList(Request $request){

        $res = handler_drive(function () use($request){

            SrsHookValidate::srsHookCallback($request,[
                'media_name'    => '',
                'username'      => '',
                'page'          => 'integer',
                'media_id'      => '',
                'description'   => '',
                'sort'          => '',
                'page_size'     => 'integer',
                'category_id'   => '',
                'appid'         => '',
            ]);

            if (!isset($request->category_id)){
                $request->replace(array_merge($request->all(),['category_id'=>'5efa9cb5d16f5a214671fd86']));
            }

            return MediaModel::mediaList($request);

        });
        return success($res);
    }



    /**
     * 测试上传文件
     * @param Request $request
     */
    function testUploadFile(Request $request){

        $token = $token = QiniuModel::uploadToken($this->bucketList['test']);
        $file = $request->file('file_name');

        $conf = new Config();
        $res = FormUploader::putFile($token,$file->getFilename(),$file->getRealPath(),$conf,null,null);


    }


}
