<?php

namespace App\Http\Services;
use App\Models\Config;
use App\Models\ParentsIntention;
use App\Models\StudentPreferenceMajor;
use Exception;
use Illuminate\Support\Facades\Log;
use App\Lib\JwtService;
use Illuminate\Support\Facades\Redis;
use App\Lib\AliSmsService;
use App\Models\Student;
use App\Models\AdminUserModel;
use App\Models\StudentEval;
use App\Models\FrontUserModel;
use App\Models\LoginCacheModel;
use App\Models\StudentConsult;
use Illuminate\Support\Facades\Http;
use setasign\Fpdi\Fpdi;
use FPDF;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use App\Exceptions\Constants;

class LoginService
{
    const CAPTCHA_EXPIRE = 300;




    public function loginHandle($phone, $passwd, $platform) {

        $where = [
            'phone'=>$phone,
            'pwd'=>$passwd,
        ];
        $userfrontModel = new AdminUserModel();
        $findRetdata = $userfrontModel->findData($where);
        if (empty($findRetdata)){
            return ['code'=>10001, 'msg'=>'不存在的账号信息','data'=>[]];
        }
        if($findRetdata['status'] == 0){
            return ['code'=>10001, 'msg'=>'账号已被禁用','data'=>[]];
        }

        //生成auth
        $info = [
            'id' => $findRetdata['id'],
            'phone' => $findRetdata['phone'],
            'platform' => $platform,
        ];
        $auth  = JwtService::createToken($info, $platform);
        $insert = [
            'auth' => $auth,
            'uid' => $findRetdata['id'],
            'type' => 1,
        ];
        $LoginCacheModel = new LoginCacheModel();
        $LoginCacheModel->insertData($insert);

        return ['code'=>0, 'msg'=>'success','data'=>['Authorization'=>$auth, 'phone'=>$findRetdata['phone'] ,'is_admin'=>$findRetdata['is_admin'] ]];

    }


    public function studentInfoSubmitService($name, $phone, $baseInfo)
    {

        try {

            $uuid = Constants::getUUID();
            $student = new Student();

            $findData = $student->findData(['phone'=>$phone]);
            if(!empty($findData)){
                return ['code'=>10002, 'msg'=>'已经提交过信息，无需重复提交', 'data'=>[]];
            }

            $insertId = $student->insertData([
                'name'=>$name,
                'phone'=>$phone,
                'base_info'=>$baseInfo,
                'uuid'=>$uuid,
            ]);

            return ['code'=>0, 'msg'=>'success', 'data'=>['id'=>$uuid]];


        } catch (\Exception $e) {
            return ['code'=>20001, 'msg'=>'系统异常，请稍后重试', 'data'=>[]];
        }
    }



    public function studentIntentionInfoSubmitService($id, $intentionInfo)
    {

        try {

            $student = new Student();
            $findData = $student->findData(['uuid'=>$id]);
            if(empty($findData)){
                return ['code'=>10002, 'msg'=>'请先填写基本信息', 'data'=>[]];
            }
            $ret = $student->updateData(['uuid'=>$id], ['intention_info'=>$intentionInfo,]);

            return ['code'=>0, 'msg'=>'success', 'data'=>[]];

        } catch (\Exception $e) {
            return ['code'=>20001, 'msg'=>'系统异常，请稍后重试', 'data'=>[]];
        }
    }

    public function studentScoreInfoSubmitService($id, $scoreInfo)
    {

        try {

            $student = new Student();
            $findData = $student->findData(['uuid'=>$id]);
            if(empty($findData)){
                return ['code'=>10002, 'msg'=>'请先填写基本信息', 'data'=>[]];
            }
            $ret = $student->updateData(['uuid'=>$id], ['score_info'=>$scoreInfo,]);

            return ['code'=>0, 'msg'=>'success', 'data'=>[]];

        } catch (\Exception $e) {
            return ['code'=>20001, 'msg'=>'系统异常，请稍后重试', 'data'=>[]];
        }
    }


