<?php

namespace app\adminapi\service\chat;

use app\adminapi\model\Admin as AdminModel;
use app\common\exception\BaseException;
use app\adminapi\model\chat\ChatTemplate as ChatTemplateModel;

/**
 * @package app\adminapi\service\chat
 * @class Speech
 * @author xzncit 2024/3/30
 */
class Speech {

    /**
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList($params){
        $array           = [];
        $fields          = ["title",["title"=>$params["keywords"]??'']];
        $array["total"]  = ChatTemplateModel::withSearch(...$fields)->count();
        $array["list"]   = ChatTemplateModel::withSearch(...$fields)->order("id","desc")->page($params["current"]??1,$params["size"]??10)->select()->toArray();
        return $array;
    }

    /**
     * 详情
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detail($id){
        return ChatTemplateModel::where("id",$id??0)->findOrEmpty()->toArray();
    }

    /**
     * 添加/修改
     * @param $data
     * @return AdminModel|bool|\think\Model
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function save($data){
        if(empty($data["id"])){
            $data["create_time"] = time();
            return ChatTemplateModel::create($data);
        }

        $user = ChatTemplateModel::where("id",$data["id"])->find();
        if(empty($user)){
            throw new BaseException("您要修改的内容不存在",0);
        }

        return ChatTemplateModel::where("id",$data["id"])->save($data);
    }

    /**
     * @param $id
     * @return bool
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function delete($id){
        return ChatTemplateModel::where("id",$id)->delete();
    }

}