package com.ktg.quartz.task;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.iscs.domain.IsMailNotifyConfig;
import com.ktg.iscs.domain.IsMaterialsCabinet;
import com.ktg.iscs.domain.IsMaterialsCheckPlan;
import com.ktg.iscs.domain.dto.checkPlan.AddCheckPlanDTO;
import com.ktg.iscs.service.IIsMailNotifyConfigService;
import com.ktg.iscs.service.IIsMaterialsCabinetService;
import com.ktg.iscs.service.IIsMaterialsCheckPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时发送检查物资柜提醒邮件
 *
 * @author CGJ
 */
@Slf4j
@Component("checkPlanTask")
public class CheckPlanTask {

    @Autowired
    private IIsMailNotifyConfigService isMailNotifyConfigService;
    @Autowired
    private IIsMaterialsCheckPlanService iIsMaterialsCheckPlanService;
    @Autowired
    private IIsMaterialsCabinetService iIsMaterialsCabinetService;


    public void addCheckPlan(String templateCode) {
        if (StringUtils.isNotBlank(templateCode)) {
            // 1.查询当前检查计划模板
            IsMailNotifyConfig notifyConfig = isMailNotifyConfigService.getOne(Wrappers.<IsMailNotifyConfig>lambdaQuery()
                    .eq(IsMailNotifyConfig::getTemplateCode, templateCode));
            // 2.如果检查计划存在
            if (notifyConfig != null && "1".equals(notifyConfig.getStartStatus()) && "1".equals(notifyConfig.getStatus())) {
                // 3.获取当前设定的检查参数（频率&日期）
                String planFrequency = notifyConfig.getPlanFrequency();
                String planDate = notifyConfig.getPlanDate();
                if ("月".equals(planFrequency)) {
                    // 获取当前日期
                    LocalDate currentDate = LocalDate.now();
                    // 获取当前年月
                    YearMonth currentYearMonth = YearMonth.from(currentDate);
                    // 获取当月的最大天数
                    int maxDay = currentYearMonth.lengthOfMonth();
                    // 4.如果当前的频率是月为单位
                    planDate = StringUtils.isBlank(planDate) ? "01" : planDate;
                    planDate = Integer.parseInt(planDate) > maxDay ? String.valueOf(maxDay) : planDate;
                    // 4.1获取当前年月
                    String monthPlanDate = currentYearMonth + "-" + planDate;
                    checkAndAddPlan(monthPlanDate, notifyConfig);
                } else if ("周".equals(planFrequency)) {
                    // 5.如果当前频率是周，获取包括今天的最近一次周内的日期
                    String weekDayDate = DateUtils.getWeekDayDate(Integer.parseInt(planDate));
                    checkAndAddPlan(weekDayDate, notifyConfig);
                }
            }
        }
    }

    private void checkAndAddPlan(String planDate, IsMailNotifyConfig notifyConfig) {
        // 4.2检查当前是否已经生成过计划，如果没有则生成一下
        List<IsMaterialsCheckPlan> checkPlans = iIsMaterialsCheckPlanService.list(Wrappers.<IsMaterialsCheckPlan>lambdaQuery()
                .eq(IsMaterialsCheckPlan::getPlanDate, planDate));
        if (checkPlans.isEmpty()) {
            AddCheckPlanDTO addCheckPlanDTO = new AddCheckPlanDTO();
            addCheckPlanDTO.setPlanName("物资检查计划" + planDate);
            addCheckPlanDTO.setWorkstationId(null);
            addCheckPlanDTO.setPlanDate(DateUtils.toDate(LocalDate.parse(planDate)));
            addCheckPlanDTO.setCheckUserId(notifyConfig.getCheckUserId());
            List<IsMaterialsCabinet> cabinets = iIsMaterialsCabinetService.list();
            if (!cabinets.isEmpty()) {
                List<Long> cabinetIds = cabinets.stream().map(IsMaterialsCabinet::getCabinetId).collect(Collectors.toList());
                addCheckPlanDTO.setCabinetIds(cabinetIds);
                iIsMaterialsCheckPlanService.insertIsMaterialsCheckPlan(addCheckPlanDTO);
            }
        }
    }

}
