<?php

namespace App\Model;

use App\Exceptions\DatabaseException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class MediaCategoryModel extends Model
{
    protected static $collection = "media_category";

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

        try{

            $catgList = DB::connection("mongodb")->collection(self::$collection)->get()->toArray();

            foreach ($catgList as &$catg){

                $idArr = ($catg['_id'])->jsonSerialize();
                $catg['_id'] = $catg['_id'] = $idArr['$oid'];

            }

        }catch (\Exception $exception){
            throw new DatabaseException("组织不存在");
        }

        return $catgList;
    }

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

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

            $mediaCatg = DB::connection("mongodb")->collection(self::$collection)->where('name',$request->name)->first();

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


            $id = DB::connection("mongodb")->collection(self::$collection)->insertGetId($data);
        }catch (\Exception $exception){
            throw new DatabaseException("组织不存在");
        }

        return $id;

    }
}
