<?php
namespace app\mobile\controller;
use app\mobile\BaseController;
use think\facade\Session;
use think\facade\Cache;
use think\facade\Cookie;
use app\common\model\User as UserModel;
use app\common\variable\MsgCode;
use GatewayClient\Gateway;
class Base extends BaseController
{
    protected $middleware = ['VerificationApi'];
    /**
     * [__construct 构造函数]
     * @return [type] [description]
     */
    public function __construct(){
        parent::__construct(App());
        $User=Session::get('User');
        if ($User && Cache::has('updateUser:'.$User['id'])) {
            Cache::delete('updateUser:'.$User['id']);
            $UserInfo=UserModel::getWebUserInfo(['user.id'=>$User['id']]);
            Session::set('User',$UserInfo->toArray());
        }
    }
    /**
     * [outLogin 注销登录]
     * @return [type] [description]
     */
    public function outLogin()
    {
        $UserInfo=Session::get('User');
        Session::delete('User');
        if(!$UserInfo)
            return $this->ajaxReturn();
        $cacheUserInfo=Cookie::get('cacheUserInfo');
        if ($cacheUserInfo)
            Cache::delete($cacheUserInfo);
        $MessageKey=Cache::get('Message::'.$UserInfo['id']);
        if ($MessageKey) {
            Cache::delete('Message::'.$UserInfo['id']);
            Cache::delete('Message::'.$MessageKey);
        }
        if (!empty($UserInfo['client_id'])) {
            Gateway::$registerAddress = config('gateway_worker.registerAddress');
            Gateway::sendToGroup('Pc:uid-'.$UserInfo['id'],socketMsg('outLogin'));
            Gateway::ungroup('Pc:uid-'.$UserInfo['id']);
            foreach ($UserInfo['client_id'] as $k => $client_id) {
                Gateway::joinGroup($client_id, 'Pc:role-company');
                Gateway::joinGroup($client_id, 'Pc:role-personal');
            }
        }
        return $this->ajaxReturn();
    }
    /**
     * [ajaxReturn 返回json]
     * @param  integer $code [description]
     * @param  [type]  $data [description]
     * @return [type]        [description]
     */
    public function ajaxReturn($msg='Success',$code=0,$data=[]){
        if (!$code)$code=MsgCode::$success;
        return json(['code'=>$code,'msg'=>$msg,'data'=>$data,'time'=>date('Y-m-d H:i:s')]);
    }
}
