<?php

namespace app\common\model\School;

use app\common\model\School\StudentService as ModelStudentService;
use app\common\model\User\User as ModelUser;
use app\common\model\School\Classes as ModelClasses;
use app\common\model\Product\ProductType as ModelProductType;
use app\common\model\Product\Product as ModelProduct;
use app\common\model\Product\ProductParts as ModelProductParts;
use app\common\arw\adjfut\src\Validate;
use app\BaseModel;
use think\model\concern\SoftDelete;
use app\Request;
use think\facade\Db;
use app\common\exception\RegularVerification;
use app\common\arw\adjfut\src\Excel;
use app\common\exception\Map;

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

        "student_id" => "int",

        "student_guid" => "string",

        "student_name" => "string",

        "user_guid" => "string",

        "classes_guid" => "string",

        "studnet_phone" => "string",

        "student_id_card" => "string",

        "student_email" => "string",

        "student_sex" => "string",

        "student_price" => "",

        "student_brithday" => "date",

        "product_type" => "string",

        "product_guid" => "string",

        "product_parts_guid" => "string",

        "student_img" => "string",

        "student_banner_img" => "string",

        "student_attachment" => "string",

        "student_intro" => "string",

        "student_location" => "string",

        "longitude" => "string",

        "latitude" => "string",

        "student_membe_type" => "string",

        "student_member_begin_time" => "date",

        "student_member_end_time" => "date",

        "student_audit_status" => "string",

        "student_audit_user_guid" => "string",

        "student_create_time" => "datetime",

        "student_create_user_guid" => "string",

        "student_update_time" => "datetime",

        "student_update_user_guid" => "string",

        "student_delete_time" => "datetime",

        "student_delete_user_guid" => "string",

    ];

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

    /**
     * 新增前
     */
    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 auditStudent($params)
    {
        $params_audit_status = $params['student_audit_status'];
        $student_guids_arr = explode(',', $params['student_guid']);
        
        Db::startTrans();
        try {

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

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

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

        $params['student_audit_user_guid'] = Request::getCurrentUser()->user_guid;

        $audit_status = $model->student_audit_status;
        $student_name = $model->student_name;

        if ($audit_status == 2) throwErrorMsg("{$student_name} 学生已通过审核！");
        if ($audit_status == 3) throwErrorMsg("{$student_name} 学生已驳回审核！");

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

    /**
     * 新增前初始化
     */
    public static function initAdd($params)
    {
        $user = ModelUser::where('user_name', $params['user_name'])->find();
        $params['user_guid'] = $user->user_guid;
        $student_user = self::where('user_guid', $params['user_guid'])->find();
        if ($student_user) throwErrorMsg("用户已经被绑定,请重新选择！");

        $isPhone = RegularVerification::checkPreg($params['studnet_phone'], 'mobile');
        if (!$isPhone) throwErrorMsg("电话格式错误");

        $isIdCard = RegularVerification::checkPreg($params['student_id_card'], 'idcard');
        if (!$isIdCard) throwErrorMsg("身份证格式错误");

        $isEmail = RegularVerification::checkPreg($params['student_email'], 'email');
        if (!$isEmail) throwErrorMsg("邮箱格式错误");

        // 季卡
        if ($params['student_membe_type'] == '1') {
            $params['student_member_begin_time'] = date('Y-m-d H:i:s');
            $params['student_member_end_time'] = date('Y-m-d H:i:s', strtotime('+3 month'));
        }
        // 年卡
        if ($params['student_membe_type'] == '2') {
            $params['student_member_begin_time'] = date('Y-m-d H:i:s');
            $params['student_member_end_time'] = date('Y-m-d H:i:s', strtotime('+1 year'));
        }

        // 已审核
        $params['student_audit_status'] = "1";
        // $params['student_audit_user_guid'] = "ds4a3d2asd423s3as4d34asdd";

        return $params;
    }

    /**
     * 导入前初始化
     */
    public static function ImportStudentInit($value)
    {
        // 用户判断
        $user = ModelUser::where('user_name', $value['user_name'])->find();
        // array_push($error, "{$line}: 产品类型不存在，导入失败!");
        if (!$user) throwErrorMsg("用户 {$value['user_name']} 不存在");
        $value['user_guid'] = $user->user_guid;
        $student_user = self::where('user_guid', $value['user_guid'])->find();
        if ($student_user) throwErrorMsg("用户 {$value['user_name']} 已经被绑定,请重新选择！");

        // 班级判断
        $classes = ModelClasses::where('classes_name', $value['classes_name'])->find();
        if (!$classes) throwErrorMsg("班级不存在");
        $value['classes_guid'] = $classes->classes_guid;


        $isPhone = RegularVerification::checkPreg($value['studnet_phone'], 'mobile');
        if (!$isPhone) throwErrorMsg("电话格式错误");

        // $isIdCard = RegularVerification::checkPreg($value['student_id_card'], 'idcard');
        // if (!$isIdCard) throwErrorMsg("身份证格式错误");

        $isEmail = RegularVerification::checkPreg($value['student_email'], 'email');
        if (!$isEmail) throwErrorMsg("邮箱格式错误");

        $sex_val = [1 => '男', 2 => '女'];


        // 性别判断
        if (!in_array($value['student_sex'], ["男", "女"])) throwErrorMsg("请填写男或女");
        else {
            $value['student_sex'] = array_search($value['student_sex'], $sex_val);
            // if ($value['student_sex'] == "男") $value['student_sex'] = 1;
            // if ($value['student_sex'] == "女") $value['student_sex'] = 2;
        }

        // 价格判断
        if (!is_numeric($value['student_price'])) throwErrorMsg("学生价格必须为整数");
        if ($value['student_price'] < 0) throwErrorMsg("学生价格不能为负数");

        // 产品类型判断
        $product_type = ModelProductType::where('product_type_name', $value['product_type_name'])->find();
        if (!$product_type) throwErrorMsg("{$value['product_type_name']} 产品类型不存在");
        $value['product_type_guid'] = $product_type->product_type_guid;

        // 产品判断
        $product = ModelProduct::where('product_name', $value['product_name'])->find();
        if (!$product) throwErrorMsg("{$value['product_name']} 产品不存在");
        $value['product_guid'] = $product->product_guid;
        $InProductType = ModelProduct::where('product_type_guid', $value['product_type_guid'])->find();
        if (!$InProductType) throwErrorMsg("{$value['product_name']} 产品 没有绑定产品类型:{$value['product_type_name']}");

        // 产品零件判断
        $product_parts = ModelProductParts::where('product_parts_name', $value['product_parts_name'])->find();
        if (!$product_parts) throwErrorMsg("{$value['product_parts_name']} 产品零件不存在");
        $value['product_parts_guid'] = $product_parts->product_parts_guid;
        $InProduct = ModelProductParts::where('product_guid', $value['product_guid'])->find();
        if (!$InProduct) throwErrorMsg("{$value['product_parts_name']} 产品零件 没有绑定产品:{$value['product_name']}");

        // 获取经纬度
        $longitude_latitude_arr = Map::getLongitudeAndLatitude($value['student_location']);
        $value['longitude'] = $longitude_latitude_arr['longitude'];
        $value['latitude'] = $longitude_latitude_arr['latitude'];

        // 季卡
        if ($value['student_membe_type'] == '季卡') {
            $value['student_membe_type'] = '1';
            $value['student_member_begin_time'] = date('Y-m-d H:i:s');
            $value['student_member_end_time'] = date('Y-m-d H:i:s', strtotime('+3 month'));
        }
        // 年卡
        if ($value['student_membe_type'] == '年卡') {
            $value['student_membe_type'] = '2';
            $value['student_member_begin_time'] = date('Y-m-d H:i:s');
            $value['student_member_end_time'] = date('Y-m-d H:i:s', strtotime('+1 year'));
        }

        // 已审核
        $value['student_audit_status'] = "2";
        $value['student_audit_user_guid'] = "ds4a3d2asd423s3as4d34asdd";

        // 生日日期处理
        $time = strtotime($value['student_brithday']);
        $newformat = date('Y-m-d', $time);

        return self::create([
            'student_name' => $value['student_name'],
            'user_guid' => $value['user_guid'],
            'classes_guid' => $value['classes_guid'],
            'studnet_phone' => $value['studnet_phone'],
            'student_id_card' => $value['student_id_card'],
            'student_email' => $value['student_email'],
            'student_sex' => $value['student_sex'],
            'student_price' => $value['student_price'],
            'student_brithday' => $newformat,
            'product_type' => $value['product_type_guid'],
            'product_guid' => $value['product_guid'],
            'product_parts_guid' => $value['product_parts_guid'],
            'student_img' => $value['student_img'],
            'student_banner_img' => $value['student_banner_img'],
            'student_intro' => $value['student_intro'],
            'student_location' => $value['student_location'],
            'longitude' => $value['longitude'],
            'latitude' => $value['latitude'],
            'student_membe_type' => $value['student_membe_type'],
            'student_member_begin_time' => $value['student_member_begin_time'],
            'student_member_end_time' => $value['student_member_end_time'],
            'student_audit_status' => $value['student_audit_status'],
            'student_audit_user_guid' => $value['student_audit_user_guid'],
        ]);
    }

    /**
     * 导入学生
     */
    public static function ImportStudent($file)
    {
        $error = [];

        Db::startTrans();
        try {

            $excel = new Excel($file);
            $data = $excel->parseExcel(
                [
                    [
                        'title' => '学生名称',
                        'validate' => 'require',
                        'field' => 'student_name',
                    ], [
                        'title' => '用户',
                        'validate' => 'require',
                        'field' => 'user_name',
                    ], [
                        'title' => '班级',
                        'validate' => 'require',
                        'field' => 'classes_name',
                    ], [
                        'title' => '手机号',
                        'validate' => 'require',
                        'field' => 'studnet_phone',
                    ], [
                        'title' => '身份证号',
                        'validate' => 'require',
                        'field' => 'student_id_card',
                    ], [
                        'title' => '邮箱',
                        'validate' => 'require',
                        'field' => 'student_email',
                    ], [
                        'title' => '性别',
                        'validate' => 'require',
                        'field' => 'student_sex',
                    ], [
                        'title' => '学生价格',
                        'validate' => 'require',
                        'field' => 'student_price',
                    ], [
                        'title' => '生日',
                        'validate' => 'require',
                        'field' => 'student_brithday',
                    ], [
                        'title' => '产品类型',
                        'validate' => 'require',
                        'field' => 'product_type_name',
                    ], [
                        'title' => '产品',
                        'validate' => 'require',
                        'field' => 'product_name',
                    ], [
                        'title' => '产品零件',
                        'validate' => 'require',
                        'field' => 'product_parts_name',
                    ], [
                        'title' => '头像',
                        'validate' => 'require',
                        'field' => 'student_img',
                    ], [
                        'title' => '轮播图片',
                        'validate' => 'require',
                        'field' => 'student_banner_img',
                    ], [
                        'title' => '简介',
                        'validate' => 'require',
                        'field' => 'student_intro',
                    ], [
                        'title' => '家庭住址',
                        'validate' => 'require',
                        'field' => 'student_location',
                    ], [
                        'title' => '会员类型',
                        'validate' => 'require',
                        'field' => 'student_membe_type',
                    ],
                    //  [
                    //     'title' => '会员开始时间',
                    //     'validate' => 'require',
                    //     'field' => 'student_member_begin_time',
                    // ], [
                    //     'title' => '会员结束时间',
                    //     'validate' => 'require',
                    //     'field' => 'student_member_end_time',
                    // ],
                ],
                [
                    'titleLine' => [1]
                ]
            );
            if (!$data)  throwErrorMsg('excel无数据', 1);
            $error = [];
            foreach ($data as $line => $value) {
                try {
                    $model = self::ImportStudentInit($value);
                    $error[] = "{$line}  学生:【{$value['student_name']}】<span style='color:#27af49'>新增成功!</span><br>";
                } catch (\Throwable $th) {
                    $error[] = "{$line}  学生:【{$value['student_name']}】<span style='color:red'>{$th->getMessage()}</span><br>";
                }
            }
            Db::commit();

            return implode(', ', $error);
        } catch (\Throwable $th) {
            Db::rollback();
            throw $th;
        }

        return $error;
    }

    /**
     * 导出学生
     */
    public static function exportStudent()
    {
        $select = self::alias('a')
            ->field([
                'a.student_name',
                'b.user_name',
                'f.classes_name',
                'a.studnet_phone',
                'a.student_id_card',
                'a.student_email',
                'a.student_sex',
                'a.student_price',
                'a.student_brithday',
                'c.product_type_name',
                'd.product_name',
                'e.product_parts_name',
                'a.student_img',
                'a.student_banner_img',
                'a.student_attachment',
                'a.student_location',
                'a.student_membe_type',
                'a.student_member_begin_time',
                'a.student_member_end_time',
                'a.student_audit_status',
                "(SELECT `user`.`user_name` FROM `user` WHERE `user`.user_guid = `a`.`student_audit_user_guid`) as student_audit_user_name",
            ])
            ->leftjoin('user b', 'a.user_guid = b.user_guid')
            ->leftjoin('product_type c', 'a.product_type = c.product_type_guid')
            ->leftjoin('product d', 'a.product_guid = d.product_guid')
            ->leftjoin('product_parts e', 'a.product_parts_guid = e.product_parts_guid')
            ->leftjoin('classes f', 'a.classes_guid = f.classes_guid')
            ->order('student_update_time', 'desc')->select();

        $data = [[
            '学生名称',
            '用户',
            '班级',
            '手机号',
            '身份证号',
            '邮箱',
            '性别',
            '学生价格',
            '生日',
            '产品类型',
            '产品',
            '产品零件',
            '头像',
            '轮播图片',
            '家庭住址',
            '会员类型',
            '会员开始时间',
            '会员结束时间',
            '审核状态',
            '审核人'
        ]];
        foreach ($select as $key => $val) {

            $sex_arr = [1 => "男", 2 => "女"];
            $member_arr = [1 => "季卡", 2 => "年卡"];
            $audit_arr = [1 => "未审核", 2 => "已审核", 3 => "未通过"];

            $val['student_sex'] = $sex_arr[$val['student_sex']];
            $val['student_membe_type'] = $member_arr[$val['student_membe_type']];
            $val['student_audit_status'] = $audit_arr[$val['student_audit_status']];
            $val['student_img'] = Excel::ExportImgFiled($val['student_img']);
            $val['student_banner_img'] = Excel::ExportImgFiled($val['student_banner_img']);

            $data[] = [
                $val['student_name'],
                $val['user_name'],
                $val['classes_name'],
                $val['studnet_phone'],
                $val['student_id_card'],
                $val['student_email'],
                $val['student_sex'],
                $val['student_price'],
                $val['student_brithday'],
                $val['product_type_name'],
                $val['product_name'],
                $val['product_parts_name'],
                $val['student_img'],
                $val['student_banner_img'],
                $val['student_location'],
                $val['student_membe_type'],
                $val['student_member_begin_time'],
                $val['student_member_end_time'],
                $val['student_audit_status'],
                $val['student_audit_user_name'],
            ];
        }
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('学生.xlsx');
    }

    /**
     * 新增学生服务
     */
    public static function addStudentService($student_guid, $params): void
    {
        $student_service_arr = $params['student_service'];

        foreach ($student_service_arr as $key => $item) {
            Db::startTrans();
            try {
                $add_data = [
                    'student_guid' => $student_guid,
                    'student_service_name' => $item['service_name'],
                    'student_service_price' => $item['service_price'],
                ];
                $student_service = ModelStudentService::create($add_data);

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

    /**
     * 编辑学生服务
     */
    public static function editStudentService($params): void
    {
        // 从学生服务(副表)查询出所有当前学生的服务，进行删除
        ModelStudentService::where('student_guid', $params['student_guid'])->select()->delete();

        // 再把传值的数据，写入副表
        $student_service_arr = $params['student_service'];
        foreach ($student_service_arr as $key => $item) {
            Db::startTrans();
            try {
                $add_data = [
                    'student_guid' => $params['student_guid'],
                    'student_service_name' => $item['service_name'],
                    'student_service_price' => $item['service_price'],
                ];
                ModelStudentService::create($add_data);

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

    /**
     * 会员时间获取器
     */
    public function getStudentMemberTimeAttr($value, $data)
    {
        $student_member_time = [];

        array_push($student_member_time, $data['student_member_begin_time']);
        array_push($student_member_time, $data['student_member_end_time']);

        return $student_member_time;
    }


    /**
     * 学生服务获取器
     */
    public function getStudentServiceAttr($value, $data)
    {
        $studnet_guid = $data['student_guid'];
        $studetn_service = ModelStudentService::field([
            'student_service_guid',
            'student_service_name' => 'service_name',
            'student_service_price' => 'service_price',
        ])->where('student_guid', $studnet_guid)->select();
        return $studetn_service;
    }
}
