<?php

namespace app\common\model\TeachersStrength;

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 Overtrue\Pinyin\Pinyin;
use app\common\model\TeachersStrength\Subject as ModelSubject;

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

        "teacher_id" => "int",

        "teacher_guid" => "string",

        "teacher_name" => "string",

        "teacher_position" => "string",

        "teacher_img" => "string",

        "teacher_content" => "string",

        "subject_guid" => "string",

        "teacher_intro" => "string",
           
        "teacher_status" => "int",

        "teacher_order" => "int",

        "teacher_create_time" => "datetime",

        "teacher_create_user_guid" => "string",

        "teacher_update_time" => "datetime",

        "teacher_update_user_guid" => "string",

        "teacher_delete_time" => "datetime",

        "teacher_delete_user_guid" => "string",

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


    // excel导入/下载模板表头
    public const EXCELFIELD = [
        'subject_name' => '授教科目',
        'teacher_name' => '教师名称',
        'teacher_position' => '教师职位',
        'teacher_intro' => '教师简介',
        'teacher_order' => '教师排序',
    ];


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

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

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

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

    /**
     * 导出Excel
     */
    public static function exportExcel($select)
    {
        $data = [[
            '授教科目',
            '教师名称',
            '教师职位',
            '教师图片',
            '授课科目',
            '教师简介',
            '教师排序'
        ]];
        foreach ($select as $key => $val) {
            $data[] = [
                $val['subject_name'],
                $val['teacher_name'],
                $val['teacher_position'],
                Excel::ExportImgFiled($val['teacher_img']),
                $val['subject_guid'],
                $val['teacher_intro'],
                $val['teacher_order'],
            ];
        }
        $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->subject_name}】{$model->teacher_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)
    {
        $subject_name = $value['subject_name'];
        $teacher_name = $value['teacher_name'];
        $teacher_position = $value['teacher_position'];
        $teacher_intro = $value['teacher_intro'];
        $teacher_order = $value['teacher_order'];

        // 授教科目
        $subject = ModelSubject::where('subject_name',$subject_name)->find();
        if(!$subject) throwErrorMsg($subject_name . " 授教科目不存在！");
        else $subject_guid = $subject->subject_guid;

        $model = self::create([
            'teacher_name' => $teacher_name,
            'teacher_position' => $teacher_position,
            'subject_guid' => $subject_guid,
            'teacher_intro' => $teacher_intro,
            'teacher_order' => $teacher_order,
        ]);

        $model['subject_name'] = $subject->subject_name;
        return $model;
    }

    // 获取器 - 中文转拼音(全部大写)
    public function getTeacherEngNameAttr($value, $data)
    {
        $teacher_name =  $data['teacher_name'];

        // 实例化拼音转换库
        $pinyin = new Pinyin();
    
        // 将中文转换为拼音
        $teacher_eng_name = $pinyin->abbr($teacher_name);
    
        // 将拼音转换为大写字母
        $teacher_eng_name = strtoupper("$teacher_eng_name");
    
        return $teacher_eng_name;
    }
}
