<?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;
use app\common\model\Works\WorksType as ModelWorksType;
use app\common\model\Enrol\Classes as ModelClasses;

class Works extends BaseModel
{
    use SoftDelete;
    // 删除字段
    protected $deleteTime = 'works_delete_time';
    // 设置主键名
    protected $pk = 'works_guid';
    // 设置废弃字段
    protected $disuse = [];
    // 设置字段信息
    protected $schema = [
        "works_id" => "int",
        "works_guid" => "string",
        "works_name" => "string",
        "works_author" => "string",
        "classes_guid" => "string",
        "works_img" => "string",
        "works_intro" => "string",
        "works_type_guid" => "string",
        "works_likes_count" => "int",
        "works_order" => "int",
        "works_create_time" => "datetime",
        "works_create_user_guid" => "string",
        "works_update_time" => "datetime",
        "works_update_user_guid" => "string",
        "works_delete_time" => "datetime",
        "works_delete_user_guid" => "string",
    ];
    // 设置json类型字段
    protected $json = [''];
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    // 创建时间
    protected $createTime = 'works_create_time';
    // 修改时间
    protected $updateTime = 'works_update_time';

    //排序字段
    public $order_field = 'works_order';

    // excel导出模板表头
    public const EXPORT_EXCEL_FIELD = [
        'works_type_name' => '作品类型',
        'works_img' => '作品图片',
        'works_name' => '作品名称',
        'works_author' => '作品作者',
        'classes_name' => '班型名称',
        'works_likes_count' => '点赞数',
    ];
    // excel导入/下载模板表头
    public const IMPORT_EXCEL_FIELD = [
        'works_type_name' => '*作品类型',
        'works_name' => '*作品名称',
        'works_author' => '*作品作者',
        'classes_name' => '*班型名称',
        'works_likes_count' => '作品点赞数',
        'works_order' => '排序',
    ];

    /**
     * 新增前
     */
    public static function onBeforeInsert(self $model): void
    {
        Tool::sortInsertProc(self::class, $model->works_order, ['works_type_guid' => $model->works_type_guid]);
        $model->completeCreateField();
    }

    /**
     * 更新前
     */
    public static function onBeforeUpdate(self $model): void
    {
        BaseModel::setUserGuid(false);
        Tool::sortEditProc(self::class, $model->works_guid, $model->works_order, ['works_type_guid' => $model->works_type_guid]);
        $model->completeUpdateField();
    }

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

    /**
     * 导出Excel
     * 
     * @param array $select 导出的数据
     */
    public static function exportExcel(array $select): void
    {
        $data = [array_values(self::EXPORT_EXCEL_FIELD)];
        foreach ($select as $key => $val) {
            foreach (array_keys(self::EXPORT_EXCEL_FIELD) as $field_name) {
                $value = $val[$field_name];
                if ($field_name == 'works_img') $value =  Excel::ExportImgFiled($value);
                if ($field_name == 'works_likes_count') $value =  strval($value);
                $data[$key + 1][$field_name] = $value;
            }
        }
        $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 {
                    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): void
    {
        $works_type_name = $value['works_type_name'];
        $works_name = $value['works_name'];
        $works_author = $value['works_author'];
        $classes_name = $value['classes_name'];
        $works_likes_count =  $value['works_likes_count'] ?? 0;
        $works_order = $value['works_order'] ?? 0;

        $works_type = ModelWorksType::where("works_type_name", $works_type_name)->find();
        if (!$works_type) throwErrorMsg("作品类型不存在!");
        $classes = ModelClasses::where("classes_name", $classes_name)->find();
        if (!$classes) throwErrorMsg("班型不存在!");

        self::create([
            'works_type_guid' => $works_type->works_type_guid,
            'classes_guid' => $classes->classes_guid,
            'works_name' => $works_name,
            'works_author' => $works_author,
            'works_likes_count' => $works_likes_count,
            'works_order' => $works_order,
        ]);
    }

    public function getLikeSrcAttr()
    {
        return "/img/business/works/like1.png";
    }
}
