<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\IntroductionInfoModel;
use App\Models\MajorInfoModel;
use App\Models\PaidSettingModel;
use App\Models\QueryInfoModel;
use App\Models\StudentCountModel;
use App\Models\UserInfoModel;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Services\Base\ErrorCode;
use Validator, Response;
use EasyWeChat\Factory;


class HomeController extends Controller
{

    protected $app;

    public function __construct()
    {
        $config = [
            'app_id' => 'wx68ef25b3ba5545c4',
            'secret' => 'b549f48de10c7157aaaa18c6c0e62e30',

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];

        $this->app = Factory::miniProgram($config);
    }


    /**
     * @api {post} /api/home/login 登陆(login)
     * @apiDescription 登陆(login)
     * @apiGroup 高考助手
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [code](必填)
     * @apiParam {int}    [nickName]
     * @apiParam {int}    [avatar]
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "userinfo": {
     *              "id": "",
     *              "nickname": "",
     *              "openid": "",
     *              "has_agreed": ""           //1:已同意说明，进入主页面；0:为同意协议，进入协议说明页面
     *          }
     *
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function login(Request $request)
    {
        $code = $request->get('code');
        $session = $this->app->auth->session($code);

        $openid = $session['openid'];

        $userinfo = UserInfoModel::where('openid', $openid)->first(['id', 'nickname', 'openid', 'has_agreed']);

        if ($userinfo) {
            return $this->api(compact('userinfo'));
        } else {
            $data['openid'] = $openid;
            $data['nickname'] = $request->get('nickName');
            $data['avatar'] = $request->get('avatar');
            $data['has_agreed'] = 0;

            $userinfo = UserInfoModel::create($data);

            return $this->api(compact('userinfo'));
        }

    }

    /**
     * @api {get} /api/home/getintroduction  获取使用说用及协议
     * @apiDescription 获取使用说用及协议
     * @apiGroup 高考助手
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "list": [
     *
     *          ]
     *
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function getIntroduction()
    {
        $list = IntroductionInfoModel::get(['title', 'content', 'type']);

        return $this->api(compact('list'));
    }


    /**
     * @api {post} /api/home/agreeintroduction   同意使用说用及协议
     * @apiDescription 同意使用说用及协议
     * @apiGroup 高考助手
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [userid]   用户ID(必填)
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "userinfo": [
     *
     *          ]
     *
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function agreeIntroduction(Request $request)
    {
        $userid = $request->get('userid');
        $data['has_agreed'] = 1;
        $res = UserInfoModel::where('id', $userid)->update($data);
        if ($res) {
            $userinfo = UserInfoModel::where('id', $userid)->first(['id', 'nickname', 'openid', 'has_agreed']);
        }

        return $this->api(compact('userinfo'));

    }


    /**
     * @api {get} /api/home/getbasedata   获取可选批次及省份
     * @apiDescription 获取可选批次及省份
     * @apiGroup 高考助手
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "batchs": [
     *
     *          ],
     *          "provinces":[
     *
     *          ]
     *
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function getBaseData()
    {
        $batchs = MajorInfoModel::groupBy('batch')->pluck('batch');

        $provinces = [
            "全部省份", "安徽", "澳门", "北京", "重庆", "福建", "甘肃", "广东", "广西", "贵州", "海南", "河北", "河南", "黑龙江", "湖北", "湖南", "吉林", "江苏", "江西", "辽宁", "内蒙古", "宁夏", "青海", "山东", "山西", "陕西", "上海", "四川", "台湾", "天津", "西藏", "香港", "新疆", "云南", "浙江"
        ];

        return $this->api(compact('batchs', 'provinces'));
    }


    /**
     * @api {post} /api/home/getqueried   查询免费信息
     * @apiDescription 查询免费信息
     * @apiGroup 高考助手
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [userid]   用户ID(必填)
     * @apiParam {string}    [username]   考生姓名(必填)
     * @apiParam {string}    [cnumber]   考号(必填)
     * @apiParam {string}    [class]   科类(必填)
     * @apiParam {int}    [grade]   高考成绩(必填)
     * @apiParam {int}    [batch]   批次(必填)
     * @apiParam {int}    [province]   省份(必填)
     * @apiParam {int}    [code]   推荐码(选填)
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "rank": ""
     *         "grade": ""
     *         "college_count": ""
     *
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function getQueried(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'cnumber' => 'required',
                'username' => 'required',
                'grade' => 'required|integer',
            ],
            [
                'cnumber.required' => '考号不能为空!',
                'username.required' => '姓名不能为空!',
                'username.required' => '姓名不能为空!',
                'grade.required' => '成绩不能为空!',
                'grade.integer' => '请输入正确格式的成绩!',
            ]
        );


        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }

        /*更新用户的信息*/
        $this->updateUserinfo();

