<?php

namespace App\Http\Controllers\Web;

use App\Exports\MediasExport;
use App\Exports\MubanExport;
use App\Imports\MediasImport;
use App\Model\DownloadRecord;
use App\Model\MediaCategoryModel;
use App\Model\MediaModel;
use App\Tool\SrsHookValidate;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\App;
use Maatwebsite\Excel\Facades\Excel;
use Qiniu\Auth;


class MediaController extends Controller
{
    private const PREVIEW_DOMAIN = [
        'test'      => 'https://xue.t.eoffcn.com/preview/temp/',
        'master'    => 'https://xue.eoffcn.com/preview/temp/'
    ];

    /**
     * 媒资列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \App\Exceptions\DatabaseException
     * @throws \App\Exceptions\FormException
     */
    public function index(Request $request){

        // php 特殊字符转义，实现字符串安全存入数据库，

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

        $medias = MediaModel::mediaList($request);

        return view('admin.media.media_list', [
            'medias'      => $medias,
            'start_time'  => substr($request->start_time, 0, 10),
            'end_time'    => substr($request->end_time, 0, 10),
            'media_name'  => $request->media_name,
            'media_id'    => $request->media_id,
            'STATUS'      => ['启用','停用'],
            'category_id' => $request->category_id,
            'appid'       => $request->appid,
            'page_size'   => $request->page_size,
            'username'    => $request->username,
            'page'        => $request->page,
        ]);

    }



    /**
     * 编辑房间
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \App\Exceptions\ControllerException
     */
    public function edit(Request $request,$id){

        $media = handler_drive(function () use ($request,$id){
            return MediaModel::getMediaDetail($id);
        });

        return view('admin.media.media_edit', [
            'media'         => $media,
        ]);

    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ControllerException
     */
    public function update(Request $request,$id){

        $res = handler_drive(function () use ($request,$id){
            return MediaModel::updatehookMedia($request,$id);
        });
        return success($res);
    }

    /**
     * 显示
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \App\Exceptions\ControllerException
     */
    public function create(Request $request){

        $reslut = handler_drive(function () use($request){
            $media_types = MediaCategoryModel::catgList($request);
            return $media_types;
        });

        $data['media_types'] = $reslut;
        $data['media_id'] = 'mda-'.generateRandomNum(16);
        return view('admin.media.media_add',$data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ControllerException
     */
    public function store(Request $request){

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

            SrsHookValidate::srsHookCallback($request,[
                'media_name'  => 'required',
                'media_type'  => 'required',
                'media_id'    => 'required',
                'access_key'  => '',
                'secret_key'  => '',
                'media_url'   => 'required',
            ]);

            $data_time = Carbon::now();

            $params = array(
                'start_time'=> $data_time,
                'end_time'  => $data_time,
                'create_time'=> $data_time,
                'status'     => "1",
            );

            $request->replace(array_merge($request->all(),$params));


            return MediaModel::hookRestoreMedia($request);

        });

        return success($id);
    }

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

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

            return MediaModel::deleteMediaById($request,$id);

        });

        return success($id);

    }

    /**
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function media_command(){
        return view('admin.control');
    }

    /**
     * 视频预览
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function media_preview(Request $request,$mediaNum){

        $isFullScreen = $request->fullScreen;

        $branch = !empty(getenv('branch'))?getenv('branch'):"test";
        $url = self::PREVIEW_DOMAIN[$branch];
        if ($isFullScreen){
            $url .= "player".'/'.$mediaNum;
        }else{
            $url .= "play".'/'.$mediaNum;
        }

        return redirect($url);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ControllerException
     */
    public function setMediaNum(Request $request){

        $res = handler_drive(function () use ($request){
            return MediaModel::setMediaNum($request);
        });
        return success($res);
    }

    /**
     * 清除Cdn缓存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ControllerException
     */
    public function clearCdnCache(Request $request,$media_id){
        $res = handler_drive(function () use ($request,$media_id){
            return MediaModel::clearCdnCache($request,$media_id);
        });
        return success($res);
    }

    /**
     * @param Request $request
     * @param $type
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function export_batch_media(Request $request){


        $type = $request->type??'media';


        $data = null;
        switch ($type){
            case 'media':
                $data = new MediasExport(["mda-f72b5ea1c0dfc7203bf7ac522cd8baf9","mda-f6eb263d99752afc"]);
                break;
            case 'muban':
                $data = new MubanExport();
                break;
            default:
                $data = new MediasExport(["mda-f72b5ea1c0dfc7203bf7ac522cd8baf9","mda-f6eb263d99752afc"]);
                break;
        }



        return Excel::download($data,$type.'.xlsx');

    }

    /**
     * 展示批处理文件
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function batch_media(Request $request){

        return view('admin.media.batch_media',$request->all());
    }

    /**
     * 批量导出永久地址
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws \App\Exceptions\ControllerException
     */
    public function import_batch_media(Request $request){
//        $type = $request->type??'media';

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

            $file = $request->file('uploadFile');

            #将文件内容转化为数组
            $sheet = (new MediasImport())->toArray($file);
            $orginal_data = null;
            foreach ($sheet as $k => $v){
                if (!empty($v)){
                    $orginal_data = $v;
                    break;
                }
            }

            if (empty($orginal_data)){
                throw new \Exception("文件格式有误");
            }

            $temp = [];
            foreach ($orginal_data as $key => $item){

                if (!isset($item["媒资编号"]) || !isset($item["名称"])){
                    throw new \Exception("文件格式有误");
                }

                $temp[$item['媒资编号']] = [
                    'media_id'  => $item["媒资编号"],
                    'name'      => $item['名称']
                ];
            }

            $data = [];
            if (!empty($orginal_data)){

                #批量获取永久播放链接地址
                $mediaInfos = MediaModel::batchGetMediaForverM3u8($request,$temp);

                $data = new MediasExport(array_values($mediaInfos));
            }

            $record = md5(json_encode($data));

            DownloadRecord::addRecord($record,$data);

            return $record;

        });


        return success($data);

    }

    /**
     * @param Request $request
     * @param $keyId
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws \App\Exceptions\ControllerException
     */
    public function download(Request $request,$keyId){


        $data = handler_drive(function () use($keyId){

            $record = DownloadRecord::getRecord($keyId);

            if (empty($record)){
                throw new \Exception("数据不存在");
            }

            $content = json_decode($record['content'],true);

            DownloadRecord::delRecord($keyId);

            return new MediasExport($content);

        });

        return Excel::download($data,'media.xlsx');
    }

}
