package com.qmth.themis.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.qmth.themis.business.dao.TBSessionMapper;
import com.qmth.themis.business.entity.TBSession;
import com.qmth.themis.business.service.TBSessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Description: 会话信息 服务实现类
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/6/25
 */
@Service
public class TBSessionServiceImpl extends ServiceImpl<TBSessionMapper, TBSession> implements TBSessionService {
    private final static Logger log = LoggerFactory.getLogger(TBSessionServiceImpl.class);

    /**
     * 保存session信息
     *
     * @param tbSession
     * @param mqTimestamp
     * @return
     */
    @Override
    public boolean saveSessionInfo(TBSession tbSession, Long mqTimestamp) {
        TBSession tbSessionDb = this.getById(tbSession.getId());
        if (Objects.isNull(tbSessionDb)) {
            Gson gson = new Gson();
            tbSessionDb = gson.fromJson(gson.toJson(tbSession), TBSession.class);
            this.saveOrUpdate(tbSessionDb);
        } else if (Objects.nonNull(tbSessionDb.getUpdateTime())) {
            Long dbtimestamp = Objects.nonNull(tbSessionDb.getUpdateTime()) ? tbSessionDb.getUpdateTime() : 0L;
            if (mqTimestamp.longValue() > dbtimestamp.longValue()) {
                log.info("mq时间大于db时间，可以更新");
                tbSessionDb.setSource(tbSession.getSource());
                tbSessionDb.setPlatform(tbSession.getPlatform());
                tbSessionDb.setDeviceId(tbSession.getDeviceId());
                tbSessionDb.setAccessToken(tbSession.getAccessToken());
                tbSessionDb.setLastAccessIp(tbSession.getLastAccessIp());
                tbSessionDb.setLastAccessTime(tbSession.getLastAccessTime());
                tbSessionDb.setExpireTime(tbSession.getExpireTime());
                this.saveOrUpdate(tbSessionDb);
            }
        }
        return true;
    }
}
