<?php


namespace app\models\system;


use crmeb\basic\BaseModel;
use crmeb\traits\ModelTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class StoreTemplate extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'store_template';

    use ModelTrait;

    public static function vaildWhere()
    {
        return self::where('is_del', 0);
    }

    /**
     * @param null $where
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getList($where = null)
    {
        $data = ($data = self::setWhere($where)->select()) && count($data) ? $data->toArray() : [];
        $count = self::setWhere($where)->count();
        return ['count' => $count, 'list' => $data];
    }

    public static function setWhere($where)
    {
        $model = (new self)::vaildWhere();
        if ($where['name']) {
            $model = $model->where('name', 'like', '%' . $where['name'] . '%');
        }
        if ($where['use_version']) {
            $model = $model->where('use_version', $where['use_version']);
        }
        if ($where['is_ban']) {
            $model = $model->where('is_ban', $where['is_ban']);
        }
        return $model;
    }

    /**
     * 删除模板
     * @param $id
     * @return bool
     */
    public static function delTemplate($id)
    {
        try {
            if (!self::vaildWhere()->where(['id' => $id])->find()) {
                return self::setErrorInfo('模板未找到或已删除');
            }
        } catch (DbException $e) {
            return self::setErrorInfo($e->getMessage());
        }
        $res = self::where('id', $id)->update(['is_del' => 1]);
        if ($res) {
            return true;
        } else {
            return self::setErrorInfo('删除失败');
        }
    }

    public static function setTemplateBan($id, $ban)
    {
        $count = self::where('id', $id)->count();
        if (!$count) return self::setErrorInfo('参数错误');
        $count = self::where('id', $id)->where('is_ban', $ban)->count();
        if ($count) return true;
        self::beginTrans();
        $res = self::where('id', $id)->update(['is_ban' => $ban]);
        self::checkTrans($res);
        return $res;
    }
}