        $year = date('Y');
        $grade = $request->get('grade');
        $batch = $request->get('batch');
        $class = $request->get('class');
        $province = $request->get('province');

        $maxgrade = StudentCountModel::where('year', $year)->orderBy('grade', 'desc')->first()->grade;
        if ($grade > $maxgrade) {
            $rank = "前10";
        } else {
            $rank = StudentCountModel::where('year', $year)->where('grade', $grade)->first(['total'])->total;
        }

        if ($province == "全部省份") {
            $college = MajorInfoModel::where('year', $year)->where('batch', $batch)->where('class', $class)->where('min_grade', "<=", $grade)->groupBy('college')->get();
        } else {
            $college = MajorInfoModel::where('year', $year)->where('batch', $batch)->where('class', $class)->where('province', 'like', '%' . $province . '%')->where('min_grade', "<=", $grade)->groupBy('college')->get();
        }

        $college_count = count($college);

        /*创建查询记录*/
        $user = UserInfoModel::find(request('userid'));
        $this - $this->createQueryInfo($user);

        return $this->api(compact('rank', 'grade', 'province', 'college_count', 'batch'));
    }


    /**
     * @api {post} /api/home/getpaidmajors   查询付费信息
     * @apiDescription 查询付费信息
     * @apiGroup 高考助手
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [userid]   用户ID(必填)
     * @apiParam {string}    [username]   考生姓名(必填)
     * @apiParam {string}    [batch]   批次(必填)
     * @apiParam {string}    [province]   省份(必填)
     * @apiParam {string}    [class]   科类(必填)
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK 已付费查看过,显示匹配信息
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "count": ""
     *         "major":[
     *      ]
     *
     *     }
     * }
     *
     *HTTP/1.1 200 OK 未曾付费，跳转到支付页面
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *              "msg": "need to pay",
     *              "price": ""
     *      }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function getPaidMajors(Request $request)
    {

        $validator = Validator::make($request->all(),
            [
                'userid' => 'required',
                'batch' => 'required',
                'province' => 'required',
                'class' => 'required'
            ],
            [
                'userid.required' => 'userid不能为空!',
                'batch.required' => 'batch不能为空!',
                'province.required' => 'province不能为空!',
                'class.required' => 'class不能为空!',

            ]
        );


        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }

        if ($this->checkPaid()) {
            $year = date('Y');
            $batch = $request->get('batch');
            $province = $request->get('province');

            $userid = request('userid');
            $_user = UserInfoModel::find($userid);
            $grade = $_user->grade;
            $class = $_user->class;


            if ($province == "全部省份") {
                $major = MajorInfoModel::where('year', $year)->where('batch', $batch)->where('class', $class)->where('min_grade', "<=", $grade)->get();
            } else {
                $major = MajorInfoModel::where('year', $year)->where('batch', $batch)->where('class', $class)->where('province', 'like', '%' . $province . '%')->where('min_grade', "<=", $grade)->get();
            }

            $count = count($major);

            return $this->api(compact('count', 'major'));
        } else {
            $price = PaidSettingModel::first();

            $msg = 'need to pay';
            $price = $price->price;

            return $this->api(compact('msg', 'price'));
        }
    }

    public function checkPaid()
    {
        $userid = request('userid');
        $_user = UserInfoModel::find($userid);

        $hasPaid = QueryInfoModel::where('user_id', $_user->id)->where('grade', $_user->grade)->where('is_paid', 1)->count();

        return $hasPaid;
    }

    public function updateUserinfo()
    {
        $userid = request('userid');

        $data['username'] = request('username');
        $data['mobile'] = request('mobile');
        $data['grade'] = request('grade');
        $data['code'] = request('code');

        $res = UserInfoModel::where('id', $userid)->update($data);

    }

    public function createQueryInfo($userinfo)
    {
        $data['is_paid'] = 0;
        $data['cnumber'] = $userinfo->cnumber;
        $data['grade'] = $userinfo->grade;
        $data['code'] = $userinfo->code;
        $data['mobile'] = $userinfo->mobile;
    }


}