<?php

namespace app\controller;


use app\business\LoginBusiness;
use app\business\SmsBusiness;
use app\business\StreamBusiness;
use Illuminate\Support\Arr;
use Respect\Validation\Validator;
use support\Db;
use support\Redis;
use support\Request;
use hg\apidoc\annotation as Apidoc;
use Webman\Captcha\CaptchaBuilder;
use Webman\Captcha\PhraseBuilder;

#[Apidoc\Title("登陆注册")]
#[Apidoc\Group("Login")]
#[Apidoc\Sort(1)]
class LoginController
{
    #[Apidoc\Title("登录")]
    #[Apidoc\Url("api/login/login.html")]
    #[Apidoc\Method("POST")]
    #[Apidoc\Param("mobile", type: "int", require: true, desc: "账号/手机号", mock: 16500000000)]
    #[Apidoc\Param("app", type: "int", require: true, desc: "是否为APP", mock: '')]
    #[Apidoc\Param("password", type: "string", require: true, desc: "密码（6-16字母加数字）位密码", mock: 123456)]
    #[Apidoc\Param("code", type: "int", require: true, desc: "验证码")]
    #[Apidoc\Param("key", type: "string", require: true, desc: "验证码的key")]
    public function login(Request $request)
    {
        $param = $request->param_data;
        Db::beginTransaction();
        try {
            $param = Arr::only($param, ['mobile', 'password', 'app', 'code', 'key']);
            Validator::input($param, [
                'mobile'   => Validator::notEmpty()->intType()->setName('手机号'),
                'password' => Validator::notEmpty()->stringType()->Length(6, 15)->alnum()->setName('密码'),
                'code'     => Validator::notEmpty()->intType()->setName('验证码'),
                'key'      => Validator::notEmpty()->stringType()->setName('验证码标识'),
            ]);
            /* if(empty(preg_match('/^1[3-9]\d{9}$/', $param['mobile']))){
                 throw new \Exception('请输入正确的手机号');
             }*/
            if (strtolower($param['code']) != Redis::get($param['key'])) {
                throw new \Exception('验证码错误!');
            }
            $param['last_ip'] = $request->getRealIp($safe_mode = true);
            $token            = LoginBusiness::login($param);
            Redis::del($param['key']);
        } catch (\Throwable $exception) {
            Db::rollBack();
            return error($exception->getMessage());
        }
        Db::commit();
        return success([
            'token' => $token
        ]);

    }

    #[Apidoc\Title("注册")]
    #[Apidoc\Url("api/login/register.html")]
    #[Apidoc\Method("POST")]
    // #[Apidoc\Header("token",type: "string",require: true,desc: "身份令牌Token",mock: "@token")]
    #[Apidoc\Param("mobile", type: "int", require: true, desc: "账号/手机号", mock: 15800000000)]
    #[Apidoc\Param("password", type: "string", require: true, desc: "密码（6-16字母加数字）位密码", mock: 123456)]
    #[Apidoc\Param("confirm_password", type: "string", require: true, desc: "确认密码（6-16字母加数字）位密码", mock: 123456)]
    #[Apidoc\Param("invitation_code", type: "int", require: true, desc: "邀请码", mock: 100001)]
    #[Apidoc\Param("code", type: "int", require: true, desc: "验证码")]
    #[Apidoc\Param("key", type: "string", require: true, desc: "验证码的key")]
    public function register(Request $request)
    {
        $param = $request->param_data;
        Db::beginTransaction();
        try {
            $param = Arr::only($param, ['mobile', 'password', 'confirm_password', 'invitation_code', 'code', 'key']);
            Validator::input($param, [
                'mobile'           => Validator::notEmpty()->intType()->setName('手机号'),
                'password'         => Validator::notEmpty()->stringType()->Length(6, 15)->alnum()->setName('密码'),
                'confirm_password' => Validator::notEmpty()->stringType()->Length(6, 15)->alnum()->setName('确认密码'),
                'invitation_code'  => Validator::notEmpty()->intType()->setName('邀请码'),
                'code'             => Validator::notEmpty()->intType()->setName('验证码'),
                'key'              => Validator::notEmpty()->stringType()->setName('验证码标识'),
            ]);
            /*  if(empty(preg_match('/^1[3-9]\d{9}$/', $param['mobile']))){
                  throw new \Exception('请输入正确的手机号');
              }
            */
            if (strtolower($param['code']) != Redis::get($param['key'])) {
                throw new \Exception('验证码错误!');
            }
            Redis::del($param['key']);
            if ($param['password'] != $param['confirm_password']) {
                throw new \Exception('两次密码不一致!');
            }
            $param['last_ip'] = $request->getRealIp($safe_mode = true);
            $param['join_ip'] = $param['last_ip'];
            $token            = LoginBusiness::register($param);
        } catch (\Throwable $exception) {
            Db::rollBack();
            return error($exception->getMessage());
        }
        Db::commit();
        return success([
            'token' => $token
        ]);
    }

//        #[Apidoc\Title("注册领取")]
//        #[Apidoc\Url("api/login/register_receive.html")]
//        #[Apidoc\Method("POST")]
//        #[Apidoc\Header("token", type: "string", require: true, desc: "身份令牌Token", mock: "@token")]
//        public function register_receive(Request $request)
//        {
//            $param = $request->all();
//            Db::beginTransaction();
//            try {
//                $user   = Db::table('wa_users')->where('id', $request->user_data['id'])->first();
//                $system = Db::table('wa_system')->first();
//                /** @var  $has 查是否已经领取 */
//                $has = Db::table('wa_stream')
//                    ->where('user_id', $request->user_data['id'])
//                    ->where('type', streamType1)
//                    ->where('mold', moldType5)
//                    ->exists();
//                if (!empty($has)) {
//                    throw new \Exception('已经领取该奖励了，不能重复领取!');
//                }
//
//                /** 注册赠送 */
//                if (!empty($system) && !empty($user) && !empty($system->register_award)) {//注册赠送
//                    StreamBusiness::addStream($request->user_data['id'], $system->register_award, streamType1, moldType5, moldTypefild5);
//                }
//            } catch (\Throwable $exception) {
//                Db::rollBack();
//                return error($exception->getMessage());
//            }
//            Db::commit();
//            return success([], '领取成功');
//        }


