<?php

namespace app\common\model\Dictionary;

use app\BaseModel;
use think\Exception;
use think\facade\Config;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsToMany;
use think\model\relation\HasMany;
use think\model\relation\HasOne;
use app\common\arw\adjfut\src\Excel;
use app\common\arw\adjfut\src\UploadFile;
use think\facade\Db;

class Dictionary extends BaseModel
{
    use SoftDelete;
    // 删除字段
    protected $deleteTime = 'dictionary_delete_time';
    // 设置主键名
    protected $pk = 'dictionary_guid';
    // 设置废弃字段
    protected $disuse = [];
    // 设置字段信息
    protected $schema = [
        'dictionary_id'          => 'int',
        'dictionary_parent_guid'        => 'string',
        'dictionary_name'        => 'string',
        'dictionary_value'        => 'string',
        'dictionary_index'        => 'int',
        'dictionary_order'        => 'int',
        'dictionary_status'      => 'int',
        'dictionary_allow_update'      => 'int',
        'dictionary_list_class'      => 'string',
        'dictionary_create_time' => 'datetime',
        'dictionary_create_user_guid' => 'string',
        'dictionary_update_time' => 'datetime',
        'dictionary_update_user_guid' => 'string',
        'dictionary_delete_time' => 'datetime',
        'dictionary_delete_user_guid' => 'string',
        'dictionary_guid' => 'string',
    ];
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    // 创建时间
    protected $createTime = 'dictionary_create_time';
    // 修改时间
    protected $updateTime = 'dictionary_update_time';
    // 状态查询范围
    public function scopeStatus($query, $status = 1)
    {
        $query->where('dictionary_status', $status);
    }

    /**
     * 新增前
     *
     * @date 2022-02-22
     * @example
     * @author admin
     * @since 1.0.0
     */
    public static function onBeforeInsert(self $model): void
    {
        $model->dictionary_status = 1;
        $model->completeCreateField();
    }

    /**
     * 更新前
     *
     * @date 2022-02-28
     * @example
     * @author admin
     * @since 1.0.0
     */
    public static function onBeforeUpdate(self $model): void
    {
        $model->completeUpdateField();
    }

    /**
     * 删除前
     *
     * @date 2022-02-28
     * @example
     * @author admin
     * @since 1.0.0
     */
    public static function onBeforeDelete(self $model): void
    {
        $model->completeDeleteField();
    }

    /**
     * 获取状态
     *
     * @param mixed $value
     * @param array $data
     * @date 2022-02-22
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function getDictionaryStatusTextAttr($value, $data): string
    {
        return [
            1 => '启用',
            2 => '停用'
        ][$data['dictionary_status']];
    }

    /**
     * 创建人
     *
     * @date 2022-02-22
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function createUser(): HasOne
    {
        return $this->hasOne(User::class, 'user_create_user_id');
    }

    /**
     * 更新人
     *
     * @date 2022-02-22
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function updateUser(): HasOne
    {
        return $this->hasOne(User::class, 'user_update_user_id');
    }

    /**
     * 删除人
     *
     * @date 2022-02-22
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function deleteUser(): HasOne
    {
        return $this->hasOne(User::class, 'user_delete_user_id');
    }


    /**
     * 导入前初始化
     */
    public static function importInit($value)
    {
        // 上级判断
        if (isset($value['dictionary_parent_name']) && $value['dictionary_parent_name']) {
            $dictionary = self::where('dictionary_name', $value['dictionary_parent_name'])->find();
            if (!$dictionary) throwErrorMsg("{$value['dictionary_parent_name']} 上级字典不存在");
            $value['dictionary_parent_guid'] = $dictionary->dictionary_guid;
        } else {
            $value['dictionary_parent_guid'] = 0;
        }

        return self::create([
            'dictionary_parent_guid' => $value['dictionary_parent_guid'],
            'dictionary_name' => $value['dictionary_name'],
            'dictionary_value' => $value['dictionary_value'],
            'dictionary_index' => $value['dictionary_index'],
            'dictionary_order' => $value['dictionary_order'],
            'dictionary_status' => 1,
            'dictionary_allow_update' => 1,
            'dictionary_list_class' => $value['dictionary_list_class'],
        ]);
    }

    /**
     * 导入字典
     */
    public static function importExcel($file)
    {
        $error = [];

        Db::startTrans();
        try {

            $excel = new Excel($file);
            $data = $excel->parseExcel(
                [
                    [
                        'title' => '上级字典',
                        'field' => 'dictionary_parent_name',
                    ], [
                        'title' => '名称',
                        'validate' => 'require',
                        'field' => 'dictionary_name',
                    ], [
                        'title' => '值',
                        'validate' => 'require',
                        'field' => 'dictionary_value',
                    ], [
                        'title' => '层级',
                        'validate' => 'require',
                        'field' => 'dictionary_index',
                    ], [
                        'title' => '排序',
                        'validate' => 'require',
                        'field' => 'dictionary_order',
                    ], [
                        'title' => '回显',
                        'field' => 'dictionary_list_class',
                    ]
                ],
                [
                    'titleLine' => [1]
                ]
            );
            if (!$data)  throwErrorMsg('excel无数据', 1);
            $error = [];
            foreach ($data as $line => $value) {
                try {
                    $model = self::importInit($value);
                    $error[] = "{$line}  字典:【{$value['dictionary_name']}】<span style='color:#27af49'>新增成功!</span><br>";
                } catch (\Throwable $th) {
                    $error[] = "{$line}  字典:【{$value['dictionary_name']}】<span style='color:red'>{$th->getMessage()}</span><br>";
                }
            }
            Db::commit();

            return implode(', ', $error);
        } catch (\Throwable $th) {
            Db::rollback();
            throw $th;
        }
    }

    /**
     * 获取字典数据(二级)
     * 
     * @param string $dictionary_value 字典模块字段值
     * @param array $field 字段筛选
     */
    public static function getDictionaryData(string $dictionary_value, array $field = ['dictionary_name', 'dictionary_value']): array
    {
        $dictionary = self::where('dictionary_value', $dictionary_value)->find();
        if (!$dictionary) throwErrorMsg("字典数据不存在dictionary_value值为{$dictionary_value}的数据!");
        return self::field($field)->where('dictionary_parent_guid',  $dictionary->dictionary_guid)->select()->toArray();
    }

    /**
     * 获取字典集合(二级)指定字典值的名称
     * 
     * @param array $dictionary_data 字典集合
     * @param string $dictionary_value 字典值
     * @return string|null 
     */
    public static function getDataDictionaryName(array $dictionary_data, string $dictionary_value)
    {
        $dictionary_name = null;
        foreach ($dictionary_data as $dictionary) {
            if ($dictionary['dictionary_value'] == $dictionary_value) {
                $dictionary_name = $dictionary['dictionary_name'];
                break;
            }
        };
        return $dictionary_name;
    }

    /**
     * 获取字典集合(二级)指定字名称的值
     * 
     * @param array $dictionary_data 字典集合
     * @param string $dictionary_name 字典名称
     * @return string|null 
     */
    public static function getDataDictionaryValue(array $dictionary_data, string $dictionary_name)
    {
        $dictionary_value = null;
        foreach ($dictionary_data as $dictionary) {
            if ($dictionary['dictionary_name'] == $dictionary_name) {
                $dictionary_value = $dictionary['dictionary_value'];
                break;
            }
        };
        return $dictionary_value;
    }
}
