<?php

namespace app\common\model\HonoraryAchievement;

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\HonoraryAchievement\SchoolCategory as ModelSchoolCategory;

class SchoolLeaders extends BaseModel
{
    use SoftDelete;
    // 删除字段
    protected $deleteTime = 'school_leaders_delete_time';
    // 设置主键名
    protected $pk = 'school_leaders_guid';
    // 设置废弃字段
    protected $disuse = [];
    // 设置字段信息
    protected $schema = [

        "school_leaders_id" => "int",

        "school_leaders_name" => "string",

        "school_category_guid" => "string",

        "school_leaders_name" => "string",

        "school_leaders_school" => "string",

        "school_leaders_img" => "string",

        "school_leaders_sort" => "int",

        "school_leaders_create_time" => "datetime",

        "school_leaders_create_user_guid" => "string",

        "school_leaders_update_time" => "datetime",

        "school_leaders_update_user_guid" => "string",

        "school_leaders_delete_time" => "datetime",

        "school_leaders_delete_user_guid" => "string",

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


    // excel导入/下载模板表头
    public const EXCELFIELD = [
        'school_category_name' => '录取院校',
        'school_leaders_name' => '领军者名称',
        'school_leaders_school' => '领军者所属院校',
        'school_leaders_sort' => '领军者排序',
    ];



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

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

    /**
     * 更新前
     */
    public static function onBeforeUpdate(self $model): void
    {
        Tool::sortEditProc(
            self::class,
            $model->school_leaders_guid,
            $model->school_leaders_sort,
            ['school_category_guid' => $model->school_category_guid]
        );
        $model->completeUpdateField();
    }

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

    /**
     * 导出Excel
     */
    public static function exportExcel($select)
    {
        $data = [[
            '录取院校',
            '名称',
            '所属院校',
            '图片',
            '排序'
        ]];
        foreach ($select as $key => $val) {
            $data[] = [
                $val['school_category_name'],
                $val['school_leaders_name'],
                $val['school_leaders_school'],
                Excel::ExportImgFiled($val['school_leaders_img']),
                $val['school_leaders_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) {
                try {
                    $model = self::importExcelInit($value);
                    $msg[] = "{$line} <span style='color:#27af49'>【{$model->school_category_name}】的{$model->school_leaders_name} 新增成功!</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)
    {
        $school_category_name = $value['school_category_name'];
        $school_leaders_name = $value['school_leaders_name'];
        $school_leaders_school = $value['school_leaders_school'];
        $school_leaders_sort = $value['school_leaders_sort'];

        // 录取院校
        $school_category = ModelSchoolCategory::where('school_category_name',$school_category_name)->find();
        if(!$school_category) throwErrorMsg( $school_category_name . " 录取院校不存在！");
        else $school_category_guid = $school_category->school_category_guid;

        $model = self::create([
            'school_category_guid' => $school_category_guid,
            'school_leaders_name' => $school_leaders_name,
            'school_leaders_school' => $school_leaders_school,
            'school_leaders_sort' => $school_leaders_sort,
        ]);

        $model['school_category_name'] =  $school_category_name;
        return  $model;
    }
}
