package com.red.circle.other.infra.database.rds.service.user.user.impl;


import com.alibaba.fastjson.JSON;
import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.other.infra.database.rds.dao.user.user.OnlineTimeDAO;
import com.red.circle.other.infra.database.rds.entity.user.user.OnlineTime;
import com.red.circle.other.infra.database.rds.service.user.user.OnlineTimeService;
import com.red.circle.tool.core.date.LocalDateUtils;
import com.red.circle.tool.core.date.TimestampUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 用户在线时长 服务实现类
 * </p>
 *
 * @author pengliang
 * @since 2020-06-02
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OnlineTimeServiceImpl extends BaseServiceImpl<OnlineTimeDAO, OnlineTime> implements
        OnlineTimeService {

    @Override
    public void inrOnlineOneMinute(Long userId, String sysOrigin) {
        long dateTimeKye = LocalDateUtils.nowTimestamp().getTime();
        OnlineTime onlineTime = query()
                .select(OnlineTime::getId, OnlineTime::getUpdateTime)
                .eq(OnlineTime::getUserId, userId)
                .eq(OnlineTime::getDateTime, dateTimeKye)
                .last(PageConstant.LIMIT_ONE)
                .getOne();
        log.info("inrOnlineOneMinute:{}", JSON.toJSON(onlineTime));
        if (Objects.nonNull(onlineTime)) {

            long currentTimeMillis = System.currentTimeMillis();
            long updateTimeMillis = onlineTime.getUpdateTime().getTime();
            long intervalMinute = (currentTimeMillis - updateTimeMillis) / (1000 * 60);

            log.info("inrOnlineOneMinute:{},{},{}", currentTimeMillis, updateTimeMillis, intervalMinute);

            if (intervalMinute < 1) {
                return;
            }

            update().setSql("time=time+1")
                    .set(OnlineTime::getUpdateTime, TimestampUtils.now())
                    .eq(OnlineTime::getId, onlineTime.getId())
                    .execute();
            return;
        }

        try {
            save(new OnlineTime()
                    .setSysOrigin(sysOrigin)
                    .setUserId(userId)
                    .setTime(1)
                    .setDateTime(dateTimeKye)
            );
        } catch (DuplicateKeyException ignore) {
            // ignore
        }
    }


}
