<?php

namespace app\common\model\LeaveMessage;

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 LeaveMessage extends BaseModel
{
    use SoftDelete;
    // 删除字段
    protected $deleteTime = 'leave_message_delete_time';
    // 设置主键名
    protected $pk = 'leave_message_guid';
    // 设置废弃字段
    protected $disuse = [];
    // 设置字段信息
    protected $schema = [

        "leave_message_id" => "int",

        "leave_message_guid" => "string",

        "leave_message_content" => "string",

        "leave_message_name" => "string",

        "leave_message_email" => "string",

        "leave_message_phone" => "int",

        "leave_message_status" => "int",

        "leave_message_create_time" => "datetime",

        "leave_message_create_user_guid" => "string",

        "leave_message_update_time" => "datetime",

        "leave_message_update_user_guid" => "string",

        "leave_message_delete_time" => "datetime",

        "leave_message_delete_user_guid" => "string",

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


    // excel导入/下载模板表头
    public const EXCELFIELD = [
        'leave_message_content' => '留言内容',
        'leave_message_name' => '姓名',
        'leave_message_email' => '邮箱',
        'leave_message_phone' => '手机号',
        'leave_message_status' => '留言受理状态',
    ];



    /**
     * 新增前
     */
    public static function onBeforeInsert(self $model): void
    {
        // self::checkRepeatData($model);
        $model->completeCreateField();
    }

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

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


    /**
     * 留言用户
     */
    public static function auditLeaveMessage($params)
    {
        $params_audit_status = $params['leave_message_status'];
        $leave_message_guids_arr = explode(',', $params['leave_message_guid']);
        
        Db::startTrans();
        try {

            if (count($leave_message_guids_arr) > 1) {
                foreach ($leave_message_guids_arr as $key => $value) {
                    self::audit($value,$params);
                }
            } else {
                self::audit($params['leave_message_guid'],$params);
            }

            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            throw $th;
        }
    }

    /**
     * 留言
     */
    public static function audit($value,$params)
    {
        $model = self::where('leave_message_guid', $value)->find();
        if (!$model) throwErrorMsg("该留言不存在", 1);

        $audit_status = $model->leave_message_status;
        $leave_message_name = $model->leave_message_name;

        if ($audit_status == 2) throwErrorMsg("{$leave_message_name} 已通过留言！");

        $model->allowField([
            'leave_message_status',
        ])->save($params);
    }


    /**
     * 导出Excel
     */
    public static function exportExcel($select)
    {
        $data = [[
            '留言内容',
            '姓名',
            '邮箱',
            '手机号',
            '留言受理状态'
        ]];
        foreach ($select as $key => $val) {
            $data[] = [
                $val['leave_message_content'],
                $val['leave_message_name'],
                $val['leave_message_email'],
                $val['leave_message_phone'],
                $val['leave_message_status'],
            ];
        }
        $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'>新增成功!</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)
    {
        $leave_message_content = $value['leave_message_content'];
        $leave_message_name = $value['leave_message_name'];
        $leave_message_email = $value['leave_message_email'];
        $leave_message_phone = $value['leave_message_phone'];
        $leave_message_status = $value['leave_message_status'];
        return self::create([
            'leave_message_content' => $leave_message_content,
            'leave_message_name' => $leave_message_name,
            'leave_message_email' => $leave_message_email,
            'leave_message_phone' => $leave_message_phone,
            'leave_message_status' => $leave_message_status,
        ]);
    }
}
