<?php

namespace app\mobile\controller;

use app\common\model\SinglePageModel;
use app\common\model\UserModel;
use app\common\service\SmsService;
use app\mobile\MobileBaseController;

class Login extends MobileBaseController
{
    public function login()
    {
        $service = SinglePageModel::getConfigValue(['service', 'privacy']);
        foreach ($service as $k => $value) {
            $value   = explode("\n", $value);
            $content = '';
            foreach ($value as $v) {
                $content .= "<p>{$v}</p>";
            }
            $service[$k] = $content;
        }

        return view('', [
            'service' => $service,
        ]);
    }

    public function loginPost()
    {
        $param = input('post.');
        empty($param['type']) && ajax_return(1, '请选择登录方式');

        $user = [];
        if ($param['type'] == 'mobile') {
            empty($param['mobile']) && ajax_return(1, '请输入手机号');
            empty($param['verify']) && ajax_return(1, '请输入验证码');
            //验证码校验
            if (config('mobile.sms_verify_expire') > 0) {
                $verify_expire = session('mobile.login.verify_expire');
                if ($verify_expire + config('mobile.sms_verify_expire') < time()) {
                    session('mobile.login.verify', null);
                    session('mobile.login.verify_expire', null);
                    ajax_return(1, '验证码已过期');
                }
            }
            $verify = session('mobile.login.verify');
            if ($verify != $param['verify']) {
                ajax_return(1, '验证码不正确');
            }

            //登录注册
            $user = UserModel::where('mobile', $param['mobile'])->find();
            if (empty($user)) {
                $user = UserModel::create([
                    'nickname' => '手机用户',
                    'mobile'   => $param['mobile'],
                    'status'   => UserModel::STATUS_PASS,
                ]);
            }
        } elseif ($param['type'] == 'account') {
            empty($param['account']) && ajax_return(1, '请输入账号');
            empty($param['password']) && ajax_return(1, '请输入密码');
            //帐号密码登录
            $user = UserModel::where('account', $param['account'])->find();
            empty($user) && ajax_return(1, '账号或密码错误');

            $password = md5(md5($user['salt']) . $param['password']);
            $password != $user['password'] && ajax_return(1, '账号或密码错误');
        } else {
            ajax_return(1, '请选择登录类型');
        }

        $user->last_login_time = time();
        $user->last_login_ip   = request()->ip();
        $user->save();
        session('mobile.user.id', $user['id']);

        $url = session('back_url') ?? url('/mobile/my/index');
        session('back_url', null);
        ajax_success(['url' => $url]);
    }

    public function sendSms()
    {
        $mobile = trim(input('post.mobile'));

        if (empty($mobile)) {
            ajax_return(1, '手机号为空');
        } else {
            $rand       = rand(100000, 999999);
            $preg_phone = '/^1[34578]\d{9}$/ims';
            if (preg_match($preg_phone, $mobile)) {
                $sms = new SmsService();
                $res = $sms->send($mobile, 'verification', [$rand]);

                if ($res['code'] == 0) {
                    session('mobile.login.verify', $rand);
                    session('mobile.login.verify_expire', time());
                } else {
                    ajax_return(1, '发送失败，请联系管理员');
                }
            } else {
                ajax_return(1, '手机号格式不正确');
            }
        }

        ajax_return();
    }

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

    /**
     * 微信回调
     */
    public function wechatBack()
    {
        $param   = input('param.');
        $open_id = $param['openid'];

        //登录
        $user = UserModel::where(['openid' => $open_id])->find();
        if (empty($user)) {
            $user_id = get_user_id();
            if (empty($user_id)) {
                $user = UserModel::create([
                    'nickname' => $param['nickname'],
                    'avatar'   => $param['headimgurl'],
                    'openid'   => $open_id,
                    'unionid'  => $param['unionid'],
                ]);
            } else {
                UserModel::update([
                    'openid'  => $open_id,
                    'unionid' => $param['unionid'],
                ], ['id' => $user_id]);
            }
        }

        $user->logintime = time();
        $user->loginip   = request()->ip();
        $user->save();

        session('mobile.user.id', $user['id']);
        $url = session('back_url') ?? url('/mobile/my/index');
        session('back_url', null);

        return redirect($url);
    }

    public function logout()
    {
        session('mobile.user.id', null);
        return redirect('/');
    }
}
