<?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 Product extends BaseModel
{
    use SoftDelete;
    // 删除字段
    protected $deleteTime = 'product_delete_time';
    // 设置主键名
    protected $pk = 'product_guid';
    // 设置废弃字段
    protected $disuse = [];
    // 设置字段信息
    protected $schema = [

        "product_id" => "int",

        "product_guid" => "string",

        "product_type_guid" => "string",

        "product_name" => "string",

        "product_img" => "string",

        "product_params" => "string",

        "product_details" => "string",

        "product_price" => "",

        "product_create_time" => "datetime",

        "product_create_user_guid" => "string",

        "product_update_time" => "datetime",

        "product_update_user_guid" => "string",

        "product_delete_time" => "datetime",

        "product_delete_user_guid" => "string",

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


    // excel导入/下载模板表头
    public const EXCELFIELD = [
        'product_type_guid' => '产品系列',
        'product_name' => '名称',
        'product_img' => '图片',
        'product_params' => '参数',
        'product_details' => '详情',
        'product_price' => '价格',
    ];

    /**
     * 新增前
     */
    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();
    }

    /**
     * 修改器(产品参数)
     */
    public function setProductParamsAttr($value): string
    {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取器(产品参数)
     */
    public function getProductParamsAttr($value): array
    {
        return json_decode($value);
    }

    /**
     * 获取器(产品图片)
     */
    public function getProductImgAttr($value): array
    {
        $data = [];
        foreach (explode(',', $value) as $item) {
            $data[] = ['url' => $item];
        };
        return $data;
    }

    /**
     * 指定产品上下id获取
     * 
     * @param string $product_id 当前产品id
     * @param string $product_type_guid 产品系列guid
     * @return array [上一个id,下一个idF]
     */
    public static function getProductUpAndDownId(string $product_id, string $product_type_guid): array
    {
        $query = function ($op, $order) use ($product_id, $product_type_guid) {
            return  self::where([['product_id', $op, $product_id], ['product_type_guid', '=', $product_type_guid]])
                ->limit(1)
                ->order('product_id', $order)
                ->value('product_id');
        };
        return [$query('<', 'desc'), $query('>', 'asc')];
    }

    /**
     * 导出Excel
     */
    public static function exportExcel($select)
    {
        $data = [[
            '产品系列',
            '名称',
            '图片',
            '参数',
            '详情',
            '价格'
        ]];
        foreach ($select as $key => $val) {
            $data[] = [
                $val['product_type_guid'],
                $val['product_name'],
                Excel::ExportImgFiled($val['product_img']),
                $val['product_params'],
                $val['product_details'],
                $val['product_price'],
            ];
        }
        $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_guid = $value['product_type_guid'];
        $product_name = $value['product_name'];
        $product_img = $value['product_img'];
        $product_params = $value['product_params'];
        $product_details = $value['product_details'];
        $product_price = $value['product_price'];
        return self::create([
            'product_type_guid' => $product_type_guid,
            'product_name' => $product_name,
            'product_img' => $product_img,
            'product_params' => $product_params,
            'product_details' => $product_details,
            'product_price' => $product_price,
        ]);
    }
}
