package com.qs.mp.quartz.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qs.mp.channel.domain.ChannelCommission;
import com.qs.mp.channel.service.IChannelCommissionService;
import com.qs.mp.common.utils.DateUtils;
import com.qs.mp.common.utils.LogUtil;
import com.qs.mp.common.utils.StringUtils;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 渠道佣金按天汇总入账
 *
 * @author zhongcp
 * @Date 2022/3/17
 */
@Component("channelCommTask")
public class ChannelCommTask {

  protected final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

  @Autowired
  private IChannelCommissionService channelCommissionService;

  /**
   * 渠道佣金汇总记账任务
   */
  public void sumComm(String executeDay) {
    LogUtil.info(logger, "...渠道佣金汇总入账定时任务开始...");
    Date bizDay;
    if (StringUtils.isNotBlank(executeDay)) {
      bizDay = DateUtils.parseStrToDate(executeDay, DateUtils.YYYYMMDD);
    } else {
      bizDay = DateUtils.addDays(DateUtils.getToday(), -1);
    }

    // 捞取前一天有分佣的渠道ID
    List<ChannelCommission> channelList = channelCommissionService.getChannelList(
        new QueryWrapper<ChannelCommission>()
            .gt("t2.level", 0)
            .ge("t1.created_time", bizDay)
            .lt("t1.created_time", DateUtils.addDays(bizDay, 1)));
    for (ChannelCommission channelCommission : channelList) {
      try {
        channelCommissionService.commEntry(channelCommission.getChannelId(), bizDay);
      } catch (Exception e) {
        LogUtil.error(logger, e, "渠道佣金汇总入账异常。channelId:{0}", channelCommission.getChannelId());
      }
    }

    LogUtil.info(logger, "...渠道佣金汇总入账定时任务结束...");
  }
}
