<?php

namespace App\Model;

use App\Exceptions\DatabaseException;
use App\Tool\Constant;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\DB;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use MongoDB\Client;


class MediaModel extends Eloquent
{
    protected $collection = "media";

    protected $connection = 'mongodb';  //使用mongodb

    protected $primaryKey = '_id';

    protected $fillable = [];

    public $timestamps = false;



    public function media_category()
    {
        return $this->belongsTo('MediaCategoryModel');
    }

    /**
     * 媒资列表
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function mediaList($request){

        try{
            $medias = MediaModel::query()->raw(function ($collection) use($request){

                $limit = (isset($request->page_size) ? (int)($request->page_size) : Constant::PAGE_NUMBER) ;


                $page = $request->page??1;

                /**
                 * 默认降序
                 */
                $sort = -1;
                if ($request->sort == 'asc'){
                    $sort = 1;
                }

                if (isset($request->media_id) && !empty($request->media_id)){
                    $aggregate[]['$match']['_id'] = $request->media_id;
                }

                if (isset($request->media_name) && !empty($request->media_name)){
                    $aggregate[]['$match']['media_name'] = ['$regex' => addslashes($request->media_name) ];
                }

                if (isset($request->username) && !empty($request->username)){
                    $aggregate[]['$match']['username'] = $request->username;
                }

                if (isset($request->description) && !empty($request->description)){
                    $aggregate[]['$match']['description'] = ['$regex' => $request->description ];
                }

                if (isset($request->start_time)&& !empty($request->start_time)){
                    $aggregate[]['$match']['start_time'] = ['$gt' => $request->start_time ];
                }

                if (isset($request->end_time)&& !empty($request->end_time)){
                    $aggregate[]['$match']['end_time'] = ['$lt' => $request->end_time ];
                }

                $aggregate[]['$sort'] = ['start_time'  => $sort];
                $count = sizeof($collection->aggregate($aggregate)->toArray());


                $skip = ((empty($request->page)   ? 1 : $request->page)-1) * $limit;

                $aggregate[]['$skip'] = $skip;
                $aggregate[]['$limit'] = $limit;


