package com.eitc.quartz.task;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eitc.common.utils.spring.SpringUtils;
import com.eitc.patient.domain.SchedulingConfiguration;
import com.eitc.patient.domain.SchedulingDetails;
import com.eitc.patient.service.ISchedulingConfigurationService;
import com.eitc.patient.service.ISchedulingDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * schedulingConfigurationTask
 *
 * @author mtx
 * @date: 2024/05/28 16:16
 */
@Component("schedulingConfigurationTask")
@Slf4j
public class SchedulingConfigurationTask {

    private final ISchedulingConfigurationService schedulingConfigurationService = SpringUtils.getBean(ISchedulingConfigurationService.class);
    private final ISchedulingDetailsService schedulingDetailsService = SpringUtils.getBean(ISchedulingDetailsService.class);

    public void generateScheduling() {
        log.info("generateScheduling start");
        Calendar instance = Calendar.getInstance();
        int actualMaximum = instance.getActualMaximum(Calendar.DAY_OF_MONTH);

        List<SchedulingDetails> list = new ArrayList<>();
        List<SchedulingConfiguration> schedulingConfigurationList = schedulingConfigurationService.list();
        if (CollectionUtils.isEmpty(schedulingConfigurationList)) {
            return;
        }
        Map<String, List<SchedulingConfiguration>> listMap = schedulingConfigurationList.stream().collect(Collectors.groupingBy(SchedulingConfiguration::getDoctorId));
        for (String doctorId : listMap.keySet()) {
            Map<Integer, String> collect = listMap.get(doctorId).stream()
                    .collect(Collectors.toMap(SchedulingConfiguration::getWeekNum, SchedulingConfiguration::getWorkStatus));

            for (int day = 1; day <= actualMaximum; day++) {
                instance.set(Calendar.DAY_OF_MONTH, day);
                int week = instance.get(Calendar.DAY_OF_WEEK);

                SchedulingDetails sd = new SchedulingDetails();
                sd.setDoctorId(doctorId);
                sd.setWorkYear(instance.get(Calendar.YEAR));
                sd.setWorkMonth(instance.get(Calendar.MONTH) + 1);
                sd.setWorkDay(instance.get(Calendar.DAY_OF_MONTH));
                sd.setWorkDate(instance.getTime());
                sd.setWorkStatus(collect.get(week));
                list.add(sd);
            }
        }
        schedulingDetailsService.remove(Wrappers.<SchedulingDetails>lambdaQuery()
                .eq(SchedulingDetails::getWorkYear, instance.get(Calendar.YEAR))
                .eq(SchedulingDetails::getWorkMonth, instance.get(Calendar.MONTH) + 1));
        schedulingDetailsService.saveBatch(list);
    }
}
