<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2024/5/23} {18:01} 
 */

namespace app\api\logic;


use app\api\controller\BaseWssApi;
use app\common\model\TabConf;
use GatewayWorker\Lib\Gateway;
use think\Db;
use wanghua\general_utility_tools_php\Mmodel;
use wanghua\general_utility_tools_php\tool\Tools;

class UserLogic extends BaseLogic
{

    /**
     * desc：客户端离线
     * author：wh
     */
    function offline($client_id){
        Mmodel::catchTrans(function () use ($client_id){
            Tools::log_to_write_txt(['服务端收到客户端离线消息：client_id:' . $client_id]);

            $user = Db::table(TabConf::$fa_users)
                ->where('clientid', $client_id)
                ->find();
            if(empty($user)){
                Tools::log_to_write_txt(['error:客户端离线，用户不存在：client_id:' . $client_id]);
                return ;
            }

            Tools::log_to_write_txt(['写入离线记录：openid:' . $user['openid']]);
            //写入离线记录
            Db::table(TabConf::$fa_user_offline_record)
                ->insert([
                    'openid'=>$user['openid'],
                ]);

            Tools::log_to_write_txt(['设置离线时间：clientid:' . $client_id]);
            Db::table(TabConf::$fa_users)
                ->where('clientid', $client_id)
                ->data([
                    'clientid'=>'',
                    'offline_time'=>Tools::get_now_date(),//离线时间
                ])
                ->update();

            Tools::log_to_write_txt(['好友列表设置为离线：openid:' . $user['openid']]);
            //好友列表设置为离线
            Db::table(TabConf::$fa_gamefriend)
                ->data([
                    'offline_time'=>Tools::get_now_date(),//离线时间
                ])
                ->where('friend_openid',$user['openid'])
                ->update();

            Tools::log_to_write_txt(['返回离线消息']);

            //在$client_id无效的情况下可能会抛出异常
            //$json = BaseWssApi::json_wss('ok', '用户已离线');
            //Gateway::sendToClient($client_id, json_encode($json, JSON_UNESCAPED_UNICODE));
        });
    }
}