<?php
namespace app\service\controller;

use think\Controller;

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

        return $this->fetch();
    }

    public function doLogin()
    {
        //验证客服IP
        $settings = db('settings')->where('id',1)->find();
        if($settings['kf_white_list'] == 'on'){
            $ip = request()->ip();
            //将ip地址转换成int型
            $intip = bindec(decbin(ip2long($ip)));
            $res = db('iplimit')->where('ip',$ip)->where('object',2)->find();
            $result = db('iplimit')->where('start_ip','<=',$intip)->where('end_ip','>=',$intip)->where('object',2)->find();
            if(empty($res) && empty($result)){
                return json(['code' => 0, 'data' => [], 'msg' => '访问受限']);
            }
        }

        $userAccount = input('post.username');
        $password = input('post.password');

        //在线客服
        $users = db('kfonline')->select();

        $user = db('users')->where('user_account', $userAccount)->find();
        if(empty($user)){
            return json(['code' => -1, 'data' => '', 'msg' => '客服不存在']);
        }

        if($user['status'] != 1){
            return json(['code' => -3, 'data' => '', 'msg' => '此账号已禁用']);
        }

        /*$has = db('kfonline')->where('uid','KF'.$user['id'])->select();
        if(!empty($has)){
            return json(['code' => -4, 'data' => '', 'msg' => '此账号已登录']);
        }*/

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


        // 登陆成功 生成token
        $module = mt_rand(100000,999999);
        $token = base64_encode($module.'#$@%!^*/'.time().'/'.$user['id']);
        // 更新管理员状态
        $param = [
            'token' => $token,
            'expire_time' => time()
        ];
        db('users')->where('id', $user['id'])->update($param);
        //$user = db('users')->field('id,user_account,user_name,user_avatar,phone,group_id,token')->where('id', $user['id'])->select();
        $user = db('users')->where('id', $user['id'])->select();
        $group = db('groups')->where('id', $user[0]['group_id'])->find();
        $user[0]['group'] = $group['name'];

        $this->assign([
            'token' => $token,
            'user_name' => $user[0]['user_name'],
            'user_account' => $userAccount
        ]);

        return json(['code' => 1, 'data' => ['user' => $user[0]], 'msg' => '登录成功']);
    }

    public function loginOut()
    {

        $this->redirect(url('login/index'));
    }
}
