package cn.pluss.platform.job;

import cn.hutool.core.date.DateUtil;
import cn.pluss.platform.bill.MemberTransStatisticsService;
import cn.pluss.platform.bill.MerchantBillStatisticsService;
import cn.pluss.platform.merchantOrder.MerchantOrderStatisticsService;
import cn.pluss.platform.wx.WxTalkService;
import cn.pluss.platform.wx.impl.WxTalkServiceImpl;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Calendar;
import java.util.Date;

/**
 * 账单相关定时任务
 * @author DJH
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class MerchBillJob {

    @Setter(onMethod_ = {@Autowired})
    private MerchantBillStatisticsService billStatisticsService;

    @Setter(onMethod_ = {@Autowired})
    private MemberTransStatisticsService memberTransStatisticsService;

    @Autowired
    private MerchantOrderStatisticsService mosService;

    @Autowired
    private WxTalkService wxTalkService;

    /**
     * 前一天的数据播报
     */
    @Scheduled(cron = "0 0 10 * * ? ")
    public void setWxTalkDailyData() {
        try {
            wxTalkService.sendStatisticData();
        } catch (Exception e) {
            wxTalkService.sendTextMsg("账单统计失败(- -)!!!", WxTalkServiceImpl.WX_GO_PUBLIC_TALK_URL);
        }
    }

    /**
     * 每天统计商户前一天的账单
     */
    @Scheduled(cron = "10 0 0 * * ? ")
    public void processDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_WEEK, -1);
        Date date = calendar.getTime();
        String format = DateUtil.format(date, "yyyy-MM-dd");

        billStatisticsService.saveDaysBill(format);
    }

    /**
     * 每天统计商户前一天的会员账单
     */
    @Scheduled(cron = "10 0 0 * * ? ")
    public void processMemberDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_WEEK, -1);
        Date date = calendar.getTime();
        String format = DateUtil.format(date, "yyyy-MM-dd");

        memberTransStatisticsService.saveDaysBill(format);
    }

    /**
     * 统计月账单
     */
    @Scheduled(cron = "0 0 0 * * ? ")
    public void processMonthOrderStatistics() {
        mosService.untilLastMonth();
    }
}
