<?php

namespace app\common\model\Enrol;

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

        "classes_id" => "int",

        "classes_guid" => "string",

        "classes_name" => "string",

        "classes_cover" => "string",

        "classes_desc" => "string",

        "classes_content" => "string",

        "classes_status" => "int",

        "classes_sort" => "int",

        "classes_create_time" => "datetime",

        "classes_create_user_guid" => "string",

        "classes_update_time" => "datetime",

        "classes_update_user_guid" => "string",

        "classes_delete_time" => "datetime",

        "classes_delete_user_guid" => "string",

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

    // excel导入/下载模板表头
    public const EXCELFIELD = [
        'classes_name' => '名称',
        'classes_desc' => '简介',
        'classes_sort' => '排序',
    ];


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

    /**
     * 新增前
     */
    public static function onBeforeInsert(self $model): void
    {
        Validate::unique(self::class, $model->classes_guid, $model->getData(), [
            'classes_name' => '班型名称',
        ]);
        Tool::sortInsertProc(
            self::class,
            $model->classes_sort,
        );
        $model->completeCreateField();
    }

    /**
     * 更新前
     */
    public static function onBeforeUpdate(self $model): void
    {
        Validate::unique(self::class, $model->classes_guid, $model->getData(), [
            'classes_name' => '班型名称',
        ]);
        Tool::sortEditProc(
            self::class,
            $model->classes_guid,
            $model->classes_sort,
        );
        $model->completeUpdateField();
    }

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

    /**
     * 导出Excel
     */
    public static function exportExcel($select)
    {
        $data = [[
            '班型名称',
            '班型封面',
            '班型简介',
            '班型排序'
        ]];
        foreach ($select as $key => $val) {
            $data[] = [
                $val['classes_name'],
                Excel::ExportImgFiled($val['classes_cover']),
                $val['classes_desc'],
                $val['classes_sort'],
            ];
        }
        $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) {
                $classes_name = $value['classes_name'];
                try {
                    $model = self::importExcelInit($value);
                    $msg[] = "{$line} <span style='color:#27af49'>{$classes_name} 新增成功!</span><br>";
                } catch (\Throwable $th) {
                    $msg[] = "{$line} <span style='color:red'>{$classes_name} {$th->getMessage()}</span><br>";
                }
            }
            Db::commit();
            return implode(', ', $msg);
        } catch (\Throwable $th) {
            Db::rollback();
            throw $th;
        }
    }

    /**
     * 导入excel初始化
     */
    public static function importExcelInit($value)
    {
        $classes_name = $value['classes_name'];
        $classes_desc = $value['classes_desc'];
        $classes_sort = $value['classes_sort'];
        return self::create([
            'classes_name' => $classes_name,
            'classes_desc' => $classes_desc,
            'classes_sort' => $classes_sort,
        ]);
    }
}
