<?php

namespace App\Model;

use App\Exceptions\DatabaseException;
use App\Tool\Constant;
use http\Env\Request;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use MongoDB\BSON\UTCDateTime;

class MediaCategoryModel extends Eloquent
{
    protected $collection = "media_category";

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

    protected $primaryKey = '_id';

    public function medias()
    {
        return $this->hasMany('MediaModel');
    }

    /**
     * 查询所有媒资列表(不分页)
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function catgList($request){

        try{
            /**
             * 获取用户业务线及对应业务线的权限
             */

            $catgList = MediaCategoryModel::where('status',0)->limit(20)->get()->toArray();
            $appids = array_column($catgList,"media_category_id");

            #需要传一个默认的appid，否则接口会报参数缺失错误
            $url = getRbac($request,'api/open/getPlatform','ec8747abc5dbe8288e64f327a76ac517');


            $result = http_request_code($url,
                array(
                    "Content-Type: application/json"
                ),
                'POST',
                json_encode($appids)
            );

            $catgs = json_decode($result,true);

            if (!isset($catgs['data'])){
                LogModel::addlog(['获取商店列表失败'=>json_decode($result)]);
                throw new \Exception("获取商店列表失败");
            }

            $appids = array_column($catgs['data'],"appid");

            $tmp = [];
            foreach ($catgList as $catg){

                if (in_array($catg['media_category_id'],$appids)){
                    array_push($tmp,$catg);
                }
            }

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

        return $tmp;
    }

    /**
     * 查询所有媒资列表(分页)
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function catgListPage($request){
        try{

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

            $catgList = MediaCategoryModel::where($where)->orderBy("create_time",Constant::SORT_DESC)->paginate(10);

        }catch (\Exception $exception){
            throw new DatabaseException("类别不存在");
        }
        return $catgList;

    }

    /**
     * 添加媒资类别
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function addMediaCatg($request){

        try{

            $create_time = new UTCDateTime(time() * 1000);;
            $data = [
                'name'          => $request->name,
                'status'        => 0,
                'media_category_id' => $request->media_category_id??'',
                'description'   => $request->description??'',
                'create_time'   => $create_time,
                "call_back"     => $request->call_back??"media/cleanCache"
            ];

            $mediaCatg = MediaCategoryModel::where('name',$request->name)->first();

            if (!empty($mediaCatg)){
                throw new \Exception('媒资类别已经存在');
            }
            $id = MediaCategoryModel::insertGetId($data);
        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }
        return $id;
    }


    /**
     * 添加媒资类别
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function updateMediaCatg($request,$id){

        try{
            $data = [
                'name'          => $request->name,
                'status'        => $request->status??0,
                'media_category_id' => $request->media_category_id??'',
                'description'   => $request->description??''
            ];

            $mediaCatg = MediaCategoryModel::where('name',$request->name)->first();

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

            if ($id != $mediaCatg['_id'] ){
                throw new \Exception('媒资类别已经存在');
            }


            $flag = MediaCategoryModel::where("_id",$id)->update($data);

            if (!$flag){
                throw new \Exception("媒资类别更新失败");
            }

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

    /**
     * 禁用媒资店铺
     * @param $request
     * @param $id
     * @return mixed
     * @throws DatabaseException
     */
    public static function disable($request,$id){

        try{
            $data = [
                'status'        => $request->status??0,
            ];

            $mediaCatg = MediaCategoryModel::where('_id',$id)->first();

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


            $flag = MediaCategoryModel::where("_id",$id)->update($data);

            if (!$flag){
                throw new \Exception("媒资类别更新失败");
            }

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

    }

    /**
     * 根据媒资名称，获取媒资信息。
     * @param $name
     * @return mixed
     * @throws DatabaseException
     */
    public static function getCategoryByName($name){
        try{

            $catg = MediaCategoryModel::where("name",$name)->first();

            if (empty($catg)){
                throw new \Exception("店铺不存在");
            }

        }catch (\Exception $exception){

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