                return new LengthAwarePaginator($collection->aggregate($aggregate)->toArray(), $count, $limit, $page,[
                    'path' => Paginator::resolveCurrentPath(),
                    'pageName' => 'page',
                ]);


            });

        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }
        return $medias;
    }

    /**
     * 存储媒资数据
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function hookRestoreMedia($request){

        try{

            /**
             * 判断媒资ID是否存在
             */
            $media_id = $request->media_id;


            $media = MediaModel::where("_id",$media_id)->first();

            if (!empty($media)){
                throw new \Exception("媒资编号已被使用");
            }

            //hb15011&河北公务员考试试题
            /**
             * 媒资名称是由课程编号与课程名称组成
             */
            $media_info = explode("&",$request->media_name);


            $mediaCatg = MediaCategoryModel::where('_id',$request->media_type)->first();
            if (empty($mediaCatg)){
                throw new \Exception("媒资类别不存在");
            }

            $media_url = $request->media_url;

            $media_url = str_replace("http:","https:".substr($media_url,6),$media_url);


            /**
             * 处理文件名称，确认是否包含"&"符合
             */
            if (count($media_info)>=2){

                $data = [
                    '_id'           => $media_id,
                    'media_name'    => $request->media_name,
                    'media_type_id' => $mediaCatg['_id'],
                    'media_type'    => $mediaCatg['name'],
                    'book_num'      => $media_info[0],
                    'book_name'     => $media_info[1],
                    'media_url'     => $media_url,
                    'access_key'    => $request->access_key,
                    'secret_key'    => $request->secret_key,
                    'create_time'   => date('Y-m-d H:i:s',time()),
                    'description'   => $request->description,
                    'username'      => $request->token_username,//员工工号
                    'user_id'       => $request->token_user_id,
                    'start_time'    => $request->start_time??'',
                    'end_time'      => $request->end_time??'',
                ];

            }else{

                $data = [
                    '_id'           => $media_id,
                    'media_name'    => $request->media_name,
                    'media_type_id'    => $mediaCatg['_id'],
                    'media_type'=> $mediaCatg['name'],
                    'book_num'      => '',
                    'book_name'     => $request->media_name,
                    'media_url'     => $media_url,
                    'access_key'    => $request->access_key,
                    'secret_key'    => $request->secret_key,
                    'create_time'   => date('Y-m-d H:i:s',time()),
                    'description'   => $request->description,
                    'username'      => $request->token_username,//员工工号
                    'user_id'       => $request->token_user_id,
                    'start_time'    => $request->start_time??'',
                    'end_time'      => $request->end_time??'',
                ];
            }

            $id = MediaModel::insertGetId($data);
        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }
        return $id;
    }

    /**
     * 更新媒资信息
     * @param $request
     * @param $id
     * @return mixed
     * @throws DatabaseException
     */
    public static function updatehookMedia($request,$id){

        try{

            $media = MediaModel::find($id);
            if (empty($media)){
                throw new \Exception("媒资不存在");
            }

            //hb15011&河北公务员考试试题
            /**
             * 媒资名称是由课程编号与课程名称组成
             */
            $media_info = explode("&",$request->media_name);

            $mediaCatg = MediaCategoryModel::where('_id',$request->media_type)->first();
            if (empty($mediaCatg)){
                throw new \Exception("媒资类别不存在");
            }

            /**
             * 处理文件名称，确认是否包含"&"符合
             */
            if (count($media_info)>=2){

                $data = [
                    '_id'           => $id,
                    'media_name'    => $request->media_name,
                    'media_type'    => $mediaCatg['name'],
                    'media_type_id' => $mediaCatg['_id'],
                    'book_num'      => $media_info[0],
                    'book_name'     => $media_info[1],
                    'media_url'     => $request->media_url,
                    'access_key'    => $request->access_key,
                    'secret_key'    => $request->secret_key,
                    'create_time'   => date('Y-m-d H:i:s',time()),
                    'description'   => $request->description,
                    'start_time'    => $request->start_time??'',
                    'end_time'      => $request->end_time??'',
                ];

            }else{
                $data = [
                    '_id'           => $id,
                    'media_name'    => $request->media_name,
                    'media_type'    => $mediaCatg['name'],
                    'media_type_id' => $mediaCatg['_id'],
                    'book_num'      => '',
                    'book_name'     => $request->media_name,
                    'media_url'     => $request->media_url,
                    'access_key'    => $request->access_key,
                    'secret_key'    => $request->secret_key,
                    'create_time'   => date('Y-m-d H:i:s',time()),
                    'description'   => $request->description,
                    'start_time'    => $request->start_time??'',
                    'end_time'      => $request->end_time??'',
                ];
            }

            $flag = MediaModel::where("_id",$id)->update($data);
            if (!$flag){
                throw new \Exception("更新失败");
            }

        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }
        return $flag;
    }


    /**
     * 获取媒资详情
     * @param $id
     * @return mixed
     * @throws DatabaseException
     */
    public static function getMediaDetail($id){

        try{
            $media = MediaModel::find($id);

            if (empty($media)){
                throw new \Exception('媒资不存在');
            }

        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }

        return $media;

    }

    /**
     * 根据课件编号获取媒资编号与视频地址
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function getMediaList($request){

        try{
            /**
             *[{"bookNum":["hb15011","2"],"mediaCatg":"一题一码"}]
             */
            $params = json_decode($request->params,true);

            if (empty($params)){
                throw new \Exception("参数格式有误");
            }
            $tmp = [];
            foreach ($params as $param){

                if (!isset($param['mediaCatg']) || !isset($param['bookNum'])){
                    throw new \Exception("格式有误");
                }

                $media_name= $param['mediaCatg'];
                $media_ids = $param['bookNum'];

                $media_catg = MediaCategoryModel::where('name',trim($media_name))->first();

                if (empty($media_catg)){
                    throw new \Exception("媒资类别不存在");
                }
                $tmp[] = MediaModel::select("_id","book_num","book_name","secret_key","media_url")->whereIn('book_num',$media_ids)->get();
            }

        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }

        $res = [];

        foreach ($tmp as $item){
            $res = $item->groupBy("book_num");
        }

        return $res;
    }

    /**
     * 删除媒资数据
     * @param $id
     * @return int
     * @throws \Exception
     */
    public static function deleteMediaById($request,$id){

        try{
            $media = MediaModel::where('_id',$id)->first();
            if (empty($media)){
                throw new \Exception('媒资不存在！');
            }

            if ($request->token_username != 'offcn'){

            }


            $flag = MediaModel::destroy($id);
            if (!$flag){
                throw new \Exception('删除失败');
            }

        }catch (\Exception $exception){

            throw new \Exception($exception->getMessage());

        }
        return $flag;
    }

    /**
     * 获取媒资播放地址
     * @param $media_id
     * @return mixed
     * @throws DatabaseException
     */
    public static function playUrl($media_id){

        try{

            $media = MediaModel::select('media_url','secret_key')->find($media_id);

            if (empty($media)){
                throw new \Exception("媒资不存在");
            }
        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());

        }
        return $media;
    }

    public static function handleMediaUrl($request){

        try{
            $medias = MediaModel::query()->raw(function ($collection) use($request){

                $limit = (isset($request->page_size) ? (int)($request->page_size) : Constant::PAGE_NUMBER) ;

                $page = $request->page??1;

                /**
                 * 默认降序
                 */
                $sort = -1;
                if ($request->sort == 'asc'){
                    $sort = 1;
                }

                if (isset($request->media_id) && !empty($request->media_id)){
                    $aggregate[]['$match']['_id'] = $request->media_id;
                }

                if (isset($request->media_name) && !empty($request->media_name)){
                    $aggregate[]['$match']['media_url'] = ['$regex' => 'http://qcoenfz67.bkt.clouddn.com' ];
                }

                if (isset($request->username) && !empty($request->username)){
                    $aggregate[]['$match']['username'] = $request->username;
                }

                $aggregate[]['$sort'] = ['start_time'  => $sort];
                $count = sizeof($collection->aggregate($aggregate)->toArray());


                $skip = ((empty($request->page)   ? 1 : $request->page)-1) * $limit;

                $aggregate[]['$skip'] = $skip;
                $aggregate[]['$limit'] = $limit;


                return new LengthAwarePaginator($collection->aggregate($aggregate)->toArray(), $count, $limit, $page,[
                    'path' => Paginator::resolveCurrentPath(),
                    'pageName' => 'page',
                ]);


            });


            if (!empty($medias)){


                foreach ($medias as $media){
                    $data = [
                        'media_url'     => "https://vod-mam.eoffcn.com/".$media->_id.'/index.m3u8',
                    ];

                    $flag = MediaModel::where("_id",$media->_id)->update($data);
                    if ($flag==0){
                        throw new \Exception("更新失败");
                    }
                }

            }



        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }
        return $medias;

    }

}
