<?php

namespace app\common\model\Tdk;

use app\common\arw\adjfut\src\Validate;
use app\BaseModel;
use think\model\concern\SoftDelete;
use app\common\arw\adjfut\src\Excel;
use app\Request;
use app\common\model\Dictionary\Dictionary as ModelDictionary;
use app\common\exception\Tool;
use think\facade\Db;

class Tdk extends BaseModel
{
    use SoftDelete;
    // 删除字段
    protected $deleteTime = 'tdk_delete_time';
    // 设置主键名
    protected $pk = 'tdk_guid';
    // 设置废弃字段
    protected $disuse = [];
    // 设置字段信息
    protected $schema = [

        "tdk_id" => "int",

        "tdk_guid" => "string",

        "tdk_type" => "string",

        "tdk_title" => "string",

        "tdk_description" => "string",

        "tdk_keyword" => "string",

        "tdk_create_time" => "datetime",

        "tdk_create_user_guid" => "string",

        "tdk_update_time" => "datetime",

        "tdk_update_user_guid" => "string",

        "tdk_delete_time" => "datetime",

        "tdk_delete_user_guid" => "string",

    ];
    // 设置json类型字段
    protected $json = [''];
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    // 创建时间
    protected $createTime = 'tdk_create_time';
    // 修改时间
    protected $updateTime = 'tdk_update_time';


    // excel导入/下载模板表头
    public const EXCELFIELD = [
        'tdk_type' => 'tdk所属模块',
        'tdk_title' => '网页标题',
        'tdk_description' => '网页简介',
        'tdk_keyword' => '网页关键词',
    ];



    /**
     * 新增前
     */
    public static function onBeforeInsert(self $model): void
    {
        Validate::unique(
            self::class,
            $model->tdk_guid,
            $model->getData(),
            ['tdk_type' => 'tdk模块',],
            ['tdk_type' => '一个tdk模块只能拥有一个tdk数据']
        );
        $model->completeCreateField();
    }

    /**
     * 更新前
     */
    public static function onBeforeUpdate(self $model): void
    {
        $model->completeUpdateField();
    }

    /**
     * 删除前
     */
    public static function onBeforeDelete(self $model): void
    {
        $model->completeDeleteField();
    }

    /**
     * 导出Excel
     */
    public static function exportExcel($select)
    {
        $data = [[
            'tdk所属模块',
            '网页标题',
            '网页简介',
            '网页关键词'
        ]];
        foreach ($select as $key => $val) {
            // 字典取值
            $tdk_type = ModelDictionary::getDictionaryData('tdk_type');
            $val['tdk_type'] =  ModelDictionary::getDataDictionaryName($tdk_type, $val['tdk_type']);

            $data[] = [
                $val['tdk_type'],
                $val['tdk_title'],
                $val['tdk_description'],
                $val['tdk_keyword'],
            ];
        }
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('网站tdk.xlsx');
    }

    /**
     * 导入excel
     */
    public static function importExcel($file)
    {
        $msg = [];

        Db::startTrans();
        try {
            $excel = new Excel($file);
            $data = $excel->parseExcel(
                Tool::getExcelRule(self::EXCELFIELD),
                [
                    'titleLine' => [1]
                ]
            );
            if (!$data)  throwErrorMsg('excel无数据', 1);
            $msg = [];
            foreach ($data as $line => $value) {
                try {
                    $model = self::importExcelInit($value);
                    $msg[] = "{$line} <span style='color:#27af49'>新增成功!</span><br>";
                } catch (\Throwable $th) {
                    $msg[] = "{$line} <span style='color:red'>{$th->getMessage()}</span><br>";
                }
            }
            Db::commit();
            return implode(', ', $msg);
        } catch (\Throwable $th) {
            Db::rollback();
            throw $th;
        }
    }

    /**
     * 导入excel初始化
     */
    public static function importExcelInit($value)
    {
        $tdk_type = $value['tdk_type'];
        $tdk_title = $value['tdk_title'];
        $tdk_description = $value['tdk_description'];
        $tdk_keyword = $value['tdk_keyword'];

        // 字典设值
        $dic_tdk_type = ModelDictionary::getDictionaryData('tdk_type');
        $tdk_type =  ModelDictionary::getDataDictionaryValue($dic_tdk_type, $value['tdk_type']);

        return self::create([
            'tdk_type' => $tdk_type,
            'tdk_title' => $tdk_title,
            'tdk_description' => $tdk_description,
            'tdk_keyword' => $tdk_keyword,
        ]);
    }
}