    public function studentEvalSubmitService($name, $phone, $weight, $evalInfo)
    {

        try {

            $studentEval = new StudentEval();

            $findData = $studentEval->findData(['phone'=>$phone]);
            if(!empty($findData)){
                return ['code'=>10002, 'msg'=>'已经提交过信息，无需重复提交', 'data'=>[]];
            }

            $insertId = $studentEval->insertData([
                'user_name'=>$name,
                'phone'=>$phone,
                'eval_info'=>$evalInfo,
                'weight_info'=>$weight,
            ]);

            return ['code'=>0, 'msg'=>'success', 'data'=>['id'=>$insertId]];


        } catch (\Exception $e) {
            return ['code'=>20001, 'msg'=>'系统异常，请稍后重试', 'data'=>[]];
        }
    }

    public function studentConsultSubmitService($name, $phone, $info, $from)
    {

        try {

            $studentConsult = new StudentConsult();

            $findData = $studentConsult->findData(['phone'=>$phone]);
            if(!empty($findData)){
                return ['code'=>10002, 'msg'=>'已经提交过信息，无需重复提交', 'data'=>[]];
            }

            $insertId = $studentConsult->insertData([
                'user_name'=>$name,
                'phone'=>$phone,
                'info'=>$info,
                'from'=>$from,
            ]);

            return ['code'=>0, 'msg'=>'success', 'data'=>['id'=>$insertId]];


        } catch (\Exception $e) {
            return ['code'=>20001, 'msg'=>'系统异常，请稍后重试', 'data'=>[]];
        }
    }

