<?php

namespace app\user\controller;

use think\Controller;
use think\Lang;
use think\Validate;

class Login extends Controller
{

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/login.lang.php');
    }

    /**
     * 登录
     * @return mixed
     */
    public function index()
    {
        if (session('user_id')) {
            $this->success('已经登录', 'User/Index/index');
        }
        if (request()->isPost()) {

            $user_email = input('post.user_email');
            $user_password = input('post.user_password');
//            $captcha = input('post.captcha');

            $data = array(
                'user_email' => $user_email,
                'user_password' => $user_password,
//                'captcha' => $captcha,
            );

            //验证数据  BEGIN
            $rule = [
                ['user_email', 'require|min:2', '帐号为必填|帐号长度至少为2位'],
                ['user_password', 'require|min:2', '密码为必填|帐号长度至少为6位'],
//                ['captcha', 'require|min:3', '验证码为必填|帐号长度至少为3位'],
            ];
            $validate = new Validate($rule);
            $validate_result = $validate->check($data);

            if (!$validate_result) {
                $this->error($validate->getError());
            }
            //验证数据  END
//            if (!captcha_check(input('post.captcha'))) {
//                //验证失败
//                $this->error('验证码错误');
//            }

            $condition['user_email'] = $user_email;
            $condition['user_password'] = md5($user_password);

            $user_info = db('user')->where($condition)->find();
            if (is_array($user_info) and !empty($user_info)) {
                //更新 admin 最新信息
                $update_info = array(
//                    'admin_login_num' => ($admin_info['admin_login_num'] + 1),
                    'user_loginTime' => TIMESTAMP
                );
                db('user')->where('user_id', $user_info['user_id'])->update($update_info);

                //设置 session
                session('user_id', $user_info['user_id']);
                session('user_email', $user_info['user_email']);

                return $this->redirect('User/Index/index');
            } else {
                $this->success('帐号密码错误');
            }
        } else {
            return $this->fetch();
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        //设置 session
        session(null);
        return $this->redirect('User/Login/index');
        exit;
    }

}


?>
