<?php

namespace app\common\model\Product;

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 ProductType extends BaseModel
{
    use SoftDelete;
    // 删除字段
    protected $deleteTime = 'product_type_delete_time';
    // 设置主键名
    protected $pk = 'product_type_guid';
    // 设置废弃字段
    protected $disuse = [];
    // 设置字段信息
    protected $schema = [
        "product_type_id" => "int",
        "product_type_guid" => "string",
        "product_type_name" => "string",
        "product_type_parent_guid" => "string",
        "product_type_ancestors_guid" => "string",
        "product_type_icon" => "string",
        "product_type_cover" => "string",
        "product_type_order" => "int",
        "product_type_create_time" => "datetime",
        "product_type_create_user_guid" => "string",
        "product_type_update_time" => "datetime",
        "product_type_update_user_guid" => "string",
        "product_type_delete_time" => "datetime",
        "product_type_delete_user_guid" => "string",
    ];
    // 设置json类型字段
    protected $json = [''];
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    // 创建时间
    protected $createTime = 'product_type_create_time';
    // 修改时间
    protected $updateTime = 'product_type_update_time';

    // excel导入/下载模板表头
    public const EXCELFIELD = [
        'product_type_name' => '产品系列名称',
        'product_type_icon' => '产品系列图标',
        'product_type_cover' => '产品系列封面',
    ];

    /**
     * 新增前
     */
    public static function onBeforeInsert(self $model): void
    {
        // self::checkRepeatData($model);
        $model->completeCreateField();
    }

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

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

    /**
     * 产品系列祖级guid构建
     * 
     * @param string $product_type_parent_guid 产品系列父级guid
     */
    public static function buildAncestorsGuid(string $product_type_parent_guid): string
    {
        if ($product_type_parent_guid == "0") return  $product_type_parent_guid;
        $product_type = self::where('product_type_guid', $product_type_parent_guid)->find();
        if (!$product_type) throwErrorMsg('该父级产品系列不存在!');
        return  $product_type->product_type_ancestors_guid . ',' . $product_type_parent_guid;
    }

    /**
     * 产品系列重名验证
     * 
     * @param string $product_type_name 产品系列名称
     * @param string $product_type_guid 产品系列guid
     */
    public static function isDuplicateName(string $product_type_name, string $product_type_guid = null): void
    {
        $con = [
            ['product_type_name', '=', $product_type_name]
        ];
        if ($product_type_guid) {
            $con[] = ['product_type_guid', '<>', $product_type_guid];
        }
        if (self::where($con)->find()) {
            throwErrorMsg('产品系列不可重名!');
        };
    }

    /**
     * 导出Excel
     */
    public static function exportExcel($select)
    {
        $data = [[
            '产品系列标题',
            '产品系列图标',
            '产品系列封面'
        ]];
        foreach ($select as $key => $val) {
            $data[] = [
                $val['product_type_title'],
                $val['product_type_icon'],
                Excel::ExportImgFiled($val['product_type_cover']),
            ];
        }
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('产品系列.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)
    {
        $product_type_title = $value['product_type_title'];
        $product_type_icon = $value['product_type_icon'];
        $product_type_cover = $value['product_type_cover'];
        return self::create([
            'product_type_title' => $product_type_title,
            'product_type_icon' => $product_type_icon,
            'product_type_cover' => $product_type_cover,
        ]);
    }
}
