<?php

namespace app\common\model\ContactUs;

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\Dictionary\Dictionary as ModelDictionary;

class Signup extends BaseModel
{
    use SoftDelete;
    // 删除字段
    protected $deleteTime = 'signup_delete_time';
    // 设置主键名
    protected $pk = 'signup_guid';
    // 设置废弃字段
    protected $disuse = [];
    // 设置字段信息
    protected $schema = [
        "signup_id" => "int",
        "signup_guid" => "string",
        "signup_user_name" => "string",
        "signup_user_phone" => "string",
        "signup_user_parents_phone" => "string",
        "signup_user_home_address" => "string",
        "signup_user_original_school" => "string",
        "signup_user_arrival_time" => "datetime",
        "classes_guid" => "string",
        "signup_user_grad_type" => "int",
        "signup_status" => "int",
        "signup_create_time" => "datetime",
        "signup_create_user_guid" => "string",
        "signup_update_time" => "datetime",
        "signup_update_user_guid" => "string",
        "signup_delete_time" => "datetime",
        "signup_delete_user_guid" => "string",
    ];
    // 设置json类型字段
    protected $json = [''];
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    // 创建时间
    protected $createTime = 'signup_create_time';
    // 修改时间
    protected $updateTime = 'signup_update_time';

    // excel导出模板表头
    public const EXPORT_EXCEL_FIELD = [
        'signup_user_name' => '用户名称',
        'signup_user_phone' => '用户电话',
        'signup_user_parents_phone' => '家长电话',
        'signup_user_home_address' => '家庭地址',
        'signup_user_original_school' => '原就读学校',
        'signup_user_arrival_time' => '预计到校时间',
        'classes_name' => '所择班级',
        'signup_user_grad_type' => '毕业类型',
        'signup_status' => '报名受理状态',
        'signup_create_time' => '报名时间',
    ];

    /**
     * 新增前
     */
    public static function onBeforeInsert(self $model): void
    {
        BaseModel::setUserGuid(false);
        Tool::initModelFieldValue($model, ['signup_status' => 2]);
        $model->completeCreateField();
    }

    /**
     * 更新前
     */
    public static function onBeforeUpdate(self $model): void
    {
        $model->completeUpdateField();
    }

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

    /**
     * 状态受理
     * 
     */
    public static function handleStatus(\app\Request $request): string
    {
        $params = $request->param();
        self::dataValidate($params, ['signup_guid|在线报名guid' => 'require',]);

        $msg_data = [];
        $signup_guids = explode(',', $params['signup_guid']);
        $signup_guids_count = count($signup_guids);
        foreach ($signup_guids  as $line => $signup_guid) {
            $prefix_text = ($signup_guids_count != 1) ? "第" . ($line + 1) . "行-> " : null;
            try {
                $signup = self::where('signup_guid', $signup_guid)->find();
                if (!$signup) throwErrorMsg('该在线报名数据不存在!');
                if ($signup->signup_status == 1)  throwErrorMsg('该在线报名数据已处理!');
                $signup->signup_status = 1;
                $signup->save();
                $msg_data[] = $prefix_text . "用户名称【{$signup->signup_user_name}】: <span style='color:#27af49'>受理成功!</span>";
            } catch (\Throwable $th) {
                $msg_data[] = $prefix_text . "用户名称:【{$signup->signup_user_name}】: <span style='color:red'>{$th->getMessage()}</span>";
            }
        };

        return implode('<br>', $msg_data);
    }

    /**
     * 导出Excel
     * 
     * @param array $select 导出的数据
     */
    public static function exportExcel(array $select): void
    {
        $processing_state_data = ModelDictionary::getDictionaryData('processing_state');
        $graduation_type_data = ModelDictionary::getDictionaryData('graduation_type');

        $export_excel_fields = self::EXPORT_EXCEL_FIELD;
        $data = [array_values($export_excel_fields)];
        foreach ($select as $key => $val) {
            foreach (array_keys($export_excel_fields) as $field_name) {
                $value = $val[$field_name];
                switch ($field_name) {
                    case 'signup_status': //毕业类型
                        $value =  ModelDictionary::getDataDictionaryName($processing_state_data, $value);
                        break;
                    case 'signup_user_grad_type': //报名受理状态
                        $value =  ModelDictionary::getDataDictionaryName($graduation_type_data, $value);
                        break;
                }
                $data[$key + 1][$field_name] = $value;
            }
        }
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('在线报名.xlsx');
    }
}