    public function checkCommonPreferenceMajorHandle($studentInfo) {
        $result = [
            'res' => false,
            'msg' => '校验成功',
            'data' => [],
        ];

        if (!isset($studentInfo['user_name']) || mb_strlen($studentInfo['user_name']) == 0 || mb_strlen($studentInfo['user_name']) > 32) {
            $result['msg'] = '姓名异常';
            return $result;
        }
        $result['data']['user_name'] = $studentInfo['user_name'];

        if (!isset($studentInfo['phone']) || !checkPhone($studentInfo['phone'])) {
            $result['msg'] = '手机号异常';
            return $result;
        }
        $result['data']['phone'] = $studentInfo['phone'];

        if (!isset($studentInfo['province']) || mb_strlen($studentInfo['province']) == 0 || mb_strlen($studentInfo['province']) > 32) {
            $result['msg'] = '省份异常';
            return $result;
        }
        $result['data']['province'] = $studentInfo['province'];

        if (!isset($studentInfo['subject']) || mb_strlen($studentInfo['subject']) == 0 || mb_strlen($studentInfo['subject']) > 32) {
            $result['msg'] = '选科异常';
            return $result;
        }
        $result['data']['subject'] = $studentInfo['subject'];

        if (!isset($studentInfo['score']) || !is_numeric($studentInfo['score']) || $studentInfo['score'] < 0 || $studentInfo['score'] > 99999.9) {
            $result['msg'] = '分数异常';
            return $result;
        }
        $result['data']['score'] = round($studentInfo['score'], 1);

        if (!isset($studentInfo['rank']) || !is_numeric($studentInfo['rank']) || $studentInfo['rank'] <= 0 || $studentInfo['rank'] > 99999999) {
            $result['msg'] = '分数异常';
            return $result;
        }
        $result['data']['rank'] = intval($studentInfo['rank']);

        if (!isset($studentInfo['type']) || !is_numeric($studentInfo['type']) || ($studentInfo['type'] != 1 && $studentInfo['type'] != 2)) {
            $result['msg'] = '类型异常';
            return $result;
        }
        $result['data']['type'] = intval($studentInfo['type']);

        if (!isset($studentInfo['plan']) || !is_array($studentInfo['plan']) || empty($studentInfo['plan']) || count($studentInfo['plan']) > 120) {
            $result['msg'] = '志愿异常';
            return $result;
        }

        $result['data']['plan'] = [];
        if ($studentInfo['type'] == 1) {
            foreach ($studentInfo['plan'] as $index => $plan) {
                if (!isset($plan['school_code']) || mb_strlen($plan['school_code']) == 0 || mb_strlen($plan['school_code']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个院校代码异常';
                    return $result;
                }
                if (!isset($plan['school_name']) || mb_strlen($plan['school_name']) == 0 || mb_strlen($plan['school_name']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个院校名称异常';
                    return $result;
                }
                if (!isset($plan['major_code']) || mb_strlen($plan['major_code']) == 0 || mb_strlen($plan['major_code']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业代码异常';
                    return $result;
                }
                if (!isset($plan['major_name']) || mb_strlen($plan['major_name']) == 0 || mb_strlen($plan['major_name']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业名称异常';
                    return $result;
                }

                $result['data']['plan'][] = [
                    'school_code' => $plan['school_code'],
                    'school_name' => $plan['school_name'],
                    'major_code' => $plan['major_code'],
                    'major_name' => $plan['major_name'],
                ];
            }
        } else if ($studentInfo['type'] == 2) {
            foreach ($studentInfo['plan'] as $index => $plan) {
                if (!isset($plan['school_code']) || mb_strlen($plan['school_code']) == 0 || mb_strlen($plan['school_code']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个院校代码异常';
                    return $result;
                }
                if (!isset($plan['major_name_1']) || mb_strlen($plan['major_name_1']) == 0 || mb_strlen($plan['major_name_1']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业1异常';
                    return $result;
                }
                if (!isset($plan['major_code_1']) || mb_strlen($plan['major_code_1']) == 0 || mb_strlen($plan['major_code_1']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业1代码异常';
                    return $result;
                }
                if (!isset($plan['major_name_2']) || mb_strlen($plan['major_name_2']) == 0 || mb_strlen($plan['major_name_2']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业2异常';
                    return $result;
                }
                if (!isset($plan['major_code_2']) || mb_strlen($plan['major_code_2']) == 0 || mb_strlen($plan['major_code_2']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业2代码异常';
                    return $result;
                }
                if (!isset($plan['major_name_3']) || mb_strlen($plan['major_name_3']) == 0 || mb_strlen($plan['major_name_3']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业3异常';
                    return $result;
                }
                if (!isset($plan['major_code_3']) || mb_strlen($plan['major_code_3']) == 0 || mb_strlen($plan['major_code_3']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业3代码异常';
                    return $result;
                }
                if (!isset($plan['major_name_4']) || mb_strlen($plan['major_name_4']) == 0 || mb_strlen($plan['major_name_4']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业4异常';
                    return $result;
                }
                if (!isset($plan['major_code_4']) || mb_strlen($plan['major_code_4']) == 0 || mb_strlen($plan['major_code_4']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业4代码异常';
                    return $result;
                }
                if (!isset($plan['major_name_5']) || mb_strlen($plan['major_name_5']) == 0 || mb_strlen($plan['major_name_5']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业5异常';
                    return $result;
                }
                if (!isset($plan['major_code_5']) || mb_strlen($plan['major_code_5']) == 0 || mb_strlen($plan['major_code_5']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业5代码异常';
                    return $result;
                }
                if (!isset($plan['major_name_6']) || mb_strlen($plan['major_name_6']) == 0 || mb_strlen($plan['major_name_6']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业6异常';
                    return $result;
                }
                if (!isset($plan['major_code_6']) || mb_strlen($plan['major_code_6']) == 0 || mb_strlen($plan['major_code_6']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个专业6代码异常';
                    return $result;
                }
                if (!isset($plan['is_obey_adjust']) || mb_strlen($plan['is_obey_adjust']) == 0 || mb_strlen($plan['is_obey_adjust']) > 64) {
                    $result['msg'] = '第' . ($index + 1) . '个是否服从调剂异常';
                    return $result;
                }

                $result['data']['plan'][] = [
                    'school_code' => $plan['school_code'],
                    'major_code' => $plan['major_code'],
                    'major_name_1' => $plan['major_name_1'],
                    'major_code_1' => $plan['major_code_1'],
                    'major_name_2' => $plan['major_name_2'],
                    'major_code_2' => $plan['major_code_2'],
                    'major_name_3' => $plan['major_name_3'],
                    'major_code_3' => $plan['major_code_3'],
                    'major_name_4' => $plan['major_name_4'],
                    'major_code_4' => $plan['major_code_4'],
                    'major_name_5' => $plan['major_name_5'],
                    'major_code_5' => $plan['major_code_5'],
                    'major_name_6' => $plan['major_name_6'],
                    'major_code_6' => $plan['major_code_6'],
                    'is_obey_adjust' => $plan['is_obey_adjust'],
                ];
            }
        }

        $result['res'] = true;
        return $result;
    }

    public function commonPreferenceMajorHandle($studentInfo) {
        $result = [
            'res' => false,
            'msg' => '提交成功',
            'data' => [],
        ];

        $studentPreferenceMajorModel = new StudentPreferenceMajor();
        $info = $studentPreferenceMajorModel->findDataWithField(['phone' => $studentInfo['phone'], 'type' => $studentInfo['type']], ['id']);
        if (!empty($info)) {
            $result['msg'] = '您已提交过信息,无需重复提交';
            return $result;
        }

        $insertData = [
            'user_name' => $studentInfo['user_name'],
            'phone' => $studentInfo['phone'],
            'province' => $studentInfo['province'],
            'subject' => $studentInfo['subject'],
            'score' => $studentInfo['score'],
            'rank' => $studentInfo['rank'],
            'type' => $studentInfo['type'],
            'plan' => json_encode($studentInfo['plan'], JSON_UNESCAPED_UNICODE),
        ];
        $insertRes = $studentPreferenceMajorModel->insertData($insertData);
        if (false === $insertRes) {
            $result['msg'] = '提交失败';
            return $result;
        }

        $result['res'] = true;
        return $result;
    }

    public function parentsIntentionPeriodsHandle() {
        $result = [
            'res' => false,
            'msg' => '获取成功',
            'data' => [],
        ];

        $configModel = new Config();
        $periods = $configModel->findDataWithField(['type' => 1, 'config_key' => 'intention_' . date('Y')]);
        if (empty($periods)) {
            $result['msg'] = '报名期数配置异常';
            return $result;
        }

        $result['res'] = true;
        $result['data']['periods'] = json_decode($periods['config_value'], true);
        return $result;
    }

    public function checkParentsIntentionHandle($studentInfo) {
        $result = [
            'res' => false,
            'msg' => '校验成功',
            'data' => [],
        ];

        if (!isset($studentInfo['user_name']) || mb_strlen($studentInfo['user_name']) == 0 || mb_strlen($studentInfo['user_name']) > 32) {
            $result['msg'] = '姓名异常';
            return $result;
        }
        $result['data']['user_name'] = $studentInfo['user_name'];

        if (!isset($studentInfo['phone']) || !checkPhone($studentInfo['phone'])) {
            $result['msg'] = '手机号异常';
            return $result;
        }
        $result['data']['phone'] = $studentInfo['phone'];

        if (!isset($studentInfo['province']) || mb_strlen($studentInfo['province']) == 0 || mb_strlen($studentInfo['province']) > 32) {
            $result['msg'] = '省份异常';
            return $result;
        }
        $result['data']['province'] = $studentInfo['province'];

        if (!isset($studentInfo['periods']) || !is_numeric($studentInfo['periods']) || $studentInfo['periods'] < 1 || $studentInfo['periods'] > 4) {
            $result['msg'] = '期数异常';
            return $result;
        }
        $result['data']['periods'] = intval($studentInfo['periods']);

        $result['res'] = true;
        return $result;
    }

    public function parentsIntentionHandle($studentInfo) {
        $result = [
            'res' => false,
            'msg' => '提交成功',
            'data' => [],
        ];

        $year = date('Y');

        $parentsIntention = new ParentsIntention();
        $info = $parentsIntention->findDataWithField(['phone' => $studentInfo['phone'], 'year' => $year], ['id']);
        if (!empty($info)) {
            $result['msg'] = '您已提交过信息,无需重复提交';
            return $result;
        }

        $insertData = [
            'user_name' => $studentInfo['user_name'],
            'phone' => $studentInfo['phone'],
            'province' => $studentInfo['province'],
            'year' => $year,
            'periods' => $studentInfo['periods'],
        ];
        $insertRes = $parentsIntention->insertData($insertData);
        if (false === $insertRes) {
            $result['msg'] = '提交失败';
            return $result;
        }

        $result['res'] = true;
        return $result;
    }


}