    #[Apidoc\Title("验证码")]
    #[Apidoc\Url("api/login/authccode.html")]
    #[Apidoc\Method("POST")]
    // #[Apidoc\Header("token",type: "string",require: true,desc: "身份令牌Token",mock: "@token")]
    #[Apidoc\Returned(name: "img", type: "blob", require: true, desc: '图形验证码', default: 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD//gA7')]
    #[Apidoc\Returned(name: "key", type: "string", require: true, desc: '验证码KEY', default: 'authccode172036979253337')]
    public function authccode()
    {
        $phraseBuilder = new PhraseBuilder(4, '123456789');
        $builder       = new CaptchaBuilder(null, $phraseBuilder);
        // 生成验证码
        $builder->build(100, 29);
        $key = 'authccode' . time() . mt_rand(10000, 99999);
        Redis::setEx($key, 600, strtolower($builder->getPhrase()));
        $img_content = $builder->inline();
        return success(['img' => $img_content, 'key' => $key]);
    }

    #[Apidoc\Title("邀请规则")]
    #[Apidoc\Url("api/login/invite.html")]
    #[Apidoc\Method("POST")]
    #[Apidoc\Header("token", type: "string", require: true, desc: "身份令牌Token", mock: "@token")]
//        #[Apidoc\Returned(name: "invite", type: "array", desc: '活动规则', default: '', children: [
//            ['name' => "id", 'type' => 'int', 'require' => true, 'default' => 1, 'desc' => '规则ID'],
//            ['name' => "num", 'type' => 'int', 'require' => true, 'default' => 1, 'desc' => '邀请人'],
//            ['name' => "money", 'type' => 'int', 'require' => true, 'default' => 38, 'desc' => '农业补贴金'],
//            ['name' => "money_one", 'type' => 'int', 'require' => true, 'default' => 38, 'desc' => '中国粮仓支票'],
//            ['name' => "complete", 'type' => 'int', 'require' => true, 'default' => 0, 'desc' => '完成人数'],
//            ['name' => "has", 'type' => 'int', 'require' => true, 'default' => false, 'desc' => '是否领奖 true  已领奖  false 未领奖'],
//        ])]
    #[Apidoc\Returned(name: "uuid", type: "string", require: true, desc: '邀请码', default: '10001')]
    #[Apidoc\Returned(name: "is_num", type: "string", require: true, desc: '累计邀请人数', default: '10001')]
    #[Apidoc\Returned(name: "rebate_money", type: "int", require: true, desc: '一级奖励', default: '1000')]
    #[Apidoc\Returned(name: "rebate_one_money", type: "int", require: true, desc: '二级奖励', default: '1')]
    #[Apidoc\Returned(name: "rebate_two_money", type: "int", require: true, desc: '三级奖励', default: '1')]
    public function invite(Request $request)
    {
//        $invite = Db::table('wa_invite')->where('status', 1)
//            ->select(['id', 'num', 'money', 'money_two', 'money_one'])
//            ->orderBy('sort')->get()->toArray();
//        foreach ($invite as $k => $v) {
//            $invite[$k]->complete = $request->user_data['is_num'];
//            $invite[$k]->has      = Db::table('wa_stream')
//                ->where('user_id', $request->user_data['id'])
//                ->where('type', streamType3)
//                ->where('source_id', $v->id)->exists();
//        }

        $system = Db::table('wa_system')->first();
        return success([
            'invite'           => [],
            'uuid'             => $request->user_data['uuid'],
            'is_num'           => $request->user_data['is_num'],
            'rebate_money'     => 90000,
            'rebate_one_money' => 40000,
            'rebate_two_money' => 20000,

        ]);
    }

//    #[Apidoc\Title("邀请领奖")]
//    #[Apidoc\Url("api/login/invite_receive.html")]
//    #[Apidoc\Method("POST")]
//    #[Apidoc\Header("token", type: "string", require: true, desc: "身份令牌Token", mock: "@token")]
//    #[Apidoc\Param("id", type: "int", require: true, desc: '邀请规则ID', mock: 1)]
//    public function invite_receive(Request $request)
//    {
//        $param = $request->param_data;
//        Db::beginTransaction();
//        try {
//            $param = Arr::only($param, ['id']);
//            Validator::input($param, [
//                'id' => Validator::notEmpty()->intType()->setName('标识'),
//            ]);
//            if (!empty(Redis::get($param['id'] . $request->user_data['id']))) {
//                throw new \Exception('请不要连续操作');
//            }
//            Redis::setEx($param['id'] . $request->user_data['id'], 5, $request->user_data['id']);
//
//            $inviteData = Db::table('wa_invite')->where('id', $param['id'])->first();
//            if (empty($inviteData)) {
//                throw new \Exception('非法操作');
//            }
//            if ($request->user_data['is_num'] < $inviteData->num) {
//                throw new \Exception('未达到,邀请规则!');
//            }
//            $has = Db::table('wa_stream')
//                ->where('user_id', $request->user_data['id'])
//                ->where('type', streamType3)
//                ->where('source_id', $param['id'])
//                ->exists();
//            if (!empty($has)) {
//                throw new \Exception('已领取过奖励!');
//            }
//            if (!empty($inviteData->money)) {
//                //农业补贴金
//                StreamBusiness::addStream($request->user_data['id'], $inviteData->money, streamType3, moldType3, moldTypefild3, $inviteData->id);
//            }
//            if (!empty($inviteData->money_one)) {
//                //中国粮仓支票
//                StreamBusiness::addStream($request->user_data['id'], $inviteData->money_one, streamType3, moldType2, moldTypefild2, $inviteData->id);
//            }
//
//
//        } catch (\Throwable $exception) {
//            Db::rollBack();
//            return error($exception->getMessage());
//        }
//        Db::commit();
//        return success([], '领取成功');
//    }

