<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-present http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\controller;

use app\user\service\UserService;
use think\facade\Validate;
use cmf\controller\HomeBaseController;
use app\user\model\UserModel;

class LoginController extends HomeBaseController
{

    /**
     * 登录
     */
    public function index()
    {
        $redirect = $this->request->param("redirect");
        if (empty($redirect)) {
            $redirect = $this->request->server('HTTP_REFERER');
        } else {
            if (strpos($redirect, '/') === 0 || strpos($redirect, 'http') === 0) {
            } else {
                $redirect = base64_decode($redirect);
            }
        }
        if (!empty($redirect)) {
            session('login_http_referer', $redirect);
        }
        if (cmf_is_user_login()) { //已经登录时直接跳到首页
            return redirect($this->request->root() . '/');
        } else {
            return $this->fetch(":login");
        }
    }

    /**
     * 登录验证提交
     */
    public function doLogin()
    {
        if ($this->request->isPost()) {
            $validate = new \think\Validate();
            $validate->rule([
                'captcha'  => 'require',
                'username' => 'require',
                'password' => 'require|min:6|max:32',
            ]);
            $validate->message([
                'username.require' => lang('用户名不能为空！'),
                'password.require' => lang('密码不能为空！'),
                'password.max'     => lang('密码不能超过32个字符！'),
                'password.min'     => lang('密码不能小于6个字符！'),
                'captcha.require'  => lang('验证码不能为空！'),
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            if (!cmf_captcha_check($data['captcha'])) {
                $this->error(lang('验证码错误！'));
            }

            $user['user_pass'] = $data['password'];
            if (Validate::is($data['username'], 'email')) {
                $user['user_email'] = $data['username'];
                $log                = UserService::doEmail($user);
            } else if (cmf_check_mobile($data['username'])) {
                $user['mobile'] = $data['username'];
                $log            = UserService::doMobile($user);
            } else {
                $user['user_login'] = $data['username'];
                $log                = UserService::doName($user);
            }
            $session_login_http_referer = session('login_http_referer');
            $redirect                   = empty($session_login_http_referer) ? $this->request->root() : $session_login_http_referer;
            switch ($log) {
                case 0:
                    $this->success(lang('登录成功！'), $redirect);
                    break;
                case 1:
                    $this->error(lang('密码错误！'));
                    break;
                case 2:
                    $this->error(lang('账户不存在！'));
                    break;
                case 3:
                    $this->error(lang('账号被禁止访问系统！'));
                    break;
                default :
                    $this->error(lang('未受理的请求！'));
            }
        } else {
            $this->error(lang('请求错误！'));
        }
    }

    /**
     * 找回密码
     */
    public function findPassword()
    {
        return $this->fetch('/find_password');
    }

    /**
     * 用户密码重置
     */
    public function passwordReset()
    {
        if ($this->request->isPost()) {
            $validate = new \think\Validate();
            $validate->rule([
                //'captcha'           => 'require',
                'verification_code' => 'require',
                'password'          => 'require|min:6|max:32',
            ]);
            $validate->message([
                'verification_code.require' => lang('数字验证码不能为空！'),
                'password.require'          => lang('密码不能为空！'),
                'password.max'              => lang('密码不能超过32个字符！'),
                'password.min'              => lang('密码不能小于6个字符！'),
                'captcha.require'           => lang('验证码不能为空！'),
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            $result = hook_one("check_third_party_captcha");

            if ($result) {
                if (is_string($result)) {
                    $this->error($result);
                }
            } else {
                if (empty($data['captcha'])) {
                    $this->error(lang('验证码不能为空！'));
                }
                $captchaId = empty($data['_captcha_id']) ? '' : $data['_captcha_id'];
                if (!cmf_captcha_check($data['captcha'], $captchaId)) {
                    $this->error(lang('验证码错误！'));
                }

                $errMsg = cmf_check_verification_code($data['username'], $data['verification_code']);
                if (!empty($errMsg)) {
                    $this->error($errMsg);
                }
            }

            if (Validate::is($data['username'], 'email')) {
                $log = UserService::emailPasswordReset($data['username'], $data['password']);

            } else if (cmf_check_mobile($data['username'])) {
                $user['mobile'] = $data['username'];
                $log            = UserService::mobilePasswordReset($data['username'], $data['password']);
            } else {
                $log = 2;
            }
            switch ($log) {
                case 0:
                    $this->success(lang('密码重置成功！'), cmf_url('user/Profile/center'));
                case 1:
                    $this->error(lang('您的账户尚未注册！'));
                case 2:
                    $this->error(lang('您输入的账号格式错误！'));
                default :
                    $this->error(lang('未受理的请求！'));
            }

        } else {
            $this->error(lang('illegal request'));
        }
    }


}
