<?php

namespace App\Model;

use App\Exceptions\DatabaseException;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use Illuminate\Support\Facades\DB;
use Qiniu\Config;
use Qiniu\Storage\FormUploader;

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

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

    protected $primaryKey = '_id';

    public static function mediaList($request){


        try{
            $where = [];

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

            $medias = DB::connection('mongodb')->collection('media')
                ->where($where)
                ->paginate(10);


        }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::find($media_id);
            if ($media){
                throw new \Exception('媒资已经存在');
            }

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


            $data = [

                '_id'           => $media_id,
                'media_name'    => $request->media_name,
                'media_type'    => $request->media_type??'一题一码',
                'class_id'      => $media_info[0],
                'class_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())
            ];

            $id = MediaModel::insertGetId($data);

        }catch (\Exception $exception){

            throw new DatabaseException($exception->getMessage());
        }

        return $id;
    }

    public static function upload($request){



    }

}
