package com.bzd.system.service.dtp;

import com.bzd.common.annotation.Excel;
import com.bzd.common.config.dao.DaoBase;
import com.bzd.common.config.dao.DaoSupport;
import com.bzd.common.config.dao.PageData;
import com.bzd.common.constant.ScheduleConstants;
import com.bzd.common.exception.job.TaskException;
import com.bzd.common.utils.DateUtils;
import com.bzd.common.utils.StringUtils;
import com.bzd.common.utils.uuid.IdUtils;
import com.bzd.common.utils.uuid.SnowflakeIdGenerator;
import com.bzd.quartz.domain.SysJob;
import com.bzd.quartz.mapper.SysJobMapper;
import com.bzd.quartz.service.ISysJobService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.quartz.CronExpression;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;

import static com.bzd.common.utils.ShiroUtils.getSysUser;


/**
*
* 随访SOP表 service
* @author wsp
* @since 2024-10-15
*/

@Service
public class SDtpYypzFollowUpSopService {

    @Autowired
    private DaoBase dao;
    @Autowired
    ISysJobService jobService;

    @Resource(name = "daoSupport")
    private DaoSupport daoSupport;

    @Autowired
    private SysJobMapper jobMapper;
    @Transactional(rollbackFor = Exception.class)
    public Integer addSDtpYypzFollowUpSop(PageData pd) throws Exception {
        Integer templateId = IdUtils.get10randomNumber(); // 生成7位随机数
        Object nodesDataList = pd.get("nodesData");
        List<PageData> nodeList = new ArrayList<>();
        List<PageData> addList = new ArrayList<>();
        Object drugListObj = pd.get("applicableDrug"); // 获取药品信息列表
        String storeId = getSysUser().getDeptId().toString(); // 门店id
        String businessBelonging = (String) pd.get("businessBelonging");

        // 收集所有药品编码
        List<String> productCodes = new ArrayList<>();
        if (StringUtils.isNotNull(drugListObj)) {
            ObjectMapper objectMapper = new ObjectMapper();
            List<Map<String, Object>> rowsdrugList = objectMapper.readValue(drugListObj.toString(), List.class);

            // 将药品编码加入集合
            for (Map<String, Object> lxr : rowsdrugList) {
                productCodes.add((String) lxr.get("productCode"));
            }

            // 如果有药品编码，进行批量查询校验
            if (!productCodes.isEmpty()) {
                PageData queryPd = new PageData();
                queryPd.put("storeId", storeId);
                queryPd.put("businessBelonging", businessBelonging);
                queryPd.put("productCodes", productCodes); // 设置药品编码列表
                queryPd.put("status", 2); // 模版状态 不等于2 的 不是禁用状态的

                List<PageData> existingTemplates = (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.getTemplateNodesByMBSIn", queryPd);
                Set<String> existingProductCodes = existingTemplates.stream()
                        .map(pdItem -> (String) pdItem.get("productCode"))
                        .collect(Collectors.toSet());

                // 检查是否有重复项
                for (Map<String, Object> lxr : rowsdrugList) {
                    String productCode = (String) lxr.get("productCode");
                    if (existingProductCodes.contains(productCode)) {
                        throw new RuntimeException("药品:" + lxr.get("productName") + "-" + productCode + " 已经存在模板，请先禁用该模板");
                    }
                }

                // 构建要添加的数据列表
                for (Map<String, Object> lxr : rowsdrugList) {
                    PageData pageData = new PageData();
                    pageData.put("storeId", getSysUser().getDeptId());
                    pageData.put("createTime", DateUtils.getTime());
                    pageData.put("productName", lxr.get("productName"));
                    pageData.put("productCode", lxr.get("productCode"));
                    pageData.put("specification", lxr.get("specification"));
                    pageData.put("templateId", templateId);
                    pageData.put("templateName", pd.get("templateName"));
                    addList.add(pageData);
                }

                final HashMap<String, Object> addMap = new HashMap<>();
                addMap.put("dataList", addList);
                int resultDrug = dao.executeBatch("SDtpYypzFollowUpSopMapper.batchAddTemplateDrugDynamic", addMap);
                if (resultDrug <= 0) {
                    throw new RuntimeException("药品信息插入失败");
                }
            }
        }

        // 处理节点数据部分
        if (StringUtils.isNotNull(nodesDataList)) {
            ObjectMapper objectMapper = new ObjectMapper();
            List<Map<String, Object>> nodesList = objectMapper.readValue(nodesDataList.toString(), List.class);
            for (int i = 0; i < nodesList.size(); i++) {
                Map<String, Object> lxr = nodesList.get(i);
                PageData pageData = new PageData();

                String nodeName = "节点" + (i + 1); // 节点名称从节点1开始
                String nodeCode = String.valueOf(i + 1); // 编码从1开始
                pageData.put("creator", getSysUser().getLoginName());
                pageData.put("createTime", DateUtils.getTime());
                pageData.put("templateId", templateId);
                pageData.put("nodeName", nodeName);
                pageData.put("nodeCode", nodeCode);
                pageData.put("activateStructures", lxr.get("activateStructures"));
                pageData.put("activateWhichDay", lxr.get("activateWhichDay"));
                pageData.put("activateNodeRule", lxr.get("activateNodeRule"));
                pageData.put("createTaskStructures", lxr.get("createTaskStructures"));
                pageData.put("createTaskWhen", lxr.get("createTaskWhen"));
                pageData.put("createTaskEvery", lxr.get("createTaskEvery"));
                pageData.put("createTaskDi", lxr.get("createTaskDi"));
                pageData.put("createTaskTriggerValue", lxr.get("createTaskTriggerValue"));
                pageData.put("createTaskExecutionTimes", lxr.get("createTaskExecutionTimes"));
                pageData.put("taskActionMode", lxr.get("taskActionMode"));
                pageData.put("taskActionTaskType", lxr.get("taskActionTaskType"));
                pageData.put("taskActionRole", lxr.get("taskActionRole"));
                pageData.put("generationDaysAfter", lxr.get("generationDaysAfter"));
                pageData.put("generationHMS", lxr.get("generationHMS"));
                pageData.put("followUpSubject", lxr.get("followUpSubject"));
                pageData.put("taskValidity", lxr.get("taskValidity"));
                pageData.put("taskMaterial", lxr.get("taskMaterial"));
                pageData.put("deliveryChannel", lxr.get("deliveryChannel"));
                String smsId= (String) lxr.get("smsId");
                String useForm= (String)  lxr.get("useForm");
                if(StringUtils.isNotEmpty(smsId)){
                    pageData.put("smsId", lxr.get("smsId"));
                }
                if(StringUtils.isNotEmpty(useForm)){
                    pageData.put("useForm", lxr.get("useForm"));
                }
                pageData.put("status", 0); // 状态: 0已创建 1启用，2禁用 默认为已创建0
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> filtersData = (List<Map<String, Object>>) lxr.get("filtersData");
                if (filtersData != null && !filtersData.isEmpty()) {
                    String filtersDataJson = objectMapper.writeValueAsString(filtersData);
                    pageData.put("filterCondition", filtersDataJson);
                }

                int node1 = dao.executeBatch("SDtpYypzFollowUpSopMapper.insertNodeConfig", pageData);
                nodeList.add(pageData);
                if (node1 <= 0) {
                    throw new RuntimeException("节点配置插入失败");
                }
            }
        }

        pd.put("createdTime", DateUtils.getTime()); // 创建时间
        pd.put("createdBy", getSysUser().getLoginName()); // 创建人
        pd.put("storeName", getSysUser().getDept().getDeptName()); // 门店名称
        pd.put("status", 0); // 状态: 0已创建 1启用，2禁用 默认为已创建0
        pd.put("templateId", templateId);
        int result = daoSupport.update("SDtpYypzFollowUpSopMapper.addSDtpYypzFollowUpSop", pd);
        if (result <= 0) {
            throw new RuntimeException("主记录插入失败");
        }
        return result;
    }

    public List<PageData> findSDtpYypzFollowUpSopList(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectSDtpYypzFollowUpSopList", pd);
    }
    public List<PageData> selectDrugsByTemplateId(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectDrugsByTemplateId", pd);
    }
    public List<PageData> selectNodeConfigByTemplateId(PageData pd) throws Exception{
        List<PageData> nodeList= (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectNodeConfigByTemplateId", pd);
        // 遍历 nodeList 并处理每个节点的 filterCondition 字段
                for (PageData node : nodeList) {
                Object filterConditionBlob = node.get("filterCondition");
                if (filterConditionBlob instanceof Blob) {
                    try {
                        Blob blob = (Blob) filterConditionBlob;
                        String jsonString = IOUtils.toString(blob.getBinaryStream(), StandardCharsets.UTF_8);
                        // 将 JSON 字符串解析为 Map 或其他合适的对象类型
                        // 将解析后的对象设置回 PageData
                        node.put("filterCondition", jsonString);
                    } catch (IOException | SQLException e) {
                        // 处理异常
                        System.out.println("处理 filterCondition BLOB 数据失败: "+ e);
                        node.put("filterCondition", null); // 或者设置默认值
                    }
                }

             }
          return nodeList;
    }
    public PageData selectTemplateById(PageData pd) throws Exception{
        PageData pdObj= (PageData) daoSupport.findForObject("SDtpYypzFollowUpSopMapper.selectTemplateById", pd);
        return pdObj ;
    }

    public Integer SDtpYypzFollowUpSopRemove(PageData pd)throws Exception {
        return daoSupport.delete("SDtpYypzFollowUpSopMapper.SDtpYypzFollowUpSopRemove", pd);
    }

    public Integer updateSDtpYypzFollowUpSop(PageData pd)throws Exception {
        PageData pda =new PageData();
        Integer statusFla=null;
        String switchFlag = (String) pd.get("switchFlag");
        if(StringUtils.isNotEmpty(switchFlag)){
            if(switchFlag.equals("已创建")){
                statusFla=0;
            }
            if(switchFlag.equals("启用中")){
                statusFla=1;
            }
            if(switchFlag.equals("禁用中")){
                statusFla=2;
            }
        }
        Object nodesDataList = pd.get("nodesData");
        Integer templateId =null;
        // 获取 templateId 并进行类型转换
        Object planIdObj = pd.get("templateId");
        if (planIdObj instanceof String) {
            // 使用 NumberUtils 进行安全转换
            templateId = NumberUtils.toInt((String) planIdObj);
        } else if (planIdObj instanceof Integer) {
            templateId = (Integer) planIdObj;
        } else if (planIdObj instanceof Long) {
            Long longtemplateId = (Long) planIdObj;
            if (longtemplateId <= Integer.MAX_VALUE && longtemplateId >= Integer.MIN_VALUE) {
                templateId = longtemplateId.intValue();
            } else {
                throw new IllegalArgumentException("templateId exceeds Integer range: " + longtemplateId);
            }
        } else {
            throw new IllegalArgumentException("Unsupported type for templateId: " + planIdObj.getClass());
        }
        if (StringUtils.isNotNull(templateId)) {
            pda.put("templateId", templateId);
        }else {
            throw new RuntimeException("模板ID不能为空");
        }
        List<PageData> nodeList = new ArrayList<>();
        List<PageData> addList = new ArrayList<>();
        Object drugList = pd.get("applicableDrug");//获取药品信息列表
        String storeId = getSysUser().getDeptId().toString(); // 门店id
        String businessBelonging = (String) pd.get("businessBelonging");
        try {
            //更新药品信息
        if (StringUtils.isNotNull(drugList)) {
            // 将 JSON 字符串转换为 List<Map<String, Object>>
            ObjectMapper objectMapper = new ObjectMapper();
            List<Map<String, Object>> rowsdrugList = objectMapper.readValue(drugList.toString(), List.class);
          // 将药品编码加入集合
            List<PageData> ylist= (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectDrugsByTemplateId", pda);
            if (ylist.size() > 0) {
                int a=  daoSupport.update("SDtpYypzFollowUpSopMapper.deleteTemplateDrugByTemplateId", pda);
                if (a <= 0) {
                    throw new RuntimeException("药品更新删除失败");
                }
            }

            // 遍历列表并调用插入数据接口
            if (rowsdrugList.size() > 0) {
                for (Map<String, Object> lxr : rowsdrugList) {
                    PageData pageData = new PageData();
                    pageData.put("storeId", getSysUser().getDeptId());
                    pageData.put("createTime", DateUtils.getTime());
                    pageData.put("productName", lxr.get("productName"));
                    pageData.put("productCode", lxr.get("productCode"));
                    pageData.put("specification", lxr.get("specification"));
                    pageData.put("templateId", templateId);
                    pageData.put("templateName", pd.get("templateName"));
                    addList.add(pageData);
                }
                final HashMap<String, Object> addMap = new HashMap<String, Object>();
                addMap.put("dataList", addList);
                int resultDrug= dao.executeBatch("SDtpYypzFollowUpSopMapper.batchAddTemplateDrugDynamic", addMap);
                if (resultDrug <= 0) {
                    throw new RuntimeException("药品信息插入失败");
                }
            }
            }


            //修改节点信息
        if (StringUtils.isNotNull(nodesDataList)) {
                List<PageData> ylist= (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectNodeConfigByTemplateId", pda);
                if (ylist.size() > 0) {
                    int b=  daoSupport.update("SDtpYypzFollowUpSopMapper.deleteNodeConfigByTemplateId", pda);
                    if (b <= 0) {
                        throw new RuntimeException("节点信息更新删除失败");
                    }
                }
                // 将 JSON 字符串转换为 List<Map<String, Object>>
                ObjectMapper objectMapper = new ObjectMapper();
                List<Map<String, Object>> nodesList = objectMapper.readValue(nodesDataList.toString(), List.class);
                // 遍历列表并调用插入数据接口
                if (nodesList.size() > 0) {
                    for (int i = 0; i < nodesList.size(); i++) {
                        Map<String, Object> lxr = nodesList.get(i);
                        PageData pageData = new PageData();

                        // 自动生成节点名称和编码
                        String nodeName = "节点" + (i + 1); // 节点名称从节点1开始
                        String nodeCode = String.valueOf(i + 1); // 编码从1开始
                        pageData.put("nodeName", nodeName);
                        pageData.put("nodeCode", nodeCode);
                        pageData.put("templateId", templateId);
                        pageData.put("activateStructures", lxr.get("activateStructures"));
                        pageData.put("activateWhichDay", lxr.get("activateWhichDay"));
                        pageData.put("activateNodeRule", lxr.get("activateNodeRule"));
                        pageData.put("createTaskStructures", lxr.get("createTaskStructures"));
                        pageData.put("createTaskWhen", lxr.get("createTaskWhen"));
                        pageData.put("createTaskEvery", lxr.get("createTaskEvery"));
                        pageData.put("createTaskDi", lxr.get("createTaskDi"));
                        pageData.put("createTaskTriggerValue", lxr.get("createTaskTriggerValue"));
                        pageData.put("createTaskExecutionTimes", lxr.get("createTaskExecutionTimes"));
                        pageData.put("taskActionMode", lxr.get("taskActionMode"));
                        pageData.put("taskActionTaskType", lxr.get("taskActionTaskType"));
                        pageData.put("taskActionRole", lxr.get("taskActionRole"));
                        pageData.put("generationDaysAfter", lxr.get("generationDaysAfter"));
                        pageData.put("generationHMS", lxr.get("generationHMS"));
                        pageData.put("followUpSubject", lxr.get("followUpSubject"));
                        pageData.put("taskValidity", lxr.get("taskValidity"));
                        pageData.put("taskMaterial", lxr.get("taskMaterial"));
                        pageData.put("deliveryChannel", lxr.get("deliveryChannel"));
                        String smsId= (String) lxr.get("smsId");
                        String useForm= (String)  lxr.get("useForm");
                        if(StringUtils.isNotEmpty(smsId)){
                            pageData.put("smsId", lxr.get("smsId"));
                        }
                        if(StringUtils.isNotEmpty(useForm)){
                            pageData.put("useForm", lxr.get("useForm"));
                        }
                        if(StringUtils.isNotEmpty(switchFlag)){
                            pageData.put("status",statusFla);//状态: 0已创建 1启用，2禁用 默认为已创建0
                        }else{
                            pageData.put("status",0);//状态: 0已创建 1启用，2禁用 默认为已创建0
                        }

                        // 处理 过滤条件 filtersData
                        @SuppressWarnings("unchecked")
                        List<Map<String, Object>> filtersData = (List<Map<String, Object>>) lxr.get("filtersData");
                        if (filtersData != null && !filtersData.isEmpty()) {
                            String filtersDataJson = objectMapper.writeValueAsString(filtersData);
                            pageData.put("filterCondition", filtersDataJson);
                        }
                        System.out.println("pageData:"+pageData);
                        int node1= dao.executeBatch("SDtpYypzFollowUpSopMapper.insertNodeConfig", pageData);
                        nodeList.add(pageData);
                        if (node1 <= 0) {
                            throw new RuntimeException("节点配置插入失败");
                        }
                    }
                    //                final HashMap<String, Object> addMap = new HashMap<String, Object>();
                    //                addMap.put("dataList", nodeList);
                    //批量插入暂时不用
                    //                int node= dao.executeBatch("SDtpYypzFollowUpSopMapper.batchAddNodeConfig", addMap);
                    //                if (node <= 0) {
                    //                    throw new RuntimeException("节点配置插入失败");
                    //                }
                }

        }

        } catch (Exception e) {
        e.printStackTrace();
        }   //修改模版信息
        pd.put("updatedBy",getSysUser().getLoginName());
        pd.put("updatedTime",DateUtils.getTime());
        pd.put("storeId",getSysUser().getDeptId().toString());//门店id
        pd.put("storeName",getSysUser().getDept().getDeptName());//门店名称
        if(StringUtils.isNotEmpty(switchFlag)){
            pd.put("status",statusFla);//状态: 0已创建 1启用，2禁用 默认为已创建0
        }else{
            pd.put("status",0);//状态: 0已创建 1启用，2禁用 默认为已创建0
        }
        int result =  daoSupport.update("SDtpYypzFollowUpSopMapper.updateSDtpYypzFollowUpSop", pd);
        if (result <= 0) {
            throw new RuntimeException("模版修改失败");
        }
        return result;

    }

    public Integer updateSopStatusByTemplateId(PageData pd)throws Exception {

        pd.put("updatedBy",getSysUser().getLoginName());
        pd.put("updatedTime",DateUtils.getTime());
        int b=0;
       int a=  daoSupport.update("SDtpYypzFollowUpSopMapper.updateSopStatusByTemplateId", pd);
       if(a>0){
           b=  daoSupport.update("SDtpYypzFollowUpSopMapper.updateNodeconfigStatusByTemplateId", pd);
       }
        System.out.println("a:"+a+"b:"+b);
       if(a>0 && b>0){
           return 2;
       }else{
           return 0;
       }
   }
    /**
     * 根据创建时间和激活天数生成 Cron 表达式。
     *
     * @param createdTime   创建计划的时间字符串，格式为 "yyyy-MM-dd HH:mm:ss"
     * @param activateWhichDay 激活节点在创建后的第几天
     * @return 生成的 Cron 表达式
     */
    private static final SimpleDateFormat SDF_DATE_ONLY = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
    /**1触发任务主入口*/
    public void createTrigger(List<PageData> PlanList,List<PageData> TaskList) throws Exception {
    for (PageData pd : PlanList) {
        PageData pd1 = new PageData();
        pd1.put("templateId", pd.get("PlanTemplateId"));
        List<PageData> nodeList = (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectNodeConfigByTemplateId", pd1); // 根据模版id 获取节点配置 templateId
        System.out.println("执行mapper方法:selectNodeConfigByTemplateId,return:" + nodeList.size());
        if (nodeList.size() > 0) {
            for (PageData node : nodeList) {
                String activateStructures = (String) node.get("activateStructures"); // 激活节点 激活节点(按) 创建计划 其他方式
                int activateWhichDay = (int) node.get("activateWhichDay"); // 第几天激活
                String activateNodeRule = (String) node.get("activateNodeRule"); // 单次节点：只执行一次 周期节点：按周期规则执行
                String createdTime = DateUtils.getTime(); // 计划创建时间 为当前时间
                System.out.println("计划创建时间createdTime==:" + createdTime);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date createdDate;
                try {
                    createdDate = sdf.parse(createdTime);
                    // 确保所有参数都是正确的类型，并且进行必要的转换 productCode templateId
                    String mdmCode = (String) pd.get("PlanProductCode");
                    String storeId = (String) pd.get("storeId");
                    String patientId = (String) pd.get("patientId");
                    String templateId =(String) node.get("templateId");
                    Integer planId = (Integer) pd.get("planId");

                    if ("创建计划".equals(activateStructures)) {
                        // 计算激活计划的时间
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(createdDate);
                        calendar.add(Calendar.DAY_OF_MONTH, activateWhichDay); // 根据 activateWhichDay 来决定激活计划的时间
                        Date generateTaskTime = calendar.getTime();
                        // 创建生成激活计划的任务
                        pd.put("action", "execute");
                        SysJob job2 = createSysJobPlan(pd, mdmCode, storeId, patientId, templateId, planId,activateWhichDay,generateTaskTime);
                       int jb=   jobService.insertJob2(job2);
                        for (PageData task : TaskList) {
                            task.put("JHTime",job2.getLastTaskExecutionTime());
                            task.put("businessBelonging",pd.get("taskTheme"));
                            task.put("jobGroup",pd.get("taskTheme"));
                            task.put("jobName",pd.get("taskName"));
                            triggerTask(task);
                        }
                    }
                } catch (NumberFormatException e) {
                    // 处理转换失败的情况
                    System.err.println("转换 storeId, templateId 或 planId 时发生错误: " + e.getMessage());
                    // 可能需要采取进一步措施，如记录日志、通知管理员等
                }
            }
        }
    }
    }
    /**2 创建计划*/
    private SysJob createSysJobPlan(PageData pd, String mdmCode, String storeId, String patientId, String templateId, Integer planId,  int activateWhichDay, Date generateTaskTime) throws ParseException {
       String action = (String) pd.get("action");
        SysJob job = new SysJob();
        job.setJobGroup(pd.get("businessBelonging").toString()); // 任务组名
        job.setJobName(pd.get("planName").toString()); // 计划名称
        //triggerPLan(String mdmCode, String storeId, String patientId, String templateId, Integer planId)
        //triggerTask(String mdmCode, String storeId , String patientId , String templateId ,Integer planId ,Integer taskId)
        String invokeTarget = String.format("ryTask.triggerPLan('%s','%s', '%s', '%s', '%s', %d)",
                action,mdmCode, storeId, patientId, templateId, planId);
        job.setInvokeTarget(invokeTarget); // 设置调用目标字符串

        // 获取当前时间并加100秒
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime later = now.plusSeconds(100);
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        // 将时间格式化为字符串
        String generationHMS = later.format(formatter);

        // 设置 Cron 表达式
        String cronExpression = generateCronExpression4(generateTaskTime.toString(), activateWhichDay,generationHMS, false);
        String LastTaskTime=  zhuanhuaDirectly(cronExpression);
        job.setLastTaskExecutionTime(LastTaskTime);
        job.setCronExpression(cronExpression); // 设置 Cron 表达式
        job.setMisfirePolicy(ScheduleConstants.MISFIRE_FIRE_AND_PROCEED); // Cron 计划策略
        job.setConcurrent("1"); // 是否并发执行（0允许 1禁止）
        job.setStatus("0");
        job.setPlanId(planId.toString());
        job.setStoreId(storeId);
        job.setPatientId(patientId);
        return job;
    }
    /**3 创建任务*/
    private SysJob createSysJob(PageData pd, String mdmCode, String storeId, String patientId, String templateId, Integer planId, Integer taskId, int daysOffset, String generationHMS,String time) throws ParseException {
        SysJob job = new SysJob();
        job.setJobGroup(pd.get("jobGroup").toString()); //任务组名
        job.setJobName(pd.get("jobName").toString()); // 任务名称
        String action = (String) pd.get("action");
        String nodeFlag = (String) pd.get("nodeFlag");

        // 设置 Cron 表达式
        String cronExpression = generateCronExpression4(time, daysOffset, generationHMS,false);
        System.out.println("计划激活时间表达式cronExpression:"+cronExpression);
        String LastTaskTime=  zhuanhuaDirectly(cronExpression);
        // 把 lastTaskTimeStr 转成 Date 类型
        Date lastTaskTimeDate = SDF.parse(LastTaskTime);
        // 使用 SDF_DATE_ONLY 格式化 Date 对象，得到仅包含年月日的字符串
        String formattedDate = SDF_DATE_ONLY.format(lastTaskTimeDate);
        System.out.println("Formatted Date: " + formattedDate);
        String invokeTarget = String.format("ryTask.triggerTask('%s','%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
                formattedDate, nodeFlag, action, mdmCode, storeId, patientId, templateId, planId, taskId);
        job.setInvokeTarget(invokeTarget); // 设置调用目标字符串
        job.setLastTaskExecutionTime(LastTaskTime);
        job.setCronExpression(cronExpression); // 设置 Cron 表达式
        job.setMisfirePolicy(ScheduleConstants.MISFIRE_FIRE_AND_PROCEED); // Cron 计划策略
        job.setConcurrent("1"); // 是否并发执行（0允许 1禁止）
        job.setStatus("0");
        job.setPlanId(planId.toString());
        job.setStoreId(storeId);
        job.setPatientId(patientId);
        job.setTaskId(taskId.toString());
        return job;
    }

    /**1.2 创建任务生成定时任务分支*/
    public void triggerTask(PageData node) throws Exception {
        System.out.println("生成定时任务-执行定时任务有参方法:triggerTask" + node);

        try {
            String createTaskStructures = (String) node.get("createTaskStructures"); // 生成任务(按)
            String activateNodeRule = (String) node.get("activateNodeRule"); // 单次节点或周期节点
            LocalDateTime createdTime = (LocalDateTime) node.get("createdTime");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedCreatedTime = createdTime.format(formatter);
            String mdmCode = (String) node.get("productCode");
            String patientId = (String) node.get("patientId");
            String templateId = (String) node.get("templateId");
            Integer planId = (Integer) node.get("planId");
            Integer taskId = (Integer) node.get("taskId");
            String storeId = (String) node.get("storeId");
            // 根据不同的生成任务条件和节点规则调用相应的处理方法
            if ("时间条件".equals(createTaskStructures)) {
                if ("单次节点".equals(activateNodeRule)) {
                    handleSingleTimeNode(node, mdmCode, storeId, patientId, templateId, planId, taskId);
                } else if ("周期节点".equals(activateNodeRule)) {
                    handlePeriodicTimeNode(node, mdmCode, storeId, patientId, templateId, planId, taskId);
                }
            } else if ("事件条件".equals(createTaskStructures)) {
                if ("单次节点".equals(activateNodeRule)) {
                    handleSingleEventNode(node, mdmCode, storeId, patientId, templateId, planId, taskId);
                } else if ("周期节点".equals(activateNodeRule)) {
                    handlePeriodicEventNode(node, mdmCode, storeId, patientId, templateId, planId, taskId);
                }
            }
        } catch (NumberFormatException e) {
            System.err.println("转换 storeId, templateId 或 planId 时发生错误: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("处理节点配置时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
    /**1.2.1 时间条件+ 单次节点 ST ok*/
    private void handleSingleTimeNode(PageData node, String mdmCode, String storeId, String patientId, String templateId, Integer planId, Integer taskId) {
        node.put("nodeFlag", "ST");// 设置节点标志为ST 时间条件+单次节点
        int createTaskDi = (int) node.get("createTaskDi"); // 第几天生成任务
        int generationDaysAfter = (int) node.get("generationDaysAfter"); // 执行任务(生成后第几天执行任务)
        String generationHMS = (String) node.get("generationHMS"); // 执行任务时分秒 16:40:00
        int taskValidity = (int) node.get("taskValidity"); // 任务有效期天数 20
        Date createdDate;
        try {
            createdDate = SDF.parse(node.get("JHTime").toString());//获取激活计划的时间日期 作为第几天生成任务的基准时间
            // 通过计划激活时间 计算生成任务的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(createdDate);
            calendar.add(Calendar.DAY_OF_MONTH, createTaskDi); // 根据 createTaskDi 来决定生成任务的时间
            // 增加5秒
            calendar.add(Calendar.SECOND, 5);
            Date generateTaskTime = calendar.getTime();
            System.out.println("生成任务日期是：" + generateTaskTime);
            // 提取生成任务时间的时分秒部分
            String generationHMSSCRW = TIME_FORMAT.format(generateTaskTime);
            // 打印或使用生成的时分秒字符串
            System.out.println("Generated Time (HH:mm:ss): " + generationHMSSCRW);

            // 生成任务 定时器
            node.put("action", "create");
            SysJob job2 = createSysJob(node, mdmCode, storeId, patientId, templateId, planId, taskId, createTaskDi, generationHMSSCRW,generateTaskTime.toString());
            System.out.println("生成任务时间是：" + job2.getLastTaskExecutionTime());
            Date generateAdjustedDate = parseStringToDateWithMultipleFormats(job2.getLastTaskExecutionTime());
            job2.setExpiryDate(calculateExpiryDate(generateAdjustedDate, taskValidity));
            int STC=  jobService.insertJob2(job2);
            if (STC > 0) { // 确保第一个任务插入成功
               // 延迟1秒
                Thread.sleep(1000);
                createdDate = SDF.parse(job2.getLastTaskExecutionTime());//获取生成的时间日期 作为第几天后执行任务的基准时间
                // 通过生成任务的时间 计算执行任务的时间
                Calendar calendar3 = Calendar.getInstance();
                calendar3.setTime(createdDate);
                calendar3.add(Calendar.DAY_OF_MONTH, generationDaysAfter); // 根据 generationDaysAfter 生成后第几天执行任务 来决定执行任务的时间
                Date generateTaskTime3 = calendar3.getTime();

                // 执行任务 定时器
                node.put("action", "execute");
                SysJob job3 = createSysJob(node, mdmCode, storeId, patientId, templateId, planId, taskId, generationDaysAfter, generationHMS,generateTaskTime3.toString());
                Date ExCutDate = parseStringToDateWithMultipleFormats(job2.getLastTaskExecutionTime());
                job3.setExpiryDate(ExCutDate);
                int STA= jobService.insertJob2(job3);
                }


        } catch (ParseException e) {
            e.printStackTrace();
        } catch (TaskException e) {
            throw new RuntimeException(e);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    /**1.2.2 时间条件+ 周期节点 PT ok*/
    private void handlePeriodicTimeNode(PageData node, String mdmCode, String storeId, String patientId, String templateId, Integer planId, Integer taskId) {
        node.put("nodeFlag", "PT");// 设置节点标志为PT 时间条件+周期节点
        int createTaskEvery = (int) node.get("createTaskEvery"); // 每几天生成任务 假如每 2 天生成一次任务
        int createTaskExecutionTimes = (int) node.get("createTaskExecutionTimes"); // 共执行几次任务 9999次
        int generationDaysAfter = (int) node.get("generationDaysAfter"); // 执行任务(生成后第几天执行任务) 生成后第 1 天执行任务
        String generationHMS = (String) node.get("generationHMS"); // 执行任务时分秒 18:30:00
        int taskValidity = (int) node.get("taskValidity"); // 任务有效期天数 30天
        Date startDate;
        try {
            startDate = SDF.parse(node.get("JHTime").toString()); // 获取激活计划的时间日期作为第几天生成任务的基准时间

            // 初始化生成任务的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            calendar.add(Calendar.DAY_OF_MONTH, createTaskEvery); // 根据 createTaskEvery 来决定生成任务的时间
            // 增加5秒
            calendar.add(Calendar.SECOND, 5);
            Date generateTaskTime = calendar.getTime();
            // 提取生成任务时间的时分秒部分
            String generationHMSSCRW = TIME_FORMAT.format(generateTaskTime);
            // 打印或使用生成的时分秒字符串
            System.out.println("Generated Time (HH:mm:ss): " + generationHMSSCRW);
            // 生成任务 定时器
            node.put("action", "create");
            SysJob job2 = createSysJob(node, mdmCode, storeId, patientId, templateId, planId, taskId, createTaskEvery, generationHMSSCRW, generateTaskTime.toString());
            Date generateAdjustedDate = parseStringToDateWithMultipleFormats(job2.getLastTaskExecutionTime());
            job2.setExpiryDate(calculateExpiryDate(generateAdjustedDate, taskValidity));
            job2.setRemainingExecutions(createTaskExecutionTimes); // 设置剩余执行次数
            int PTC= jobService.insertJob2(job2);
            if (PTC > 0) { // 确保第一个任务插入成功
                // 延迟1秒
                Thread.sleep(1000);
                // 通过生成任务的时间计算执行任务的时间
                Calendar calendar3 = Calendar.getInstance();
                calendar3.setTime(generateAdjustedDate);
                calendar3.add(Calendar.DAY_OF_MONTH, generationDaysAfter); // 根据 generationDaysAfter 来决定执行任务的时间

                Date executeTaskTime = calendar3.getTime();

                // 执行任务 定时器
                node.put("action", "execute");
                SysJob job3 = createSysJob(node, mdmCode, storeId, patientId, templateId, planId, taskId, generationDaysAfter, generationHMS, executeTaskTime.toString());
                Date ExCutDate = parseStringToDateWithMultipleFormats(job2.getLastTaskExecutionTime());
                job3.setExpiryDate(ExCutDate);
                job3.setMaxExecutions(createTaskExecutionTimes); // 设置最大执行次数
                job3.setCurrentExecutionCount(0); // 初始化当前执行次数为0
                job3.setRemainingExecutions(createTaskExecutionTimes); // 设置剩余执行次数
                int PTA= jobService.insertJob2(job3);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        } catch (TaskException e) {
            throw new RuntimeException(e);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    /**1.2.3 事件条件+ 单次节点 SE*/
    private void handleSingleEventNode(PageData node, String mdmCode, String storeId, String patientId, String templateId, Integer planId, Integer taskId) throws Exception {
        node.put("nodeFlag", "SE");// 设置节点标志为SE 事件条件+单次节点
        String createTaskWhen = (String) node.get("createTaskWhen"); // 生成任务(当)
        int createTaskTriggerValue = (int) node.get("createTaskTriggerValue"); // 剩余用药天数
        int generationDaysAfter = (int) node.get("generationDaysAfter"); // 执行任务(生成后第几天执行任务)
        String generationHMS = (String) node.get("generationHMS"); // 执行任务时分秒
        int taskValidity = (int) node.get("taskValidity"); // 任务有效期天数
        if ("最近订单D值".equals(createTaskWhen)) {
            // 查询关联的D值购药用药天数
            PageData pd1 = new PageData();
            pd1.put("patientId", patientId);
            pd1.put("mdmCode", mdmCode);
            pd1.put("storeId", storeId);
            try {
                Date startDate;
                PageData D3Conditions = (PageData) daoSupport.findForObject("dvalueMapper.selectLinkDValuesBy3Conditions", pd1);
                int sum_total = Optional.ofNullable(D3Conditions).map(data -> (int) data.get("sum_total")).orElse(0); // 如果是空的 没有数据 就默认为0

                // 计算间隔天数
                int intervalTime = sum_total - createTaskTriggerValue;

                startDate = SDF.parse(node.get("JHTime").toString()); // 获取激活计划的时间日期作为第几天生成任务的基准时间

                // 初始化生成任务的时间
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(startDate);
                calendar.add(Calendar.DAY_OF_MONTH, intervalTime); // 根据 intervalTime 来决定生成任务的时间
                // 增加5秒
                calendar.add(Calendar.SECOND, 5);
                Date generateTaskTime = calendar.getTime();
                // 提取生成任务时间的时分秒部分
                String generationHMSSCRW = TIME_FORMAT.format(generateTaskTime);
                // 打印或使用生成的时分秒字符串
                System.out.println("Generated Time (HH:mm:ss): " + generationHMSSCRW);
                // 生成任务 定时器
                node.put("action", "create");
                SysJob job2 = createSysJob(node, mdmCode, storeId, patientId, templateId, planId, taskId, intervalTime, generationHMSSCRW, generateTaskTime.toString());
                Date generateAdjustedDate = parseStringToDateWithMultipleFormats(job2.getLastTaskExecutionTime());
                job2.setExpiryDate(calculateExpiryDate(generateAdjustedDate, taskValidity));
                int SEC= jobService.insertJob2(job2);
                if (SEC > 0) { // 确保第一个任务插入成功
                    // 延迟1秒
                    Thread.sleep(1000);
                    // 通过生成任务的时间计算执行任务的时间
                    Calendar calendar3 = Calendar.getInstance();
                    calendar3.setTime(generateAdjustedDate);
                    calendar3.add(Calendar.DAY_OF_MONTH, generationDaysAfter); // 根据 generationDaysAfter 来决定执行任务的时间
                    Date executeTaskTime = calendar3.getTime();

                    // 执行任务 定时器
                    node.put("action", "execute");
                    SysJob job3 = createSysJob(node, mdmCode, storeId, patientId, templateId, planId, taskId, generationDaysAfter, generationHMS, executeTaskTime.toString());
                    Date ExCutDate = parseStringToDateWithMultipleFormats(job2.getLastTaskExecutionTime());
                    job3.setExpiryDate(ExCutDate);
                    int SEA= jobService.insertJob2(job3);
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }

        } else {
            System.out.println("暂不支持该类型");
        }
        }
    /**1.2.4 事件条件+ 周期节点 PE*/
    public void handlePeriodicEventNode(PageData node, String mdmCode, String storeId, String patientId, String templateId, Integer planId, Integer taskId) throws Exception {
        node.put("nodeFlag", "PE");// 设置节点标志为PE 事件条件+周期节点
        // 事件条件 周期节点
        String createTaskWhen = (String) node.get("createTaskWhen"); // 生成任务(当)
        int createTaskTriggerValue = (int) node.get("createTaskTriggerValue"); // 剩余用药天数
        int createTaskExecutionTimes = (int) node.get("createTaskExecutionTimes"); // 共执行几次任务
        int generationDaysAfter = (int) node.get("generationDaysAfter"); // 执行任务(生成后第几天执行任务)
        String generationHMS = (String) node.get("generationHMS"); // 执行任务时分秒
        int taskValidity = (int) node.get("taskValidity"); // 任务有效期天数

        if ("最近订单D值".equals(createTaskWhen)) {
            // 查询关联的D值购药用药天数
            PageData pd1 = new PageData();
            pd1.put("patientId", patientId);
            pd1.put("mdmCode", mdmCode);
            pd1.put("storeId", storeId);
            Date startDate;
            try {
            PageData D3Conditions = (PageData) daoSupport.findForObject("dvalueMapper.selectLinkDValuesBy3Conditions", pd1);
            int sum_total = Optional.ofNullable(D3Conditions).map(data -> (int) data.get("sum_total")).orElse(0); // 如果是空的 没有数据 就默认为0
            // 计算间隔天数
            int intervalTime = sum_total - createTaskTriggerValue;
            startDate = SDF.parse(node.get("JHTime").toString()); // 获取激活计划的时间日期作为第几天生成任务的基准时间
            // 初始化生成任务的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            calendar.add(Calendar.DAY_OF_MONTH, intervalTime); // 根据 createTaskEvery 来决定生成任务的时间
            // 增加5秒
            calendar.add(Calendar.SECOND, 5);
            Date generateTaskTime = calendar.getTime();
                // 提取生成任务时间的时分秒部分
                String generationHMSSCRW = TIME_FORMAT.format(generateTaskTime);
                // 打印或使用生成的时分秒字符串
                System.out.println("Generated Time (HH:mm:ss): " + generationHMSSCRW);
            // 生成任务 定时器
            node.put("action", "create");
            SysJob job2 = createSysJob(node, mdmCode, storeId, patientId, templateId, planId, taskId, intervalTime, generationHMSSCRW, generateTaskTime.toString());
            Date generateAdjustedDate = parseStringToDateWithMultipleFormats(job2.getLastTaskExecutionTime());
            job2.setExpiryDate(calculateExpiryDate(generateAdjustedDate, taskValidity));
            job2.setRemainingExecutions(createTaskExecutionTimes); // 设置剩余执行次数
            int PEC=    jobService.insertJob2(job2);
                if (PEC > 0) { // 确保第一个任务插入成功
                    // 延迟1秒
                    Thread.sleep(1000);
                    // 通过生成任务的时间计算执行任务的时间
                    Calendar calendar3 = Calendar.getInstance();
                    calendar3.setTime(generateAdjustedDate);
                    calendar3.add(Calendar.DAY_OF_MONTH, generationDaysAfter); // 根据 generationDaysAfter 来决定执行任务的时间的
                    Date executeTaskTime = calendar3.getTime();

                    // 执行任务 定时器
                    node.put("action", "execute");
                    SysJob job3 = createSysJob(node, mdmCode, storeId, patientId, templateId, planId, taskId, generationDaysAfter, generationHMS, executeTaskTime.toString());
                    Date ExCutDate = parseStringToDateWithMultipleFormats(job2.getLastTaskExecutionTime());
                    job3.setExpiryDate(ExCutDate);
                    job3.setMaxExecutions(createTaskExecutionTimes); // 设置最大执行次数
                    job3.setCurrentExecutionCount(0); // 初始化当前执行次数为0
                    job3.setRemainingExecutions(createTaskExecutionTimes); // 设置剩余执行次数
                    int PEA=  jobService.insertJob2(job3);
                }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        } else {
            System.out.println("暂不支持该类型");
        }
    }

    /**3 生成表达式*/
    public static String generateCronExpression4(String createdTime, int activateWhichDay, String generationHMS, boolean isActivationJob) {
        // 正确的日期格式
        SimpleDateFormat sdfInput = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
        Calendar calendar = Calendar.getInstance();

        try {
            // 解析传入的创建时间
            Date date = sdfInput.parse(createdTime);
            calendar.setTime(date);

            // 加上激活计划的天数
            calendar.add(Calendar.DAY_OF_MONTH, activateWhichDay);

            if (isActivationJob) {
                // 对于激活任务，我们只关心日期部分
                return String.format("%d %d %d %d %d ? %d",
                        0, // 秒
                        0, // 分钟
                        0, // 小时
                        calendar.get(Calendar.DAY_OF_MONTH), // 日
                        calendar.get(Calendar.MONTH) + 1, // 月份（Calendar.MONTH 是从0开始计数的）
                        calendar.get(Calendar.YEAR)); // 年份
            } else {
                // 设置具体执行的小时、分钟和秒
                String[] timeParts = generationHMS.split(":");
                calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeParts[0]));
                calendar.set(Calendar.MINUTE, Integer.parseInt(timeParts[1]));
                calendar.set(Calendar.SECOND, Integer.parseInt(timeParts[2]));

                // 返回Cron表达式
                return String.format("%d %d %d %d %d ? %d",
                        calendar.get(Calendar.SECOND),
                        calendar.get(Calendar.MINUTE),
                        calendar.get(Calendar.HOUR_OF_DAY),
                        calendar.get(Calendar.DAY_OF_MONTH),
                        calendar.get(Calendar.MONTH) + 1,
                        calendar.get(Calendar.YEAR)); // 添加年份字段
            }
        } catch (ParseException e) {
            // 提供默认值或采取其他措施处理异常
            e.printStackTrace();
            // 这里可以设置一个默认的cron表达式，例如立即执行的任务
            return "0 0 0 * * ? *"; // 默认每天午夜执行的任务，并且包含年份占位符
        }
    }

    /**4 将字符串格式的时间转换为Date类型。*/
    public static Date parseStringToDateWithMultipleFormats(String time) throws ParseException {
        if (time == null || time.trim().isEmpty()) {
            throw new IllegalArgumentException("Time string cannot be null or empty.");
        }

        // 定义多个可能的时间格式
        String[] formats = {
                "yyyy-MM-dd HH:mm:ss",
                "yyyy/MM/dd HH:mm:ss",
                "dd-MM-yyyy HH:mm:ss",
                "MM/dd/yyyy HH:mm:ss"
        };

        // 尝试每种格式进行解析
        for (String format : formats) {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            try {
                return sdf.parse(time);
            } catch (ParseException e) {
                // 继续尝试下一个格式
            }
        }

        // 如果所有格式都无法解析，则抛出异常
        throw new ParseException("Unable to parse the date string with any of the provided formats.", 0);
    }

    /**6 任务有效期转换*/
    private Date calculateExpiryDate(Date startDate, int taskValidity) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        calendar.add(Calendar.DAY_OF_MONTH, taskValidity);
        return calendar.getTime();
    }

    /**购药处方登记成功后如果是随访品 触发计划和执行任务 暂时不用*/
    public String triggerPLan(PageData pd) throws Exception {
        System.out.println("生成定计划定时任务-执行有参方法:triggerPLan" + pd);
        PageData pd1 = new PageData();
        pd1.put("templateId", pd.get("PlanTemplateId"));
        List<PageData> nodeList = (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectNodeConfigByTemplateId", pd1); // 根据模版id 获取节点配置 templateId
        System.out.println("执行mapper方法:selectNodeConfigByTemplateId,return:" + nodeList.size());
        if (nodeList.size() > 0) {
            for (PageData node : nodeList) {
                String activateStructures = (String) node.get("activateStructures"); // 激活节点 激活节点(按) 创建计划 其他方式
                int activateWhichDay = (int) node.get("activateWhichDay"); // 第几天激活
                String activateNodeRule = (String) node.get("activateNodeRule"); // 单次节点：只执行一次 周期节点：按周期规则执行
                String createdTime = DateUtils.getTime(); // 计划创建时间 为当前时间
                System.out.println("计划创建时间createdTime==:" + createdTime);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date createdDate;
                try {
                    createdDate = sdf.parse(createdTime);
                    // 确保所有参数都是正确的类型，并且进行必要的转换 productCode templateId
                    String mdmCode = (String) pd.get("PlanProductCode");
                    String storeId = (String) pd.get("storeId");
                    String patientId = (String) pd.get("patientId");
                    String templateId =(String) node.get("templateId");
                    Integer planId = (Integer) pd.get("planId");

                    if ("创建计划".equals(activateStructures)) {
                        // 计算激活计划的时间
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(createdDate);
                        calendar.add(Calendar.DAY_OF_MONTH, activateWhichDay); // 根据 activateWhichDay 来决定激活计划的时间
                        Date generateTaskTime = calendar.getTime();
                        // 创建生成激活计划的任务
                        SysJob job2 = createSysJobPlan(pd, mdmCode, storeId, patientId, templateId, planId,activateWhichDay,generateTaskTime);
                        jobService.insertJob2(job2);
                    }
                } catch (NumberFormatException e) {
                    // 处理转换失败的情况
                    System.err.println("转换 storeId, templateId 或 planId 时发生错误: " + e.getMessage());
                    // 可能需要采取进一步措施，如记录日志、通知管理员等
                }
            }
        }
        return "2025-02-25 25:30:00";
    }

    /**5 Cron表达式转化为时间字符串*/
    public static String zhuanhuaDirectly(String cronExpression) throws ParseException {
        try {
            // 分割 Cron 表达式
            String[] parts = cronExpression.split(" ");
            if (parts.length != 7) {
                throw new ParseException("Invalid Cron expression format. Expected 7 fields.", 0);
            }

            // 提取各部分
            String second = parts[0];
            String minute = parts[1];
            String hour = parts[2];
            String dayOfMonth = parts[3];
            String month = parts[4];
            String dayOfWeek = parts[5]; // 这里我们忽略 dayOfWeek 字段
            String year = parts[6];

            // 构建 Calendar 对象并设置各字段
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, Integer.parseInt(year));
            calendar.set(Calendar.MONTH, parseMonth(month) - 1); // Calendar.MONTH 是从 0 开始的
            calendar.set(Calendar.DAY_OF_MONTH, parseDayOfMonth(dayOfMonth));
            calendar.set(Calendar.HOUR_OF_DAY, parseHour(hour));
            calendar.set(Calendar.MINUTE, parseMinute(minute));
            calendar.set(Calendar.SECOND, parseSecond(second));

            // 格式化时间为字符串
            return SDF.format(calendar.getTime());
        } catch (ParseException e) {
            // 打印或记录异常信息
            System.err.println("Error parsing Cron expression: " + e.getMessage());
            throw e; // 或者你可以选择返回一个错误消息而不是重新抛出异常
        }
    }

    /**
     * 解析月份字段。
     *
     * @param monthStr 月份字段字符串
     * @return 月份值
     * @throws ParseException 如果解析失败
     */
    private static int parseMonth(String monthStr) throws ParseException {
        switch (monthStr.toLowerCase()) {
            case "1": case "jan": return 1;
            case "2": case "feb": return 2;
            case "3": case "mar": return 3;
            case "4": case "apr": return 4;
            case "5": case "may": return 5;
            case "6": case "jun": return 6;
            case "7": case "jul": return 7;
            case "8": case "aug": return 8;
            case "9": case "sep": return 9;
            case "10": case "oct": return 10;
            case "11": case "nov": return 11;
            case "12": case "dec": return 12;
            default: throw new ParseException("Invalid month value: " + monthStr, 0);
        }
    }

    /**
     * 解析日字段。
     *
     * @param dayOfMonthStr 日字段字符串
     * @return 日值
     * @throws ParseException 如果解析失败
     */
    private static int parseDayOfMonth(String dayOfMonthStr) throws ParseException {
        try {
            return Integer.parseInt(dayOfMonthStr);
        } catch (NumberFormatException e) {
            throw new ParseException("Invalid day of month value: " + dayOfMonthStr, 0);
        }
    }

    /**
     * 解析小时字段。
     *
     * @param hourStr 小时字段字符串
     * @return 小时值
     * @throws ParseException 如果解析失败
     */
    private static int parseHour(String hourStr) throws ParseException {
        try {
            return Integer.parseInt(hourStr);
        } catch (NumberFormatException e) {
            throw new ParseException("Invalid hour value: " + hourStr, 0);
        }
    }

    /**
     * 解析分钟字段。
     *
     * @param minuteStr 分钟字段字符串
     * @return 分钟值
     * @throws ParseException 如果解析失败
     */
    private static int parseMinute(String minuteStr) throws ParseException {
        try {
            return Integer.parseInt(minuteStr);
        } catch (NumberFormatException e) {
            throw new ParseException("Invalid minute value: " + minuteStr, 0);
        }
    }

    /**
     * 解析秒字段。
     *
     * @param secondStr 秒字段字符串
     * @return 秒值
     * @throws ParseException 如果解析失败
     */
    private static int parseSecond(String secondStr) throws ParseException {
        try {
            return Integer.parseInt(secondStr);
        } catch (NumberFormatException e) {
            throw new ParseException("Invalid second value: " + secondStr, 0);
        }
    }


}
