<?php

namespace App\Model;

use App\Exceptions\DatabaseException;
use Illuminate\Support\Facades\DB;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

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

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

    protected $primaryKey = '_id';


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

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

        try{
            $where = [];
            if ($request->name){
                $where['media_name'] = $request->name;
            }

            $mediaCatgs = MediaCategoryModel::select("_id","name")->get()->toArray();
            $tmp = [];
            foreach ($mediaCatgs as $catg){
                $tmp[$catg['_id']] = $catg['name'];
            }

            $medias = MediaModel::where($where)->orderBy("create_time","desc")->paginate(10);

            foreach ($medias as $media){
                $media['media_type'] = $tmp[$media['media_type_id']];
            }



        }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;

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


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

            /**
             * 处理文件名称，确认是否包含"&"符合
             */
            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'     => $request->media_url,
                    'access_key'    => $request->access_key,
                    'secret_key'    => $request->secret_key,
                    'create_time'   => date('Y-m-d H:i:s',time())
                ];

            }else{

                $data = [
                    '_id'           => $media_id,
                    'media_name'    => $request->media_name,
                    'media_type'    => $mediaCatg->_id,
                    'media_category'=> $mediaCatg['name'],
                    '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())
                ];

            }

            $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())
                ];

            }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())
                ];
            }

            $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 $reqeust
     * @return mixed
     * @throws DatabaseException
     */
    public static function updateMedia($request,$id){
        try{

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

            if (count($media_info)!=2){
                throw new \Exception('视频名称格式不对');
            }

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

            $data = [
                '_id'             => $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'       => $request->media_url,
                'access_key'      => $request->access_key,
                'secret_key'      => $request->secret_key,
                'create_time'     => date('Y-m-d H:i:s',time())
            ];

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

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


    /**
     * 根据课件编号获取媒资编号与视频地址
     * @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',$media_name)->first();

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

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

        $res = [];

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

        /**
         * 排除res为空
         */
        if (!isset($res[0]) || empty($res[0])){
            return [];
        }

        return $res;
    }

}
