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 DeptDataReportTask 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 deptBroadcast = systemConfigItemService.getSystemConfigItemValueByCode("DEPT_BROADCAST");

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

        // 周报：当周首个工作日触发
        if (FirstMondayChecker.isWeek(today, calendarService) || deptList.contains(1)) {
            broadcastService.sendDeptData(10);
        }

        // 月报：当月首个工作日触发
        if (FirstMondayChecker.isMonth(today, calendarService) || deptList.contains(2)) {
            broadcastService.sendDeptData(20);
        }

        // 季报：季度首月首个工作日触发
        if (FirstMondayChecker.isQuarter(today, calendarService) || deptList.contains(3)) {
            broadcastService.sendDeptData(30);
        }

        // 半年报：1/7月首个工作日触发
        if (FirstMondayChecker.isHalfYear(today, calendarService) || deptList.contains(4)) {
            broadcastService.sendDeptData(40);
        }

        // 年报：当年1月首个工作日触发
        if (FirstMondayChecker.isYear(today, calendarService) || deptList.contains(5)) {
            broadcastService.sendDeptData(50);
        }
    }
}
