package com.storlead.sales.task.broadcast;


import cn.hutool.core.util.StrUtil;
import com.storlead.sales.service.BroadcastDataService;
import com.storlead.sales.service.customer.StorleadCalendarService;
import com.storlead.system.service.SystemConfigItemService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/***
 * @Description: 分公司总经理数据报表定时任务
 * @Param:
 * @return:
 * @Author: LPK
 * @Date: 2025/12/8 9:27
 */
@Slf4j
@Component
@NoArgsConstructor
@DisallowConcurrentExecution
public class CeoDataReportTask implements Job {

    @Resource
    private StorleadCalendarService calendarService;
    @Resource
    private BroadcastDataService broadcastService;

    @Resource
    private SystemConfigItemService systemConfigItemService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        LocalDate today = LocalDate.now();


        String subCompanyBroadcast = systemConfigItemService.getSystemConfigItemValueByCode("SUB_COMPANY_BROADCAST");

        if (StrUtil.isBlank(subCompanyBroadcast)) {
            return;
        }
        List<Integer> subCompanyList = Arrays.stream(subCompanyBroadcast.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        // 周：本周首个工作日
        if (FirstMondayChecker.isWeek(today, calendarService) || subCompanyList.contains(1)) {
            broadcastService.sendCeoData(10);
        }

        // 月：当月首个工作日
        if (FirstMondayChecker.isMonth(today, calendarService) || subCompanyList.contains(2)) {
            broadcastService.sendCeoData(20);
        }

        // 季度：当前季度首月的首个工作日
        if (FirstMondayChecker.isQuarter(today, calendarService) || subCompanyList.contains(3)) {
            broadcastService.sendCeoData(30);
        }

        // 半年度：当前半年的首月（1月或7月）的首个工作日
        if (FirstMondayChecker.isHalfYear(today, calendarService) || subCompanyList.contains(4)) {
            broadcastService.sendCeoData(40);
        }

        // 年度：当年1月的首个工作日
        if (FirstMondayChecker.isYear(today, calendarService) || subCompanyList.contains(5)) {
            broadcastService.sendCeoData(50);
        }
    }
}
