<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use app\common\behavior\AdminLogBehavior;
use think\Cache;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Hook;
use think\Session;

class Common extends Controller
{
    const USE_REMEMBER = 'usermember';

    protected function _initialize()
    {
        stopCC();

        if (\think\Env::get('online_status', 'open') == 'close') {
            exit("网站后台维护中 ...");
        }
        Hook::listen('admin_log');
    }

    /**
     * 登录
     * //不适用表单令牌，验证码输错时，token不会变，导致要刷新页面并重新输入
     * @return mixed
     */
    public function login()
    {
        if (Session::has(Permissions::ADMIN_ID) == false) {
            if ($this->request->isPost()) {
                $post = $this->request->post();
                $validate = new \think\Validate([
                    ['name|账号', 'require|alphaDash|max:30'],
                    ['password|密码', 'require|length:6,32'],
                    ['captcha', 'require|captcha', '验证码不能为空|验证码不正确'],
                ]);
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                //连续错误5次账号暂停
                $error_count = Cache::get('error_count' . $post['name']);
                if ($error_count >= 5) {
                    (new AdminLogBehavior())->updateLastLog("登入频繁,请休息10分钟", false);
                    $this->error('登入频繁,请休息10分钟');
                }

                $name = Db::name('admin')->where('name', $post['name'])->find();
                if (empty($name)) {
                    //不存在该用户名
                    (new AdminLogBehavior())->updateLastLog("账号不存在", false);
                    $this->error('账号不存在');
                } else {
                    //验证密码
                    $post['password'] = password($post['password']);
                    if ($name['password'] != $post['password']) {
                        //记录次数
                        if (empty($error_count)) {
                            Cache::set('error_count' . $post['name'], 1, 600);
                        } else {
                            Cache::set('error_count' . $post['name'], ++$error_count, 600);
                        }
                        (new AdminLogBehavior())->updateLastLog("密码错误", false);
                        $this->error('密码错误');
                    } else {
                        //是否记住账号
                        if (!empty($post['remember']) and $post['remember'] == 1) {
                            //检查当前有没有记住的账号
                            if (Cookie::has(self::USE_REMEMBER)) {
                                Cookie::delete(self::USE_REMEMBER);
                            }
                            //保存新的
                            Cookie::forever(self::USE_REMEMBER, $post['name']);
                        } else {
                            //未选择记住账号，或取消操作
                            if (Cookie::has(self::USE_REMEMBER)) {
                                Cookie::delete(self::USE_REMEMBER);
                            }
                        }
                        Session::set(Permissions::ADMIN_ID, $name['id']); //保存admin_id
                        Session::set(Permissions::ADMIN_NAME, $name['nickname']); //保存admin_name
                        Session::set(Permissions::ADMIN_CATE_ID, $name['admin_cate_id']); //保存admin_cate_id
                        //记录登录时间和ip
                        Db::name('admin')->where('id', $name['id'])->update(['login_ip' => $this->request->ip(), 'login_time' => time()]);
                        //清空次数
                        Cache::rm('error_count' . $post['name']);
                        (new AdminLogBehavior())->updateLastLog("登录成功", false);
                        $this->success('登录成功,正在跳转...', 'admin/index/index');
                    }
                }
            } else {
                if (Cookie::has(self::USE_REMEMBER)) {
                    $this->assign(self::USE_REMEMBER, Cookie::get(self::USE_REMEMBER));
                }
                return $this->fetch();
            }
        } else {
            $this->redirect('admin/index/index');
        }
    }

}
