package com.qs.mp.quartz.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qs.mp.admin.domain.TicketBox;
import com.qs.mp.admin.service.ITicketBoxService;
import com.qs.mp.channel.domain.Channel;
import com.qs.mp.channel.domain.ChannelCommission;
import com.qs.mp.channel.domain.ChannelCouponVerifyLog;
import com.qs.mp.channel.domain.ChannelWithdraw;
import com.qs.mp.channel.service.IChannelCommissionService;
import com.qs.mp.channel.service.IChannelCouponVerifyLogService;
import com.qs.mp.channel.service.IChannelService;
import com.qs.mp.channel.service.IChannelWithdrawService;
import com.qs.mp.common.enums.ChannelWithdrawStatusEnum;
import com.qs.mp.common.enums.CoinLogTypeEnum;
import com.qs.mp.common.enums.CouponDiscountTypeEnum;
import com.qs.mp.common.enums.TicketBoxStatusEnum;
import com.qs.mp.common.enums.TicketTypeEnum;
import com.qs.mp.common.enums.UserTicketOrderStatusEnum;
import com.qs.mp.common.utils.DateUtils;
import com.qs.mp.common.utils.LogUtil;
import com.qs.mp.common.utils.StringUtils;
import com.qs.mp.common.utils.WebhookService;
import com.qs.mp.system.domain.SysUser;
import com.qs.mp.system.service.ISysUserService;
import com.qs.mp.user.domain.UserCoinLog;
import com.qs.mp.user.domain.UserExchangeOrder;
import com.qs.mp.user.domain.UserTicketOrder;
import com.qs.mp.user.service.IUserCoinLogService;
import com.qs.mp.user.service.IUserExchangeOrderService;
import com.qs.mp.user.service.IUserTicketOrderService;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 日统计任务
 *
 * @author zhongcp
 * @Date 2022/3/17
 */
@Component("dayStatTask")
public class DayStatTask {

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

  @Autowired
  private ISysUserService sysUserService;

  @Autowired
  private IChannelService channelService;

  @Autowired
  private ITicketBoxService ticketBoxService;

  @Autowired
  private IUserTicketOrderService userTicketOrderService;

  @Autowired
  private IChannelCommissionService channelCommissionService;

  @Autowired
  private IChannelWithdrawService channelWithdrawService;

  @Autowired
  private IUserExchangeOrderService userExchangeOrderService;

  @Autowired
  private IUserCoinLogService userCoinLogService;

  @Autowired
  private IChannelCouponVerifyLogService channelCouponVerifyLogService;

  @Value("${export.page-size}")
  private int pageSize;

