
package com.tmerclub.cloud.user.service.impl;

import cn.hutool.core.date.DateUtil;
import com.tmerclub.cloud.user.bo.mongo.MongoPopupUserLogBO;
import com.tmerclub.cloud.user.model.CostPerPopup;
import com.tmerclub.cloud.user.service.PopupUserLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 弹窗广告用户日志
 * @author TRACK
 */
@Service
public class PopupUserLogServiceImpl implements PopupUserLogService {

    @Autowired
    private MongoTemplate mongoTemplate;
    private static final String TIME_FORMAT = "yyMMdd";

    @Override
    public void removeByPopupId(Long popupId) {
        mongoTemplate.remove(new Query(Criteria.where("popupId").is(popupId)), MongoPopupUserLogBO.class);
    }

    @Override
    public void save(MongoPopupUserLogBO log) {
        log.setCreateTime(DateUtil.format(new Date(), TIME_FORMAT));
        mongoTemplate.save(log);
    }

    @Override
    public List<MongoPopupUserLogBO> getByCondition(Long userId, Long uuid, CostPerPopup costPerPopup) {
        Criteria criteria = Criteria.where("popupId").is(costPerPopup.getPopupId());
        if (Objects.nonNull(userId)) {
            criteria.and("userId").is(userId);
        } else {
            criteria.and("uuid").is(uuid);
        }
        if (Objects.nonNull(costPerPopup.getWeekFrequency())) {
            String maxTime = DateUtil.format(new Date(), TIME_FORMAT);
            String minTime = DateUtil.format(DateUtil.beginOfDay(new Date()), TIME_FORMAT);
            // 按周推送校验今天有没有推送过
            criteria.and("createTime").lte(maxTime).gte(minTime);
        }
        if (Objects.nonNull(costPerPopup.getDayFrequency())) {
            // 按天推送校验x天前到今天有没有推送过
            String maxTime = DateUtil.format(new Date(), TIME_FORMAT);
            String minTime = DateUtil.format(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -costPerPopup.getDayFrequency())), TIME_FORMAT);
            criteria.and("createTime").lte(maxTime).gte(minTime);
        }
        return mongoTemplate.find(new Query(criteria), MongoPopupUserLogBO.class);
    }
}
