<?php

namespace app\common\model\Works;

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\exception\Tool;
use think\facade\Db;

class WorksType extends BaseModel
{
    use SoftDelete;
    // 删除字段
    protected $deleteTime = 'works_type_delete_time';
    // 设置主键名
    protected $pk = 'works_type_guid';
    // 设置废弃字段
    protected $disuse = [];
    // 设置字段信息
    protected $schema = [
        "works_type_id" => "int",
        "works_type_guid" => "string",
        "works_type_name" => "string",
        "works_type_order" => "int",
        "works_type_create_time" => "datetime",
        "works_type_create_user_guid" => "string",
        "works_type_update_time" => "datetime",
        "works_type_update_user_guid" => "string",
        "works_type_delete_time" => "datetime",
        "works_type_delete_user_guid" => "string",
        "works_type_parent_guid" => "string",
        "works_type_ancestors_guid" => "string",

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

    //排序字段
    public $order_field = 'works_type_order';
    //父级主键
    public $parent_guid_field = 'works_type_parent_guid';
    //祖级主键集字段
    public $ancestors_guid_field = 'works_type_ancestors_guid';

    // excel导入/下载模板表头
    public const IMPORT_EXCEL_FIELD = [
        // 'works_type_parent_name' => '上级类型名称',
        'works_type_name' => '*作品类型名称',
        'works_type_order' => '作品类型排序',
    ];

    /**
     * 新增前
     */
    public static function onBeforeInsert(self $model): void
    {
        Validate::unique(self::class, $model->works_type_guid, $model->getData(), [
            'works_type_name' => '作品类型名称',
        ]);
        Tool::buildAncestorsGuid($model, true);
        Tool::sortInsertProc(
            self::class,
            $model->works_type_order,
            // ['works_type_parent_guid' => $model->works_type_parent_guid]
        );
        $model->completeCreateField();
    }

    /**
     * 更新前
     */
    public static function onBeforeUpdate(self $model): void
    {
        Validate::unique(self::class, $model->works_type_guid, $model->getData(), [
            'works_type_name' => '作品类型名称',
        ]);
        // Tool::handleEthicalRel($model);
        Tool::buildAncestorsGuid($model, true);
        Tool::sortEditProc(
            self::class,
            $model->works_type_guid,
            $model->works_type_order,
            // ["works_type_parent_guid" =>  $model->works_type_parent_guid],
        );
        $model->completeUpdateField();
    }

    /**
     * 删除前
     */
    public static function onBeforeDelete(self $model): void
    {
        Tool::sortDeleteProc(self::class, $model->works_type_guid, ["works_type_parent_guid"]);
        $model->completeDeleteField();
    }

    /**
     * 导出Excel
     * 
     * @param array $select 导出的数据
     */
    public static function exportExcel(array $select): void
    {
        $data = [[
            '作品类型名称',
            '作品类型排序'
        ]];
        foreach ($select as $key => $val) {
            $data[] = [
                // $val['works_type_parent_name'] ?? "无",
                $val['works_type_name'],
                strval($val['works_type_order']),
            ];
        }
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('作品类型.xlsx');
    }

    /**
     * 导入excel
     * 
     * @param \app\common\arw\adjfut\src\UploadFile $file excel
     */
    public static function importExcel(\app\common\arw\adjfut\src\UploadFile $file): string
    {
        $msg = [];

        Db::startTrans();
        try {
            $excel = new Excel($file);
            $data = $excel->parseExcel(
                Tool::getExcelRule(self::IMPORT_EXCEL_FIELD),
                ['titleLine' => [1]]
            );
            if (!$data)  throwErrorMsg('excel无数据', 1);
            $msg = [];
            foreach ($data as $line => $value) {
                try {
                    $op = self::importExcelInit($value);
                    if ($op == 'create') {
                        $msg[] = "{$line} <span style='color:#27af49'>新增成功!</span><br>";
                    } else {
                        $msg[] = "{$line} <span style='color:#ce723b'>修改成功!</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初始化
     * 
     * @param array $value 每行数据
     */
    public static function importExcelInit(array $value): string
    {
        // $works_type_parent_name = $value['works_type_parent_name'];
        $works_type_name = $value['works_type_name'];
        $works_type_order = $value['works_type_order'] ?? 0;

        //上级类型验证
        // $works_type_parent_guid = "0";
        // if ($works_type_parent_name) {
        //     $works_type_parent = self::where('works_type_name', $works_type_parent_name)->find();
        //     if (!$works_type_parent) throwErrorMsg('该上级类型名称不存在!');
        //     $works_type_parent_guid = $works_type_parent->works_type_guid;
        // }

        //修改/新增
        if ($works_type = self::where('works_type_name', $works_type_name)->find()) {
            $works_type->works_type_name = $works_type_name;
            $works_type->works_type_order = $works_type_order;
            // $works_type->works_type_parent_guid = $works_type_parent_guid;
            $works_type->save();
            return 'update';
        } else {
            self::create([
                'works_type_name' => $works_type_name,
                'works_type_order' => $works_type_order,
                // 'works_type_parent_guid' => $works_type_parent_guid,
            ]);
            return 'create';
        }
    }
}
