<?php

namespace app\mobile\controller;

use app\mobile\MobileBaseController;
use app\common\model\UserAuths as UserAuthsModel;
use app\common\model\Broker as BrokerModel;
use app\common\model\User as UserModel;
use app\common\model\Agent as AgentModel;
use app\common\model\BrokerForm as BrokerFormModel;
use chuanglan\Chuanglan;

class Login extends MobileBaseController
{
    public function login()
    {
        return redirect('https://www.jucai.gov.cn/api/auth/wechat_auth?url=' . urlencode(url('/mobile/login/wechatBack')));
    }

    /**
     * 微信回调
     */
    public function wechatBack()
    {
        $param     = input('param.');
        $unionid   = $param['unionid'];
        $userauths = UserAuthsModel::where(['identifier' => $unionid, 'identitytype' => "weixin"])->find();

        //登录成功
        if (!empty($userauths)) {
            $user = UserModel::where(['id' => $userauths->userid])->find();
            session('mobile.user.id', $user['id']);

            //非经济人
            $broker = BrokerModel::where('userid', $user['id'])->find();
            if (empty($broker)) {
                return redirect('/mobile/login/broker');
            }
            session('mobile.broker.id', $broker['id']);

            return redirect('/mobile/my/index');
        }

        session('mobile.user.unionid', $param['unionid']);
        if (!empty($param['nickname'])) {
            session('mobile.user.nickname', $param['nickname']);
        }
        if (!empty($param['avatar'])) {
            session('mobile.user.avatar', $param['avatar']);
        }

        return redirect('/mobile/login/mobile');
    }

    /**
     * 手机号注册
     */
    public function mobile()
    {
        $unionid = session('mobile.user.unionid');
        if (empty($unionid)) {
            return redirect('/mobile/login/login');
        }

        return view('login/mobile');
    }

    public function mobilePost()
    {
        $param = input('post.');
        empty($param['mobile']) && page_result(1, '请输入手机号');
        empty($param['verify']) && page_result(1, '请输入验证码');

        //验证码校验
        $verify_expire = session('mobile.login.verify_expire');
        if ($verify_expire < time()) {
            session('mobile.login.verify', null);
            session('mobile.login.verify_expire', null);
            page_result(1, '验证码已过期');
        }
        $verify = session('mobile.login.verify');
        if ($verify != $param['verify']) {
            page_result(1, '验证码不正确');
        }

        //手机号
        $unionid   = session('mobile.user.unionid');
        $userauths = UserAuthsModel::where(['identifier' => $param['mobile'], 'identitytype' => "mobile"])->find();
        if (!empty($userauths)) {
            $password = md5(time() . mt_rand(100000, 999999));
            $this->authsRegister($userauths->userid, "weixin", $unionid, $password);
            $this->authsRegister($userauths->userid, "mobile", $param['mobile'], $password);
            session('mobile.user.id', $userauths->userid);

            //非经济人
            $broker = BrokerModel::where('userid', $userauths->userid)->find();
            if (empty($broker)) {
                return page_result(0, '', ['url' => '/mobile/login/broker']);
            }
            session('mobile.broker.id', $broker['id']);

            page_result(0, '', ['url' => '/mobile/my/index']);
        }

        //登录注册
        $nickname = session('mobile.user.nickname') ?? '';
        $avatar   = session('mobile.user.avatar') ?? '';
        $data     = [
            'groupsid'       => 7,
            'nickname'       => $nickname,
            'avatar'         => $avatar,
            'realname'       => $nickname,
            'mobile'         => $param['mobile'],
            'status'         => 2,
            'bankcard'       => [],
            'emp_time'       => [],
            'com_cate'       => [],
            'work_place'     => [],
            'user_tags'      => [],
            'skill_cert'     => [],
            'createtime'     => time(),
            'workexperience' => '',
            'eduexperience'  => '',
            'broker_channel' => 2,
            'education'      => '',
        ];
        $user     = UserModel::create($data);
        $password = md5(time() . mt_rand(100000, 999999));
        $this->authsRegister($user->id, "weixin", $unionid, $password);
        $this->authsRegister($user->id, "mobile", $param['mobile'], $password);
        session('mobile.user.id', $user->userid);

        return page_result(0, '', ['url' => '/mobile/login/broker']);
    }

