<?php
declare (strict_types = 1);

namespace app\agent\controller;
use app\apicom\model\Member;
use app\apicom\model\JWT;
use think\facade\Session;
use util\Captcha;
use think\facade\Db;
use util\RedisUtil;

class Login extends AgentBase
{
    
    public function index()
    {
        if (!sysConfig("web_site_status")) return ajaxmsg('站点已经关闭',0);
        // 用户参数
        $data['mobile']   = input('username', '');
        $data['password'] = input('password', '');
        // 查询用户
        $user = Member::where('mobile', $data['mobile'])->find();
        
        // 是否被禁止登录
        if($user) {
            if($user['status'] !== 1)  return ajaxmsg('禁止登陆',0);
            if($user['agent_id'] != 1) return ajaxmsg('不是代理',0);
            if(!password_verify($data['password'], $user['passwd'])) return ajaxmsg('密码错误',0);
            $datas = self::doLogin($user);
            if(!$datas) return ajaxmsg('登录失败',0);
            return ajaxmsg('登录成功',200,$datas);
        }
        return ajaxmsg('手机号或密码错误',0);
    }
    
    public function doLogin($user)
    {
        $ret = Member::where('id',$user['id'])->update(['last_login_time'=>date('Y-m-d H:i:s'),'last_login_ip'=>getClientIp()]);
        if($ret){
            $token = array(
                "uid"    => $user['id'],
                "name"   => $user['name'],
                'doHost' => WS_SERVER_IP,
                'doTime' => time(),
                "mobile" => $user['mobile'],
            );
            $jwt = JWT::encode($token,LOCAL_TRADING_TOKEN);
            RedisUtil::cacheToken($jwt, $token);
            $datas['token']  = $jwt;
            $datas['mobile'] = $user['mobile'];
            $datas['uid']    = $user['id'];
            return $datas;
        }
        return false;
    }
    /*
    * 退出登录
    */
    public function signout()
    {
        if ($this->token != '') {
            RedisUtil::deleteToken($this->token);
        }
        return ajaxmsg('退出登录成功',1);
    }
}
