<?php
namespace app\bsadmin\controller;
use think\facade\View;
use think\facade\Cookie;
use think\facade\Session;
use think\facade\Db;
use think\Validate;
use app\bsadmin\model\Admin;
use app\bsadmin\model\AdminLoginLog;
use app\common\controller\Captcha as CaptchaController;
class Login extends Base
{
    /**
     * [__construct 构造函数]
     * @return [type] [description]
     */
    public function __construct(){
    }
    public function index()
    {
        if (request()->isAjax()) {
            $D=request()->post();
            $headers=request()->header();
            $is_imgcode=intval(Cookie::get('is_imgcode'),0);
            $errorCode=-100;
            // 数据验证
            $rule = [
                'user'                => 'require|alphaNum|length:6,25',
                'pass'                => 'require|length:6,25',
            ];
            $msg = [
                'user.require'        => '用户名不能为空',
                'user.alphaNum'       => '用户名不合法',
                'user.length'         => '用户名长度应在6~25位之间',
                'pass.require'        => '密码不能为空',
                'pass.length'         => '密码长度应在6~25位之间',
            ];
            if ($is_imgcode && $is_imgcode>=config('captcha.error_sum')){
                $errorCode=1001;
                if (!CaptchaController::captcha_check($D))
                    return $this->ajaxReturn('验证码错误',$errorCode);
            }
            $validate = new Validate($rule, $msg);
            $result = $validate->check($D);
            if(true !== $result){
                return $this->ajaxReturn($validate->getError(),$errorCode);
            }
            $is_imgcode=$is_imgcode+1;
            if ($is_imgcode && $is_imgcode>=config('captcha.error_sum'))$errorCode=1001;
            $admin=Admin::where(['admin.username'=>$D['user']])->alias('admin')
                ->join('role role','role.rid = admin.role_id')
                ->field('admin.*,role.rid,role.title')->find();
            if(!$admin){
                Cookie::set('is_imgcode',$is_imgcode);
                return $this->ajaxReturn('该管理员不存在',$errorCode);
            }
            if($admin->password!==Admin::getAdminPassword($admin->password_hash,$D['pass'])){
                Cookie::set('is_imgcode',$is_imgcode);
                return $this->ajaxReturn('密码错误',$errorCode);
            }
            if(!$admin->status){
                Cookie::set('is_imgcode',$is_imgcode);
                return $this->ajaxReturn('该管理员已被禁止登录',$errorCode);
            }
            $nowTime=intval(date('H'));
            if(!($nowTime>=$admin->allow_time_start && $nowTime<=$admin->allow_time_end && in_array(date('w'),explode(',',$admin->allow_week)))){
                Cookie::set('is_imgcode',$is_imgcode);
                return $this->ajaxReturn('当前时间段不在工作范围内',$errorCode);
            }
            //重组管理员信息
            $userInfo=[
                'uid'       =>  $admin->id,
                'headimg'   =>  $admin->headimg,
                'nickname'  =>  $admin->nickname,
                'title'     =>  $admin->title,
                'rid'       =>  $admin->role_id,
                'start'     =>  $admin->allow_time_start,
                'end'       =>  $admin->allow_time_end,
                'week'      =>  $admin->allow_week,
            ];
            $admin->login_time=time();
            $admin_log=new AdminLoginLog;
            $admin_log->admin_id=$admin->id;
            $admin_log->is_mobile=request()->isMobile();
            $admin_log->ip=request()->ip();
            $admin_log->user_agent=substr(request()->header('user-agent'),0,200);
            $admin_log->create_time=time();
            Db::startTrans();
            try {
                $admin->save();
                $admin_log->save();
                Db::commit();
                Session::set('AdminUser',$userInfo);
                Cookie::delete('is_imgcode');
                return $this->ajaxReturn('登录成功');
            } catch (Exception $e) {
                Db::rollback();
                return $this->ajaxReturn('登录失败，请重试',-100);
            }
        }else{
            $is_imgcode=intval(Cookie::get('is_imgcode'),0);
            if ($is_imgcode && $is_imgcode>=config('captcha.error_sum')) {
                $is_imgcode=1;
            }else{
                $is_imgcode=0;
            }
            View::assign('is_imgcode',$is_imgcode);
            return View::fetch();
        }
    }
    public function unauthorized()
    {
    	$G=request()->get();
        $msg='';
        if (!empty($G)) {
            $msg=$G['msg'];
        }
    	View::assign('message',$msg);
    	return View::fetch();
    }
    /**
     * [captcha 手动验证码]
     * @return [type] [description]
     */
    public function captcha()
    {
        return CaptchaController::captcha();
    }
}
