<?php

namespace app\common\model\AboutUs\TeachingEnvir;

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 TeachingEnvirType extends BaseModel
{
    use SoftDelete;
    // 删除字段
    protected $deleteTime = 'teaching_envir_type_delete_time';
    // 设置主键名
    protected $pk = 'teaching_envir_type_guid';
    // 设置废弃字段
    protected $disuse = [];
    // 设置字段信息
    protected $schema = [
        "teaching_envir_type_id" => "int",
        "teaching_envir_type_guid" => "string",
        "teaching_envir_type_name" => "string",
        "teaching_envir_type_order" => "int",
        "teaching_envir_type_create_time" => "datetime",
        "teaching_envir_type_create_user_guid" => "string",
        "teaching_envir_type_update_time" => "datetime",
        "teaching_envir_type_update_user_guid" => "string",
        "teaching_envir_type_delete_time" => "datetime",
        "teaching_envir_type_delete_user_guid" => "string",
        "teaching_envir_type_parent_guid" => "string",
        "teaching_envir_type_ancestors_guid" => "string",
    ];
    // 设置json类型字段
    protected $json = [''];
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    // 创建时间
    protected $createTime = 'teaching_envir_type_create_time';
    // 修改时间
    protected $updateTime = 'teaching_envir_type_update_time';

    //排序字段
    public $order_field = 'teaching_envir_type_order';
    //父级主键
    public $parent_guid_field = 'teaching_envir_type_parent_guid';
    //祖级主键集字段
    public $ancestors_guid_field = 'teaching_envir_type_ancestors_guid';

    // excel导入/下载模板表头
    public const EXCELFIELD = [
        'teaching_envir_type_name' => '*环境类型名称',
        'teaching_envir_type_order' => '环境类型排序',
    ];

    /**
     * 新增前
     */
    public static function onBeforeInsert(self $model): void
    {
        Validate::unique(self::class, $model->teaching_envir_type_guid, $model->getData(), [
            'teaching_envir_type_name' => '环境类型名称',
        ]);
        Tool::buildAncestorsGuid($model, true);
        Tool::sortInsertProc(
            self::class,
            $model->teaching_envir_type_order,
            // ['teaching_envir_type_parent_guid' => $model->teaching_envir_type_parent_guid]
        );
        $model->completeCreateField();
    }

    /**
     * 更新前
     */
    public static function onBeforeUpdate(self $model): void
    {
        Validate::unique(self::class, $model->teaching_envir_type_guid, $model->getData(), [
            'teaching_envir_type_name' => '环境类型名称',
        ]);
        // Tool::handleEthicalRel($model);
        Tool::buildAncestorsGuid($model, true);
        Tool::sortEditProc(
            self::class,
            $model->teaching_envir_type_guid,
            $model->teaching_envir_type_order,
            // ["teaching_envir_type_parent_guid" =>  $model->teaching_envir_type_parent_guid],
        );
        $model->completeUpdateField();
    }

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

    /**
     * 导出Excel
     * 
     * @param array $select 导出的数据
     */
    public static function exportExcel($select): void
    {
        $data = [[
            '环境类型名称',
            '环境类型排序'
        ]];
        foreach ($select as $key => $val) {
            $data[] = [
                // $val['teaching_envir_type_parent_name'] ?? "无",
                $val['teaching_envir_type_name'],
                strval($val['teaching_envir_type_order']),
            ];
        }
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('教学环境类型.xlsx');
    }

    /**
     * 导入excel
     * 
     * @param \app\common\arw\adjfut\src\UploadFile $file excel
     */
    public static function importExcel($file): string
    {
        $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 {
                    $op = self::importExcelInit($value);
                    if ($op == 'create') {
                        $msg[] = "{$line} 环境类型名:【{$value['teaching_envir_type_name']}】 <span style='color:#27af49'>新增成功!</span><br>";
                    } else {
                        $msg[] = "{$line} 环境类型名:【{$value['teaching_envir_type_name']}】 <span style='color:#ce723b'>修改成功!</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初始化
     * 
     * @param array $value 每行数据
     */
    public static function importExcelInit(array $value): string
    {
        // $teaching_envir_type_parent_name = $value['teaching_envir_type_parent_name'];
        $teaching_envir_type_name = $value['teaching_envir_type_name'];
        $teaching_envir_type_order = $value['teaching_envir_type_order'] ?? 0;

        //上级类型验证
        // $teaching_envir_type_parent_guid = "0";
        // if ($teaching_envir_type_parent_name) {
        //     $teaching_envir_type_parent = self::where('teaching_envir_type_name', $teaching_envir_type_parent_name)->find();
        //     if (!$teaching_envir_type_parent) throwErrorMsg('该上级类型名称不存在!');
        //     $teaching_envir_type_parent_guid = $teaching_envir_type_parent->teaching_envir_type_guid;
        // }

        //修改/新增
        if ($teaching_envir_type = self::where('teaching_envir_type_name', $teaching_envir_type_name)->find()) {
            $teaching_envir_type->teaching_envir_type_name = $teaching_envir_type_name;
            $teaching_envir_type->teaching_envir_type_order = $teaching_envir_type_order;
            // $teaching_envir_type->teaching_envir_type_parent_guid = $teaching_envir_type_parent_guid;
            $teaching_envir_type->save();
            return 'update';
        } else {
            self::create([
                'teaching_envir_type_name' => $teaching_envir_type_name,
                'teaching_envir_type_order' => $teaching_envir_type_order,
                // 'teaching_envir_type_parent_guid' => $teaching_envir_type_parent_guid,
            ]);
            return 'create';
        }
    }
}
