<?php
/**
 * User: nickbai
 * Date: 2017/10/24 10:46
 * Email: 1902822973@qq.com
 */
namespace app\index\controller;

use think\Controller;

class Login extends Controller
{
    // 登录首页
    public function index()
    {
        $this->assign([
            'version' => config('version')
        ]);

        return $this->fetch();

    }

    // 处理登录
    public function doLogin()
    {
        if(request()->isPost()){

            $userName = input("param.user_name/s");
            $password = input("param.password/s");

            if(empty($userName)){
                return json(['code' => -1, 'data' => '', 'msg' => '用户名或邮箱不能为空']);
            }

            if(empty($password)){
                return json(['code' => -2, 'data' => '', 'msg' => '密码不能为空']);
            }

            $user_name = db('accounts')->where('account_name', $userName)->find();
            $user_email = db('accounts')->where('account_email', $userName)->find();

            if(empty($user_name) && empty($user_email)){
                return json(['code' => -3, 'data' => '', 'msg' => '用户名或邮箱不存在']);
            }
            if(!empty($user_name)){$userInfo = $user_name;}
            if(!empty($user_email)){$userInfo = $user_email;}

            if(md5($password . config('salt')) != $userInfo['password']){
                return json(['code' => -4, 'data' => '', 'msg' => '密码错误']);
            }

            if(1 != $userInfo['status']){
                return json(['code' => -5, 'data' => '', 'msg' => '您已被禁用']);
            }

            // 登陆成功 生成token
            $module = mt_rand(100000,999999);
            $token = base64_encode($module.'#$@%!^*/'.time().'/'.$userInfo['id']);
            // 更新用户状态
            $param = [
                'token' => $token,
                'expire_time' => time(),
                'last_login_time' => time()
            ];
            db('accounts')->where('id', $userInfo['id'])->update($param);

            $this->assign([
                'token' => $token
            ]);

            return json(['code' => 1, 'data' => url('user/index'), 'msg' => '登陆成功']);
        }
    }

    public function loginOut()
    {
        $this->redirect(url('login/index'));
    }

}