    #[Apidoc\Title("判断当前用户是否存在是否实名")]
    #[Apidoc\Url("api/login/sign_in.html")]
    #[Apidoc\Method("POST")]
    #[Apidoc\Param("mobile", type: "int", require: true, desc: "账号/手机号", mock: 15800000000)]
    #[Apidoc\Returned(name: "is_sign_in", type: "int", require: true, desc: '是否实名 1=未实名，2=实名', default: '1')]
    public function signIn(Request $request)
    {
        $param = $request->param_data;
        Db::beginTransaction();
        try {
            $param = Arr::only($param, ['mobile']);
            Validator::input($param, [
                'mobile' => Validator::notEmpty()->intType()->setName('手机号'),
            ]);
            $userlist = Db::table('wa_users')->where('mobile', $param['mobile'])->first();
            if (!$userlist) {
                throw new \Exception('请输入正确手机号!');
            }
            $is_sign_in = 1;
            if ($userlist->is_autonym == 1) {
                $is_sign_in = 2;
            }
            $data = ['is_sign_in' => $is_sign_in];

        } catch (\Throwable $exception) {
            Db::rollBack();
            return error($exception->getMessage());
        }
        Db::commit();
        return success($data, '请求成功');
    }

    #[Apidoc\Title("未登陆修改密码")]
    #[Apidoc\Url("api/login/passsave.html")]
    #[Apidoc\Method("POST")]
    #[Apidoc\Param("mobile", type: "int", require: true, desc: "手机号", mock: 15800000000)]
    #[Apidoc\Param("number", type: "string", require: true, desc: "身份证", mock: 1123)]
    #[Apidoc\Param("password", type: "int", require: true, desc: "密码", mock: 123456)]
    public function passsave(Request $request)
    {
        $param = $request->param_data;
        Db::beginTransaction();
        try {
            Validator::input($param, [
                'mobile'   => Validator::notEmpty()->intType()->setName('手机号'),
                'password' => Validator::notEmpty()->setName('密码'),
            ]);
            $userlist = Db::table('wa_users')->where('mobile', $param['mobile'])->first();
            if (!$userlist) {
                throw new \Exception('请输入正确手机号!');
            }
            if ($userlist->is_autonym == 1) {
                if (empty($param['number'])) {
                    throw new \Exception('请输入身份证号码!');
                }
                $identity = Db::table('wa_user_identity')->where('uid', $userlist->id)->where('number', $param['number'])->first();
                if (!$identity) {
                    throw new \Exception('输入的身份证号码和实名信息不一致!');
                }
            }
            Db::table('wa_users')->where('id', $userlist->id)->update(['password' => md5($param['password'])]);

        } catch (\Throwable $exception) {
            Db::rollBack();
            return error($exception->getMessage());
        }
        Db::commit();
        return success([], '修改成功');
    }

}
