package cn.iocoder.yudao.module.system.job;

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlyInfoDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.NursingPlanDO;
import cn.iocoder.yudao.module.system.service.biz.ElderlyInfoService;
import cn.iocoder.yudao.module.system.service.nursing.NursingLogService;
import cn.iocoder.yudao.module.system.service.nursing.NursingPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

/**
 * 每天生成护理日志
 */
@Component
@Slf4j
public class NurseLogSyncJob implements JobHandler {


    @Resource
    private NursingLogService nursingLogService;
    @Resource
    private ElderlyInfoService elderlyInfoService;
    @Resource
    private NursingPlanService nursingPlanService;

    @Override
    @TenantIgnore
    public String execute(String param) throws Exception {
        log.info("护理日志记录定时器开始执行..........................");
        List<NursingPlanDO> nursingPlanList = nursingPlanService.selectAll();

        Map<Long, List<NursingPlanDO>> groupMap = nursingPlanList.stream()
                .collect(Collectors.groupingBy(
                        NursingPlanDO::getElderId, // 根据长者ID分组
                        Collectors.collectingAndThen(
                                Collectors.toList(), // 先收集成列表
                                list -> list.stream() // 然后对流进行操作
                                        .sorted(Comparator.comparing(NursingPlanDO::getEffectiveDate)) // 根据时间排序
                                        .collect(Collectors.toList()) // 收集回列表
                        )
                ));

        for (Long elderId : groupMap.keySet()) {
            List<NursingPlanDO> nursingPlans = groupMap.get(elderId);
            NursingPlanDO nursingPlanDO = nursingPlans.stream().findFirst().get();
            ElderlyInfoDO elderlyInfo = elderlyInfoService.selectByIdTenantIgnore(elderId);
            LocalDate localDate = nursingPlanDO.getEffectiveDate().plusDays(1);  //当天的已经生成，从后面一天开始生成
            if (elderlyInfo != null && elderlyInfo.getInStatus() == 1 && LocalDate.now().isAfter(localDate)) {
                //创建护理日志
                nursingLogService.createNursingLog(nursingPlanDO);
            }
        }
        log.info("护理日志记录定时器执行结束..........................");
        return null;
    }
}
