<?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 PSpell\Dictionary;
use think\facade\Db;
use app\common\model\HonoraryAchievement\SchoolCategory as ModelSchoolCategory;

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

        "achievement_id" => "int",

        "achievement_guid" => "string",

        "school_category_guid" => "string",

        "achievement_title" => "string",

        "achievement_content" => "string",

        "achievement_sub_content" => "string",

        "achievement_sort" => "string",

        "achievement_create_time" => "datetime",

        "achievement_create_user_guid" => "string",

        "achievement_update_time" => "datetime",

        "achievement_update_user_guid" => "string",

        "achievement_delete_time" => "datetime",

        "achievement_delete_user_guid" => "string",

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


    // excel导入/下载模板表头
    public const EXCELFIELD = [
        'school_category_name' => '录取院校',
        'achievement_title' => '标题',
        'achievement_content' => '内容',
        'achievement_sub_content' => '副内容',
        'achievement_sort' => '排序',
    ];

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

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

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

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


    /**
     * 导出Excel
     */
    public static function exportExcel($select)
    {
        $data = [[
            '录取院校',
            '标题',
            '内容',
            '副内容',
            '排序'
        ]];
        foreach ($select as $key => $val) {
            $data[] = [
                $val['school_category_name'],
                $val['achievement_title'],
                $val['achievement_content'],
                $val['achievement_sub_content'],
                $val['achievement_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->achievement_title}数据 新增成功!</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'];
        $achievement_title = $value['achievement_title'];
        $achievement_content = $value['achievement_content'];
        $achievement_sub_content = $value['achievement_sub_content'];
        $achievement_sort = $value['achievement_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,
            'achievement_title' => $achievement_title,
            'achievement_content' => $achievement_content,
            'achievement_sub_content' => $achievement_sub_content,
            'achievement_sort' => $achievement_sort,
        ]);

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