    public function sendSms()
    {
        $mobile   = input('mobile');
        $ismobile = preg_match('/^1[3456789]{1}[0-9]{9}$/', $mobile);
        if (!$ismobile) {
            page_result(1, "请填入正确的手机号");
        }
        /*$userauths = UserAuthsModel::where(['identifier' => $mobile, 'identitytype' => "mobile"])->findOrEmpty();
        if (!$userauths->isEmpty()) {
            page_result(1, "该手机号已注册");
        }*/

        $smscode = mt_rand(100000, 999999);
        $sms     = new Chuanglan();
        $res     = $sms->send($mobile, ['message' => "尊敬的用户，您的短信验证码为{$smscode}，5分钟内有效。若非本人操作请忽略。"]);
        if ($res['code']) {
            session('mobile.login.verify', $smscode);
            session('mobile.login.verify_expire', time() + 300);
        } else {
            page_result(1, '发送失败，请联系管理员');
        }

        page_result();
    }

    public function broker()
    {
        $unionid = session('mobile.user.unionid');
        $user_id = session('mobile.user.id');
        if (empty($unionid) || empty($user_id)) {
            return redirect('/mobile/login/login');
        }

        $broker = BrokerModel::where('userid', $user_id)->find();
        if (!empty($broker)) {
            return redirect('/mobile/my/index');
        }

        $broker_form = BrokerFormModel::where('userid', $user_id)->find();
        if (!empty($broker_form)) {
            return redirect('/mobile/login/brokerTip');
        }

        $agent_list = AgentModel::where('type', 2)->where('status', 1)->field('title as text,id as value')->select();

        return view('login/broker', ['agent_list' => $agent_list]);
    }

    public function brokerPost()
    {
        $user_id = session('mobile.user.id');
        empty($user_id) && page_result(401, '请先登录');

        $broker_form = BrokerFormModel::where('userid', $user_id)->find();
        if (!empty($broker_form)) {
            return page_result(1, '请不要重复申请');
        }

        $param = input('post.');
        empty($param['title']) && page_result(1, '请输入姓名');
        empty($param['mobile']) && page_result(1, '请输入手机号');
        empty($param['agent_id']) && page_result(1, '请选择门店');
        empty($param['region']) && page_result(1, '请输入区域');

        $agent = AgentModel::where([
            ['id', '=', $param['agent_id']],
            ['type', '=', 2],
            ['status', '=', 1],
        ])->find();
        if (empty($agent)) {
            page_result(1, '门店不存在');
        }

        $user_id = session('mobile.user.id');
        BrokerFormModel::create([
            'userid'     => $user_id,
            'workerid'   => $agent['workerid'],
            'agentid'    => $agent['id'],
            'title'      => $param['title'],
            'avatar'     => '',
            'mobile'     => $param['mobile'],
            'province'   => $agent['province'],
            'city'       => $agent['city'],
            'district'   => $agent['district'],
            'town'       => '',
            'village'    => '',
            'region'     => $param['region'],
            'createtime' => time(),
            'type'       => 3,
        ]);

        page_result(0, '', ['url' => '/mobile/login/brokerTip']);
    }

    public function brokerTip()
    {
        $user_id = session('mobile.user.id');
        if (empty($user_id)) {
            return redirect('/mobile/login/login');
        }
        $broker = BrokerModel::where('userid', $user_id)->find();
        if (!empty($broker)) {
            session('mobile.broker.id', $broker['id']);
            return redirect('/mobile/my/index');
        }

        return view('login/broker_tip');
    }

    public function login1()
    {
        session('mobile.user.id', 293);
        session('mobile.broker.id', 19);
        $back_url = '/mobile/my/index';
        if (session('?back_url')) {
            $back_url = session('back_url');
            session('back_url', null);
        }
        return redirect($back_url);
    }

    /**
     * 登出
     */
    public function logout()
    {
        session('mobile.user.id', null);
        session('mobile.broker.id', null);
        return '退出';
    }

    public function authsRegister($userid, $identitytype, $identifier, $password)
    {
        $userauths = UserAuthsModel::where(['userid' => $userid, 'identitytype' => $identitytype])->findOrEmpty();
        if (!empty($identifier) && $userauths->isEmpty()) {
            $userauths = new UserAuthsModel();
            $userauths->save([
                'userid'       => $userid,
                'identitytype' => $identitytype,
                'identifier'   => $identifier,
                'password'     => $password,
                'logintime'    => time(),
                'loginip'      => $_SERVER['SERVER_ADDR'],
            ]);
        } elseif (!empty($identifier) && $identifier !== $userauths->identifier) {
            $userauths->identifier = $identifier;
            $userauths->password   = $password;
            $userauths->save();
        }
        return true;
    }
}