  /**
   * 日统计任务 2022.04.02 代理：xxx 门店：xxx 用户：xxx =============== 票组名字|线上（面值），销售：¥0.00 票组名字|线上（面值），销售：¥0.00
   * 总销售额：¥0.00 累计分佣：¥0.00 累计提现：¥0.00 兑换订单：5689 派发盲豆：8880 兑换盲豆：6666
   */
  public void stat(String executeDay) {
    LogUtil.info(logger, "...日统计定时任务开始...");
    Date bizDay;
    if (StringUtils.isNotBlank(executeDay)) {
      bizDay = DateUtils.parseStrToDate(executeDay, DateUtils.YYYYMMDD);
    } else {
      bizDay = DateUtils.addDays(DateUtils.getToday(), -1);
    }
    StringBuilder sb = new StringBuilder();
    sb.append(DateUtils.dateTime(bizDay)).append("\n");
    int allChannelCnt = channelService.count(new LambdaQueryWrapper<Channel>().gt(Channel::getLevel, 0));
    int channelCnt = channelService.count(new LambdaQueryWrapper<Channel>().gt(Channel::getLevel, 0)
        .ge(Channel::getCreatedTime, bizDay)
        .lt(Channel::getCreatedTime, DateUtils.addDays(bizDay, 1)));
    sb.append("累计代理：").append(allChannelCnt).append("，当日新增：").append(channelCnt).append("\n");
    int siteCnt = channelService.count(new LambdaQueryWrapper<Channel>().eq(Channel::getLevel, 0)
        .ge(Channel::getCreatedTime, bizDay)
        .lt(Channel::getCreatedTime, DateUtils.addDays(bizDay, 1)));
    int allSiteCnt = channelService.count(new LambdaQueryWrapper<Channel>().eq(Channel::getLevel, 0));
    sb.append("累计门店：").append(allSiteCnt).append("，当日新增：").append(siteCnt).append("\n");
    int userCnt = sysUserService.count(new LambdaQueryWrapper<SysUser>()
        .ge(SysUser::getCreateTime, bizDay)
        .lt(SysUser::getCreateTime, DateUtils.addDays(bizDay, 1)));
    int allUserCnt = sysUserService.count(new LambdaQueryWrapper<SysUser>());
    sb.append("累计用户：").append(allUserCnt - allSiteCnt - allChannelCnt).append("，当日新增：").append(userCnt - siteCnt - channelCnt).append("\n");
    sb.append("===================\n");

    StringBuffer sbDetail = new StringBuffer("");
    LambdaQueryWrapper<TicketBox> queryWrapper = new LambdaQueryWrapper<TicketBox>()
//        .nested(wrapper -> {
//          wrapper.eq(TicketBox::getType, TicketTypeEnum.ONLINE).eq(TicketBox::getStatus,
//              TicketBoxStatusEnum.PUT_ON).or().eq(TicketBox::getType, TicketTypeEnum.OFFLINE);
//        })
//        .notLike(TicketBox::getTitle, "测试票")
        .eq(TicketBox::getIsDeleted, 0);

    int totalSize = ticketBoxService.count(queryWrapper);
    int totalPage = 1;
    if (totalSize > pageSize) {
      totalPage = totalSize % pageSize == 0 ? totalSize / pageSize : totalSize / pageSize + 1;
    }
    BigDecimal sumSaleAmt = BigDecimal.ZERO;
    BigDecimal sumAllSaleAmt = BigDecimal.ZERO;
    for (int i = 0; i < totalPage; i++) {
      queryWrapper.orderByAsc(TicketBox::getBoxNo);
      queryWrapper.last("limit " + (i * pageSize) + ", " + pageSize);
      List<TicketBox> ticketBoxList = ticketBoxService.list(queryWrapper);
      for (TicketBox ticketBox : ticketBoxList) {
        Map<String, Object> orderMap = userTicketOrderService.getMap(
            new QueryWrapper<UserTicketOrder>()
                .select("IFNULL(sum(pay_amt) ,0) as orderAmt")
                .lambda().eq(UserTicketOrder::getBoxId, ticketBox.getBoxId())
                .eq(UserTicketOrder::getStatus, UserTicketOrderStatusEnum.FINISHED)
                .ge(UserTicketOrder::getPayTime, bizDay)
                .lt(UserTicketOrder::getPayTime, DateUtils.addDays(bizDay, 1)));
        if (null != orderMap) {
          BigDecimal orderAmt = new BigDecimal(
              Integer.valueOf(String.valueOf(orderMap.get("orderAmt")))).divide(new BigDecimal(100),
              2, RoundingMode.DOWN);
          sumSaleAmt = sumSaleAmt.add(orderAmt);

          Map<String, Object> allOrderMap = userTicketOrderService.getMap(
              new QueryWrapper<UserTicketOrder>()
                  .select("IFNULL(sum(pay_amt) ,0) as orderAmt")
                  .lambda().eq(UserTicketOrder::getBoxId, ticketBox.getBoxId())
                  .eq(UserTicketOrder::getStatus, UserTicketOrderStatusEnum.FINISHED)
                  .lt(UserTicketOrder::getPayTime, DateUtils.addDays(bizDay, 1)));
          BigDecimal allOrderAmt = new BigDecimal(
              Integer.valueOf(String.valueOf(allOrderMap.get("orderAmt")))).divide(new BigDecimal(100),
              2, RoundingMode.DOWN);
          sumAllSaleAmt = sumAllSaleAmt.add(allOrderAmt);
          // 只输出当日销量大于0的票组
          if (orderAmt.compareTo(BigDecimal.ZERO) > 0) {
            sbDetail.append(ticketBox.getTitle()).append("|").append(ticketBox.getType().getDesc())
                .append("(").append(
                    new BigDecimal(ticketBox.getSalePrice()).divide(new BigDecimal(100), 2,
                        RoundingMode.DOWN)).append("元)，累计销售额：")
                .append(allOrderAmt).append("元，当日：")
                .append(orderAmt).append("元\n");
            sbDetail.append("------------------------\n");
          }
        }
      }
    }

    sb.append("累计销售额：").append(sumAllSaleAmt).append("元，当日：").append(sumSaleAmt).append("元\n");

    Map<String, Object> commMap = channelCommissionService.getMap(
        new QueryWrapper<ChannelCommission>()
            .select("IFNULL(sum(comm_amt) ,0) as commAmt")
            .lambda().ge(ChannelCommission::getCreatedTime, bizDay)
            .lt(ChannelCommission::getCreatedTime, DateUtils.addDays(bizDay, 1)));
    Map<String, Object> allCommMap = channelCommissionService.getMap(
        new QueryWrapper<ChannelCommission>()
            .select("IFNULL(sum(comm_amt) ,0) as commAmt")
            .lambda().lt(ChannelCommission::getCreatedTime, DateUtils.addDays(bizDay, 1)));
    if (null != commMap) {
      sb.append("累计分佣：").append(
              new BigDecimal(Integer.valueOf(String.valueOf(allCommMap.get("commAmt")))).divide(
                  new BigDecimal(100), 2, RoundingMode.DOWN))
          .append("元，当日：").append(
              new BigDecimal(Integer.valueOf(String.valueOf(commMap.get("commAmt")))).divide(
                  new BigDecimal(100), 2, RoundingMode.DOWN)).append("元\n");
    }

    Map<String, Object> couponMap = channelCouponVerifyLogService.getMap(
        new QueryWrapper<ChannelCouponVerifyLog>()
            .select("IFNULL(sum(discount) ,0) as discount")
            .lambda().ge(ChannelCouponVerifyLog::getCreatedTime, bizDay)
            .lt(ChannelCouponVerifyLog::getCreatedTime, DateUtils.addDays(bizDay, 1))
            .eq(ChannelCouponVerifyLog::getDiscountType, CouponDiscountTypeEnum.MONEY_OFF));
    Map<String, Object> allCouponMap = channelCouponVerifyLogService.getMap(
        new QueryWrapper<ChannelCouponVerifyLog>()
            .select("IFNULL(sum(discount) ,0) as discount")
            .lambda().lt(ChannelCouponVerifyLog::getCreatedTime, DateUtils.addDays(bizDay, 1))
            .eq(ChannelCouponVerifyLog::getDiscountType, CouponDiscountTypeEnum.MONEY_OFF));
    if (null != commMap) {
      sb.append("累计核销：").append(
              new BigDecimal(Integer.valueOf(String.valueOf(allCouponMap.get("discount")))).divide(
                  new BigDecimal(100), 2, RoundingMode.DOWN))
          .append("元，当日：").append(
              new BigDecimal(Integer.valueOf(String.valueOf(couponMap.get("discount")))).divide(
                  new BigDecimal(100), 2, RoundingMode.DOWN)).append("元\n");
    }

    Map<String, Object> withdrawMap = channelWithdrawService.getMap(
        new QueryWrapper<ChannelWithdraw>()
            .select("IFNULL(sum(money) ,0) as withdrawAmt")
            .lambda().ge(ChannelWithdraw::getCreateTime, bizDay)
            .lt(ChannelWithdraw::getCreateTime, DateUtils.addDays(bizDay, 1))
            .eq(ChannelWithdraw::getStatus, ChannelWithdrawStatusEnum.FINISHED));
    Map<String, Object> allWithdrawMap = channelWithdrawService.getMap(
        new QueryWrapper<ChannelWithdraw>()
            .select("IFNULL(sum(money) ,0) as withdrawAmt")
            .lambda().lt(ChannelWithdraw::getCreateTime, DateUtils.addDays(bizDay, 1))
            .eq(ChannelWithdraw::getStatus, ChannelWithdrawStatusEnum.FINISHED));
    Map<String, Object> allAcctMoneyMap = channelService.getMap(
        new QueryWrapper<Channel>()
            .select("IFNULL(sum(money) ,0) as acctAmt"));
    if (null != withdrawMap) {
      sb.append("累计提现：").append(
              new BigDecimal(Integer.valueOf(String.valueOf(allWithdrawMap.get("withdrawAmt")))).divide(
                  new BigDecimal(100), 2, RoundingMode.DOWN))
          .append("元，待提现：").append(
              new BigDecimal(Integer.valueOf(String.valueOf(allAcctMoneyMap.get("acctAmt")))).divide(
                  new BigDecimal(100), 2, RoundingMode.DOWN))
          .append("元，当日：").append(
              new BigDecimal(Integer.valueOf(String.valueOf(withdrawMap.get("withdrawAmt")))).divide(
                  new BigDecimal(100), 2, RoundingMode.DOWN)).append("元\n");
    }

    int exCnt = userExchangeOrderService.count(new LambdaQueryWrapper<UserExchangeOrder>()
        .ge(UserExchangeOrder::getCreatedTime, bizDay)
        .lt(UserExchangeOrder::getCreatedTime, DateUtils.addDays(bizDay, 1)));
    int allExCnt = userExchangeOrderService.count(new LambdaQueryWrapper<UserExchangeOrder>()
        .lt(UserExchangeOrder::getCreatedTime, DateUtils.addDays(bizDay, 1)));
    sb.append("累计兑换订单：").append(allExCnt).append("个，当日：").append(exCnt).append("个\n");

    Map<String, Object> deliverMap = userCoinLogService.getMap(new QueryWrapper<UserCoinLog>()
        .select("IFNULL(sum(log_money) ,0) as deliverAmt")
        .lambda().eq(UserCoinLog::getType, CoinLogTypeEnum.PRIZE)
        .ge(UserCoinLog::getCreatedTime, bizDay)
        .lt(UserCoinLog::getCreatedTime, DateUtils.addDays(bizDay, 1)));
    Map<String, Object> allDeliverMap = userCoinLogService.getMap(new QueryWrapper<UserCoinLog>()
        .select("IFNULL(sum(log_money) ,0) as deliverAmt")
        .lambda().eq(UserCoinLog::getType, CoinLogTypeEnum.PRIZE)
        .lt(UserCoinLog::getCreatedTime, DateUtils.addDays(bizDay, 1)));
    if (null != deliverMap) {
      sb.append("累计派发盲豆：").append(Integer.valueOf(String.valueOf(allDeliverMap.get("deliverAmt"))))
          .append("颗，当日：").append(Integer.valueOf(String.valueOf(deliverMap.get("deliverAmt"))))
          .append("颗\n");
    }

    Map<String, Object> exchangeMap = userCoinLogService.getMap(new QueryWrapper<UserCoinLog>()
        .select("IFNULL(sum(log_money) ,0) as exchangeAmt")
        .lambda().eq(UserCoinLog::getType, CoinLogTypeEnum.EXCHANGE)
        .ge(UserCoinLog::getCreatedTime, bizDay)
        .lt(UserCoinLog::getCreatedTime, DateUtils.addDays(bizDay, 1)));
    Map<String, Object> allExchangeMap = userCoinLogService.getMap(new QueryWrapper<UserCoinLog>()
        .select("IFNULL(sum(log_money) ,0) as exchangeAmt")
        .lambda().eq(UserCoinLog::getType, CoinLogTypeEnum.EXCHANGE)
        .lt(UserCoinLog::getCreatedTime, DateUtils.addDays(bizDay, 1)));
    if (null != withdrawMap) {
      sb.append("累计兑换盲豆：").append(0 - Integer.valueOf(String.valueOf(allExchangeMap.get("exchangeAmt"))))
          .append("颗，当日：").append(0 - Integer.valueOf(String.valueOf(exchangeMap.get("exchangeAmt"))))
          .append("颗\n");
    }
    sb.append("===================\n");
    sb.append(sbDetail);
    LogUtil.info(logger, "通知发送结果：" + WebhookService.sendBizData(sb.toString()));
    LogUtil.info(logger, sb.toString());
    LogUtil.info(logger, "...日统计任务结束..." );
  }
}
