<?php

namespace app\admin\controller;

use app\admin\model\AdminModel;
use app\admin\model\StaffModel;
use think\Controller;
use think\facade\Cache;
use think\facade\Session;
use think\Request;
use app\admin\validate\LoginValidate;
use think\captcha\Captcha;
/**
 * 登录控制器
 * 负责检测用户登录
 * Class Login
 * @package app\admin\controller
 */
class Login extends Controller
{
    public function index()
    {
        echo '<script type="text/javascript">top.location.href="http://oa.gonn.com.cn/";</script>';
    }

    public function login(Request $request,LoginValidate $validate)
    {
        $pattern = config('admin.login_pattern');

        if(!$validate->check($request->post())){
            $data = [
                'status' => 0,
                'message' => $validate->getError()
            ];
            return $data;
        }
        $captcha = new Captcha();
        if( !$captcha->check($request->post('verify')))
        {
            $data = [
                'status' => 0,
                'message' => '验证码错误'
            ];
            return $data;
        }
        //如果是邮箱
        if(preg_match($pattern,$request->post('name'))){
            return $this->checkStaff();
        } else {
            return $this->checkAdmin();
        }
    }
    //验证码
    public function verify()
    {

        $captcha = new Captcha();
        $captcha->fontSize = 30;
        $captcha->length   = 4;
        $captcha->useNoise = true;
        $captcha->imageH=0;
        $captcha->imageW=0;

        return $captcha->entry();
    }

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

    private function checkStaff(){
        $email = $this->request->post('name');
        $passwd = $this->request->post('password');

        $staff = StaffModel::with('passwd')->get(['email'=>$email]);

        if(!$staff){
            $data = [
                'status' => 0,
                'message' => '用户不存在'
            ];
            return $data;
        }
        $status=(new StaffModel)->getStaffStatusByName($email);
         if(!$status['status']==1){
             $data = [
                'status' => 0,
                'message' => '该账户当前禁用，请联系管理员开启'
            ];
            return $data;
         }
        if(decrypt($passwd) == $staff->passwd->passwd){
            $user = [
                'name'=> $staff->name,
                'user_id' => $staff->id,
                'is_admin' => false
            ];
            loginlog($staff->name,$staff->id,'用户成功登录系统',1);
            Session::set('user',$user);
            return $this->goRedirect($user);
        } else {
             loginlog($staff->name,$staff->id,'用户名或密码错误',2);
            $data = [
                'status' => 0,
                'message' => '用户名或密码错误'
            ];
            return $data;
        }
    }

    private function checkAdmin(){
        $name = $this->request->post('name');
        $passwd = decrypt($this->request->post('password'));

        $admin = AdminModel::get(['name'=>$name,'password'=>$passwd]);

        if(!$admin){
            $data = [
                'status' => 0,
                'message' => '用户名或密码错误'
            ];
            return $data;
        } else {
            loginlog($admin->name,$admin->id,'管理员用户成功登录系统',1);
            $user = [
                'name' => $admin->name,
                'user_id' => $admin->id,
                'is_admin' => true
            ];
            //写入登录信息
            $admin->ip = \think\facade\Request::ip();
            $admin->load_times += 1;
            $admin->load_time_at = time();

            $admin->save();

            Session::set('user',$user);
            return $this->goRedirect($user);
        }
    }

    private function goRedirect($user){
        //存储redis

        $key = $this->getRandomStr();
        $data = [
            'status'=> 1,
            'message' => '登录成功',
            'user' => $key,
            'home' => '/'
        ];

        $encryptKey = substr(md5(config('admin.encrypt_key').$key),0,10);
        //存储到redis
        Cache::store('redis')->set($encryptKey,json_encode($user),3600);

        return $data;
    }

    private function getRandomStr($length = 10){
        $strs="QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
        return substr(str_shuffle($strs),mt_rand(0,strlen($strs)-11),$length);
    }
}