<?php

namespace app\model;

use app\BaseModel;
use app\observer\DictionaryObserver;
use think\Model;
use think\model\Collection;
use think\model\concern\SoftDelete;
use think\model\relation\HasMany;

/**
 * 系统字典模型
 * @property int $dict_id
 * @property string $dict_code
 * @property string $dict_name
 * @property string $dict_type
 * @property int $sort_number
 * @property string $comments
 * @property int $is_system
 * @property int $deleted
 * @property string $create_time
 * @property string $update_time
 * @property string $delete_time
 * @property SysDictionaryData[]|Collection $dictData
 * @property array $dictDataCodes
 */
class SysDictionary extends BaseModel
{
    use SoftDelete;


    protected $name = "sys_dictionary";
    protected $pk = "dict_id";
    protected string $eventObserver = DictionaryObserver::class;

    public function dictData(): HasMany
    {
        return $this->hasMany(SysDictionaryData::class, 'dict_id', 'dict_id');
    }

//
//    public static function onAfterInsert(Model|SysDictionary $model): void
//    {
//        security_log_record([SysDictionary::class, 'onAfterInsert'], "添加了新字典集", $model);
//    }
//
//    public static function onAfterDelete(Model|SysDictionary $model): void
//    {
//        security_log_record([SysDictionary::class, 'onAfterDelete'], "字典集{$model->dict_name}被删除", $model);
//    }
//
//    public static function onBeforeUpdate(Model|SysDictionary $model): void
//    {
//        security_log_record([SysDictionary::class, 'onBeforeUpdate'], "修改了{$model->dict_name}字典集", $model);
//    }

    public static function getByDictCode(string $dictCode)
    {
        return self::with(['dictData'])->where('dict_code', $dictCode)->findOrEmpty();
    }

    public function scopeDictCode($query, $dictCode)
    {
        $query->with(['dictData'])->where('dict_code', $dictCode);
    }

    public function getDictDataCodesAttr()
    {
        return $this->dictData->column('dict_data_code');
    }

    public function getByDictDataCode(string $dictDataCode, mixed $default = null)
    {
        $dictDataMap = $this->dictData->column('dict_data_name', 'dict_data_code');

        return $dictDataMap[$dictDataCode] ?? $default;
    }

    public function searchGroupAttr($query, $value): void
    {
        $query->where('group_tag', '=', $value);
    }

    public function searchDictNameAttr($query, $value): void
    {
        $query->where('dict_name', 'like', "%$value%");
    }
//    public function searchDictCodeAttr($query, $value): void
//    {
//        $query->where('dict_code', '=', $value);
//    }
}