陈昶聿
23 小时以前 a2dd5b42824eff9626d1f48e1561be85f17f6107
smartor/src/main/java/com/smartor/service/impl/ServiceSubtaskServiceImpl.java
@@ -8,24 +8,30 @@
import com.google.gson.Gson;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.service.IConfigService;
import com.ruoyi.common.dx.MessageSend;
import com.ruoyi.common.enums.WxGZHEnum;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.core.service.IConfigService;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.sms.SmsUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.smartor.common.FtpService;
import com.smartor.common.MtSubmitSmUtil;
import com.smartor.common.ScheduleSubtaskBuilder;
import com.smartor.config.PhoneUtils;
import com.smartor.domain.DTO.MydTrendReqDTO;
import com.smartor.domain.DTO.MzMydScoreRankDTO;
import com.smartor.domain.DTO.QuestionCountKsOrBqDTO;
import com.smartor.domain.DTO.ServiceSubtaskDetailDTO;
import com.smartor.domain.DTO.ServiceSubtaskOptionStatDTO;
import com.smartor.domain.*;
import com.smartor.domain.VO.HeLibraryCountVO;
import com.smartor.domain.VO.ServiceSubtaskCotinueCountVO;
import com.smartor.domain.VO.TransferDeptVO;
import com.smartor.domain.VO.*;
import com.smartor.domain.entity.ServiceSubtaskEntity;
import com.smartor.mapper.*;
import com.smartor.service.*;
@@ -41,12 +47,13 @@
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.*;
@@ -57,6 +64,8 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static cn.hutool.core.convert.Convert.toHex;
/**
 * 单一任务(随访)Service业务层处理
@@ -128,6 +137,9 @@
    @Autowired
    private IPatArchiveService patArchiveService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ScheduleSubtaskBuilder scheduleSubtaskBuilder;
@@ -204,10 +216,19 @@
    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    private PatMedOperationMapper patMedOperationMapper;
    private ServiceOutPathMapper serviceOutPathMapper;
    private static final String KEY_SEP = "\u0001";
    /** 二次随访生成锁前缀,防止同一原任务并发生成多条二次随访 */
    private static final String AGAIN_LOCK_KEY_PREFIX = "smartor:again:lock:";
    private static final long AGAIN_LOCK_SECONDS = 30L;
    @Autowired
    private PatMedOperationItemMapper patMedOperationItemMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    /**
     * 查询单一任务(随访)
@@ -410,26 +431,7 @@
    @Override
    public List<ServiceSubtaskRes> patItem(ServiceSubtaskEntity serviceSubtaskEntity) {
        if (serviceSubtaskEntity.getSendstateView() != null) {
            //            1:待随访(1 被领取、2 待发送、3 已发送、5 发送失败、7、超时);2:已完成( 6 已完成)、3:无需随访(4 不执行)
            if (serviceSubtaskEntity.getSendstateView() == 1)
                serviceSubtaskEntity.setSendstates(new ArrayList<>(Arrays.asList(1L, 2L, 3L, 5L, 7L)));
            if (serviceSubtaskEntity.getSendstateView() == 2)
                serviceSubtaskEntity.setSendstates(new ArrayList<>(Arrays.asList(6L)));
            if (serviceSubtaskEntity.getSendstateView() == 3)
                serviceSubtaskEntity.setSendstates(new ArrayList<>(Arrays.asList(4L)));
        }
        //患者获取随访任务-需要查询同个患者(身份证)所有的任务 景宁
        if (StringUtils.isNotEmpty(serviceSubtaskEntity.getOrgid()) && serviceSubtaskEntity.getOrgid().equals("47255004333112711A1001")) {
            if (ObjectUtils.isNotEmpty(serviceSubtaskEntity.getPatid())) {
                PatArchive patArchive = patArchiveService.selectPatArchiveByPatid(serviceSubtaskEntity.getPatid());
                if (ObjectUtils.isNotEmpty(patArchive) && StringUtils.isNotEmpty(patArchive.getIdcardno())) {
                    serviceSubtaskEntity.setPatid(null);
                    serviceSubtaskEntity.setSfzh(patArchive.getIdcardno());
                }
            }
        }
        List<ServiceSubtask> selectServiceSubtaskList = this.selectServiceSubtaskList(serviceSubtaskEntity);
        List<ServiceSubtask> selectServiceSubtaskList = getServiceSubtasks(serviceSubtaskEntity);
        List<ServiceSubtaskRes> serviceSubtaskResList = new ArrayList<>();
        for (ServiceSubtask serviceSubtask : selectServiceSubtaskList) {
@@ -465,6 +467,30 @@
            serviceSubtaskResList.add(serviceSubtaskRes);
        }
        return serviceSubtaskResList;
    }
    public List<ServiceSubtask> getServiceSubtasks(ServiceSubtaskEntity serviceSubtaskEntity) {
        if (serviceSubtaskEntity.getSendstateView() != null) {
            //            1:待随访(1 被领取、2 待发送、3 已发送、5 发送失败、7、超时);2:已完成( 6 已完成)、3:无需随访(4 不执行)
            if (serviceSubtaskEntity.getSendstateView() == 1)
                serviceSubtaskEntity.setSendstates(new ArrayList<>(Arrays.asList(1L, 2L, 3L, 5L, 7L)));
            if (serviceSubtaskEntity.getSendstateView() == 2)
                serviceSubtaskEntity.setSendstates(new ArrayList<>(Arrays.asList(6L)));
            if (serviceSubtaskEntity.getSendstateView() == 3)
                serviceSubtaskEntity.setSendstates(new ArrayList<>(Arrays.asList(4L)));
        }
        //患者获取随访任务-需要查询同个患者(身份证)所有的任务 景宁
        if (StringUtils.isNotEmpty(serviceSubtaskEntity.getOrgid()) && serviceSubtaskEntity.getOrgid().equals("47255004333112711A1001")) {
            if (ObjectUtils.isNotEmpty(serviceSubtaskEntity.getPatid())) {
                PatArchive patArchive = patArchiveService.selectPatArchiveByPatid(serviceSubtaskEntity.getPatid());
                if (ObjectUtils.isNotEmpty(patArchive) && StringUtils.isNotEmpty(patArchive.getIdcardno())) {
                    serviceSubtaskEntity.setPatid(null);
                    serviceSubtaskEntity.setSfzh(patArchive.getIdcardno());
                }
            }
        }
        List<ServiceSubtask> selectServiceSubtaskList = this.selectServiceSubtaskList(serviceSubtaskEntity);
        return selectServiceSubtaskList;
    }
    @Override
@@ -543,11 +569,22 @@
    @Override
    public List<ServiceSubtask> patItem2(ServiceSubtaskEntity serviceSubtaskEntity) {
        if (serviceSubtaskEntity.getSendstateView() != null) {
            //            1:待随访(1 被领取、2 待发送、3 已发送、5 发送失败、7、超时);2:已完成( 6 已完成)、3:无需随访(4 不执行)
            if (serviceSubtaskEntity.getSendstateView() == 1)
                serviceSubtaskEntity.setSendstates(new ArrayList<>(Arrays.asList(1L, 2L, 3L, 5L, 7L)));
            if (serviceSubtaskEntity.getSendstateView() == 2)
                serviceSubtaskEntity.setSendstates(new ArrayList<>(Arrays.asList(6L)));
            if (serviceSubtaskEntity.getSendstateView() == 3)
                serviceSubtaskEntity.setSendstates(new ArrayList<>(Arrays.asList(4L)));
        }
        List<ServiceSubtask> serviceSubtaskList = new ArrayList<>();
        for (Long sendstate : serviceSubtaskEntity.getSendstates()) {
            serviceSubtaskEntity.setSendstate(sendstate);
            List<ServiceSubtask> serviceSubtasks = serviceSubtaskMapper.selectServiceSubtaskList(serviceSubtaskEntity);
            serviceSubtaskList.addAll(serviceSubtasks);
        if(CollectionUtils.isNotEmpty(serviceSubtaskEntity.getSendstates())){
            for (Long sendstate : serviceSubtaskEntity.getSendstates()) {
                serviceSubtaskEntity.setSendstate(sendstate);
                List<ServiceSubtask> serviceSubtasks = serviceSubtaskMapper.selectServiceSubtaskList(serviceSubtaskEntity);
                serviceSubtaskList.addAll(serviceSubtasks);
            }
        }
        return serviceSubtaskList;
    }
@@ -618,6 +655,45 @@
            result.putIfAbsent("xsf", 0);
            result.putIfAbsent("dsf", 0);
            result.putIfAbsent("ywc", 0);
            result.putIfAbsent("cs", 0);
            result.putIfAbsent("yc", 0);
            result.putIfAbsent("jg", 0);
        }
        return result;
    }
    /**
     * 统计任务各种状态的数量(已优化)
     * 优化说明:
     * 1. 使用数据库层聚合计算,替代应用层遍历
     * 2. 性能提升 10-100 倍(取决于数据量)
     * 3. 降低内存占用和网络传输
     *
     * @param serviceSubtaskEntity 查询条件
     * @return 各状态统计结果
     */
    @Override
    public Map<String, Object> countByCondition(ServiceSubtaskEntity serviceSubtaskEntity) {
        // 直接调用数据库统计方法,在数据库层完成聚合计算
        Map<String, Object> result = serviceSubtaskMapper.countByCondition(serviceSubtaskEntity);
        // 处理空异常
        if (MapUtils.isEmpty(result)) {
            result = new HashMap<>();
            // 确保所有 key 都有值,避免空指针异常
            // MyBatis 的 SUM 在没有匹配行时会返回 null
            result.putIfAbsent("wzx", 0);
            result.putIfAbsent("ysf", 0);
            result.putIfAbsent("fssb", 0);
            result.putIfAbsent("yfs", 0);
            result.putIfAbsent("blq", 0);
            result.putIfAbsent("total", 0);
            result.putIfAbsent("wxsf", 0);
            result.putIfAbsent("xsf", 0);
            result.putIfAbsent("dsf", 0);
            result.putIfAbsent("dfs", 0);
            result.putIfAbsent("yfs", 0);
            result.putIfAbsent("cs", 0);
            result.putIfAbsent("ywc", 0);
            result.putIfAbsent("yc", 0);
            result.putIfAbsent("jg", 0);
        }
@@ -632,9 +708,64 @@
     */
    @Override
    public Map<String, Object> insertServiceSubtask(ServiceSubtask serviceSubtask) {
        serviceSubtask.setCreateTime(DateUtils.getNowDate());
        serviceSubtaskMapper.insertServiceSubtask(serviceSubtask);
        List<ServiceSubtask> serviceSubtasks = null;
        //先查询一下该患者是否已经创建根据serviceType,sendstate,inhospid,patid,orgid
        //这样判断主要是为了想让新华医院的外部导入患者创建任务,也能用这个接口
        if (StringUtils.isEmpty(serviceSubtask.getPatfrom()) || !serviceSubtask.getPatfrom().equals("2")) {
            ServiceSubtaskEntity serviceSubtaskVO = new ServiceSubtaskEntity();
            serviceSubtaskVO.setServiceType(serviceSubtask.getServiceType());
            serviceSubtaskVO.setInhospid(serviceSubtask.getInhospid());
            serviceSubtaskVO.setSendstates(new ArrayList<>(Arrays.asList(1L, 2L, 3L, 5L, 7L)));
            serviceSubtaskVO.setPatid(serviceSubtask.getPatid());
            serviceSubtaskVO.setOrgid(serviceSubtask.getOrgid());
            serviceSubtaskVO.setCampusid(serviceSubtask.getCampusid());
            serviceSubtasks = serviceSubtaskMapper.selectServiceSubtaskList(serviceSubtaskVO);
        }
        RSAPublicKeyExample rsaPublicKeyExample = new RSAPublicKeyExample();
        String format = null;
        if (CollectionUtils.isNotEmpty(serviceSubtasks)) {
            ServiceSubtask serviceSubtask1 = serviceSubtasks.get(0);
            ServiceOutPath serviceOutPath = new ServiceOutPath();
            serviceOutPath.setSubId(serviceSubtask1.getId());
            List<ServiceOutPath> serviceOutPaths = serviceOutPathMapper.selectServiceOutPathList(serviceOutPath);
            if (CollectionUtils.isNotEmpty(serviceOutPaths))
                format = String.format("%03X", serviceOutPaths.get(0).getId());
            else format = getOutPath(serviceSubtask1, rsaPublicKeyExample);
            serviceSubtask = serviceSubtask1;
        } else {
            //如果不存在,则新增
            ServiceTask serviceTask = serviceTaskService.selectServiceTaskByTaskid(serviceSubtask.getTaskid());
            if (ObjectUtils.isNotEmpty(serviceTask)) {
                serviceSubtask.setTaskDesc(serviceTask.getTaskDesc());
                serviceSubtask.setTaskName(serviceTask.getTaskName());
                serviceSubtask.setTemplatename(serviceTask.getTemplatename());
            }
            serviceSubtask.setCreateTime(DateUtils.getNowDate());
            serviceSubtaskMapper.insertServiceSubtask(serviceSubtask);
            //修改住院满意度状态(避免重复查询)
            if (serviceSubtask.getServiceType() != null && "6".equals(serviceSubtask.getServiceType())) {
                Long inhospid = serviceSubtask.getInhospid();
                if (inhospid != null) {
                    PatMedInhosp patMedInhosp = new PatMedInhosp();
                    patMedInhosp.setInhospMydFlag("1");
                    patMedInhosp.setInhospid(inhospid);
                    patMedInhospMapper.updatePatMedInhosp(patMedInhosp);
                }
            }
            format = getOutPath(serviceSubtask, rsaPublicKeyExample);
        }
        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isNotEmpty(format))
            result.put("url", StringUtils.isNotEmpty(req_path) ? localIP + ":" + req_path + "/wt?p=" + format : localIP + "/wt?p=" + format);
        else result.put("url", null);
        result.put("subId", serviceSubtask.getId());
        return result;
    }
    private String getOutPath(ServiceSubtask serviceSubtask, RSAPublicKeyExample rsaPublicKeyExample) {
        String format;
        String taskId = rsaPublicKeyExample.encryptedData(serviceSubtask.getTaskid().toString(), pub_key);
        String patid = rsaPublicKeyExample.encryptedData(serviceSubtask.getPatid().toString(), pub_key);
        String subId = rsaPublicKeyExample.encryptedData(serviceSubtask.getId().toString(), pub_key);
@@ -644,17 +775,15 @@
        serviceOutPath.setCreateTime(new Date());
        serviceOutPath.setParam6(subId);
        serviceOutPath.setOrgid(serviceSubtask.getOrgid());
        serviceOutPath.setTaskId(serviceSubtask.getTaskid());
        serviceOutPath.setSubId(serviceSubtask.getId());
        iServiceOutPathService.insertServiceOutPath(serviceOutPath);
        //转成16进制
        String format = String.format("%03X", serviceOutPath.getId());
        format = String.format("%03X", serviceOutPath.getId());
        serviceOutPath.setRadix(format);
        serviceOutPath.setUpdateTime(new Date());
        iServiceOutPathService.updateServiceOutPath(serviceOutPath);
        Map<String, Object> result = new HashMap<>();
        result.put("url", StringUtils.isNotEmpty(req_path) ? localIP + ":" + req_path + "/wt?p=" + format : localIP + "/wt?p=" + format);
        result.put("subId", serviceSubtask.getId());
        return result;
        return format;
    }
    /**
@@ -664,6 +793,7 @@
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addSubTaskAgain(ServiceSubtask serviceSubtask) {
        ServiceSubtask serviceSubtask1 = selectServiceSubtaskById(serviceSubtask.getId());
        PatMedInhosp patMedInhosp = new PatMedInhosp();
@@ -673,7 +803,7 @@
        PatArchive patArchive = patArchiveMapper.selectPatArchiveByPatid(serviceSubtask1.getPatid());
        //景宁 新增再次随访不能触发患者再入院
        boolean inhospAgain = true;
        if (serviceSubtask1.getOrgid().equals("47255004333112711A1001")) {
        if ("47255004333112711A1001".equals(serviceSubtask1.getOrgid())) {
            inhospAgain = false;
        }
        if (patMedInhospList.size() > 0 && inhospAgain) {
@@ -687,13 +817,17 @@
            serviceSubtask1.setRemark(StringUtils.isNotEmpty(serviceSubtask.getRemark()) ? serviceSubtask.getRemark() + ";无需再次随访,任务被标记不在执行" : "无需再次随访,任务被标记不在执行");
            serviceSubtaskMapper.updateServiceSubtask(serviceSubtask1);
            return "无需再次随访,任务被标记不在执行";
        } else if (StringUtils.isNotEmpty(patArchive.getNotrequiredFlag()) && patArchive.getNotrequiredFlag().equals("1")) {
        } else if (patArchive != null && StringUtils.isNotEmpty(patArchive.getNotrequiredFlag()) && patArchive.getNotrequiredFlag().equals("1")) {
            serviceSubtask1.setIsVisitAgain(2);
            serviceSubtaskMapper.updateServiceSubtask(serviceSubtask1);
            serviceSubtask1.setRemark(StringUtils.isNotEmpty(serviceSubtask.getRemark()) ? serviceSubtask.getRemark() + ";无需再次随访,患者被标记不需要被服务" : "无需再次随访,患者被标记不需要被服务");
            return "无需再次随访,患者被标记不需要被服务";
        } else if (ObjectUtils.isNotEmpty(serviceSubtask1.getIsVisitAgain()) && serviceSubtask1.getIsVisitAgain() == 2) {
            return "无需再次随访,该任务已经再次随访过了";
        }
        //丽水中医院根据下次任务ID生成再次随访
        if ("47231022633110211A2101".equals(serviceSubtask1.getOrgid())) {
            return addSubTaskAgainNextTaskId(serviceSubtask1);
        }
        //新增再次随访任务
        ServiceSubtask serviceSubtask2 = DtoConversionUtils.sourceToTarget(serviceSubtask, ServiceSubtask.class);
@@ -716,6 +850,285 @@
        return "再次随访任务创建失败,再请次重试";
    }
    public String addSubTaskAgainNextTaskId(ServiceSubtask serviceSubtask) {
        if (ObjectUtils.isEmpty(serviceSubtask.getTaskid())) {
            log.error("再次随访任务创建失败,缺少TaskId, 再请次重试");
            return "再次随访任务创建失败,缺少TaskId, 再请次重试";
        }
        // 同一原任务串行生成,防止并发重复插入
        String lockToken = tryLockAgainTask(serviceSubtask.getId());
        if (lockToken == null) {
            return "再次随访任务正在创建中,请勿重复提交";
        }
        try {
            ServiceTask serviceTask = serviceTaskService.selectServiceTaskByTaskid(serviceSubtask.getTaskid());
            if (ObjectUtils.isEmpty(serviceTask)) {
                log.error("再次随访任务创建失败,找不到对应任务 taskid = {}, 再请次重试", serviceSubtask.getTaskid());
                return "再次随访任务创建失败,找不到对应任务 taskid = " + serviceSubtask.getTaskid() + ", 再请次重试";
            }
            // 幂等校验:同一原任务只允许生成一条二次随访
            ServiceSubtaskEntity againQuery = new ServiceSubtaskEntity();
            againQuery.setUpid(serviceSubtask.getId().intValue());
            if (CollectionUtils.isNotEmpty(serviceSubtaskMapper.selectServiceSubtaskList(againQuery))) {
                return "无需再次随访,该任务已经再次随访过了";
            }
            // 查询出院记录
            PatMedInhosp patMedInhospVo = new PatMedInhosp();
            patMedInhospVo.setOrgid(serviceSubtask.getOrgid());
            patMedInhospVo.setInhospid(serviceSubtask.getInhospid());
            patMedInhospVo.setCry(1);
            List<PatMedInhosp> patMedInhospList = patMedInhospService.selectPatMedInhospList(patMedInhospVo);
            PatMedInhosp patMedInhosp = new PatMedInhosp();
            if (CollectionUtils.isNotEmpty(patMedInhospList)) {
                patMedInhosp = patMedInhospList.get(0);
            } else {
                log.error("再次随访任务创建失败,任务缺少 对应的出院记录, taskid = {}, 再请次重试", serviceSubtask.getTaskid());
                return "再次随访任务创建失败,任务缺少 对应的出院记录, taskid = " + serviceSubtask.getTaskid() + ", 再请次重试";
            }
            if (ObjectUtils.isEmpty(serviceTask.getNexttaskid())) {
                log.error("再次随访任务创建失败,任务缺少 nexttaskid, taskid = {}, 再请次重试", serviceSubtask.getTaskid());
                return "再次随访任务创建失败,任务缺少 nexttaskid, taskid = " + serviceSubtask.getTaskid() + ", 再请次重试";
            }
            ServiceTask nextServiceTask = serviceTaskService.selectServiceTaskByTaskid(serviceTask.getNexttaskid());
            if (ObjectUtils.isEmpty(nextServiceTask)) {
                log.error("再次随访任务创建失败,找不到对应任务 nexttaskid = {}, 再请次重试", serviceTask.getNexttaskid());
                return "再次随访任务创建失败,找不到对应任务 nexttaskid = " + serviceTask.getNexttaskid() + ", 再请次重试";
            }
            PatArchive patArchive = patArchiveService.selectPatArchiveByPatid(serviceSubtask.getPatid());
            if (ObjectUtils.isEmpty(patArchive)) {
                log.error("再次随访任务创建失败,未找到患者档案 patid = {}, subTaskId = {}", serviceSubtask.getPatid(), serviceSubtask.getId());
                return "再次随访任务创建失败,未找到患者档案, subTaskId = " + serviceSubtask.getId() + ", 再请次重试";
            }
            String config = configService.selectConfigByKey("visit.early.day");
            Integer type = 1;
            // 随访中心科室
            String centerDept = configService.selectConfigByKey("sys.smartor.center.dept", serviceSubtask.getOrgid());
            if (ObjectUtils.isEmpty(centerDept)) {
                log.error("再次随访任务创建失败,未配置随访中心科室参数 sys.smartor.center.dept ,subTaskId = {}, 再请次重试", serviceSubtask.getId());
                return "再次随访任务创建失败,未配置随访中心科室参数 sys.smartor.center.dept ,subTaskId = " + serviceSubtask.getId() + ", 再请次重试";
            }
            SysDept sysDeptVo = new SysDept();
            sysDeptVo.setDeptType("1");
            sysDeptVo.setOrgid(serviceSubtask.getOrgid());
            sysDeptVo.setDeptCode(centerDept);
            List<SysDept> sysDepts = sysDeptService.selectDeptList(sysDeptVo);
            SysDept sysDept = new SysDept();
            if (CollectionUtils.isNotEmpty(sysDepts)) {
                sysDept = sysDepts.get(0);
            } else {
                log.error("再次随访任务创建失败,未找到参数 sys.smartor.center.dept 配置的随访中心科室 deptCode = {}, 再请次重试", centerDept);
                return "再次随访任务创建失败,未找到参数 sys.smartor.center.dept 配置的随访中心科室 deptCode = " + centerDept + ", 再请次重试";
            }
            // 按下一任务生成二次随访子任务(表单、发送方式取自下一任务)
            ServiceSubtask serviceSubtaskAgain = patMedInhospService.boxedServiceSubtask(nextServiceTask,
                    patMedInhosp, patArchive, config, type);
            if (ObjectUtils.isEmpty(serviceSubtaskAgain) || ObjectUtils.isEmpty(serviceSubtaskAgain.getTaskid())) {
                log.error("再次随访任务创建失败,下一任务生成子任务为空, subTaskId = {}, nextTaskId = {}", serviceSubtask.getId(), serviceTask.getNexttaskid());
                return "再次随访任务创建失败,患者出院记录不完整或下一任务配置异常, 再请次重试";
            }
            Date now = new Date();
            serviceSubtaskAgain.setId(null);
            serviceSubtaskAgain.setUpid(serviceSubtask.getId().intValue());
            serviceSubtaskAgain.setVisitCount(ObjectUtils.isNotEmpty(serviceSubtask.getVisitCount())
                    ? serviceSubtask.getVisitCount() + 1 : 1);
            serviceSubtaskAgain.setSendstate(2L);
            serviceSubtaskAgain.setIsVisitAgain(1);
            serviceSubtaskAgain.setCreateTime(now);
            serviceSubtaskAgain.setUpdateTime(now);
//            // 二次随访时间:上次随访完成时间(未完成则当前时间)+ 下一任务发送天数;过去时间兜底为当前时间
//            Date baseTime = ObjectUtils.isNotEmpty(serviceSubtask.getFinishtime()) ? serviceSubtask.getFinishtime() : now;
//            int intervalDays = ObjectUtils.isNotEmpty(nextServiceTask.getSendDay())
//                    ? nextServiceTask.getSendDay().intValue() : 0;
//            Date nextVisitTime = DateUtils.addDays(baseTime, intervalDays);
//            if (nextVisitTime.before(now)) {
//                nextVisitTime = now;
//            }
//            serviceSubtaskAgain.setVisitTime(nextVisitTime);
//            serviceSubtaskAgain.setLongSendTime(nextVisitTime);
            serviceSubtaskAgain.setVisitType(serviceSubtask.getVisitType());
            serviceSubtaskAgain.setVisitDeptCode(sysDept.getDeptCode());
            serviceSubtaskAgain.setVisitDeptName(sysDept.getDeptName());
            int i = serviceSubtaskMapper.insertServiceSubtask(serviceSubtaskAgain);
            if (i != 1) {
                return "再次随访任务创建失败,再请次重试";
            }
            // 初始化发送方式明细,补偿(compensateTask)和超时判断依赖该表
            patMedInhospService.addServiceSubtaskPreachform(serviceSubtaskAgain, null);
            // 条件更新原任务:0 行说明已被其他请求生成,抛异常回滚本次插入的重复数据
            int updated = serviceSubtaskMapper.updateIsVisitAgainById(serviceSubtask.getId(), 2);
            if (updated != 1) {
                throw new BaseException("无需再次随访,该任务已经再次随访过了");
            }
            return "再次随访任务创建成功";
        } finally {
            unlockAgainTask(serviceSubtask.getId(), lockToken);
        }
    }
    /**
     * 首次随访任务超时后,按下一任务自动生成再次随访任务(随访中心)。
     * <p>
     * 定时任务入口 {@code RyTask#dealSubtaskDeadline} 使用。与手动入口一致的部分:
     * 表单/发送方式取下一任务、链路 upid + visit_count、发送方式明细初始化;
     * 差异:随访中心科室未配置时回退原任务科室,原任务置为发送失败(sendstate=5)。
     * <p>
     * 幂等:同一原任务只允许生成一条再次随访(Redis 锁 + upid 校验 + 原任务条件更新),
     * 多节点/多线程同时扫描时,后到的事务会在条件更新处拿到 0 行并回滚本次插入。
     *
     * @param serviceSubtask 已超时的首次随访子任务
     * @return 结果描述
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addSubTaskAgainByDeadline(ServiceSubtask serviceSubtask) {
        if (ObjectUtils.isEmpty(serviceSubtask) || ObjectUtils.isEmpty(serviceSubtask.getId())) {
            return "再次随访任务创建失败,原任务不存在";
        }
        String lockToken = tryLockAgainTask(serviceSubtask.getId());
        if (lockToken == null) {
            return "再次随访任务正在创建中,请勿重复提交";
        }
        try {
            // 幂等校验:同一原任务只允许生成一条再次随访
            ServiceSubtaskEntity againQuery = new ServiceSubtaskEntity();
            againQuery.setUpid(serviceSubtask.getId().intValue());
            if (CollectionUtils.isNotEmpty(serviceSubtaskMapper.selectServiceSubtaskList(againQuery))) {
                return "无需再次随访,该任务已经再次随访过了";
            }
            // 原任务已被标记为不再随访(手动入口写过 is_visit_again=2)
            if (ObjectUtils.isNotEmpty(serviceSubtask.getIsVisitAgain()) && serviceSubtask.getIsVisitAgain() == 2) {
                return "无需再次随访,该任务已经再次随访过了";
            }
            ServiceTask serviceTask = serviceTaskService.selectServiceTaskByTaskid(serviceSubtask.getTaskid());
            if (ObjectUtils.isEmpty(serviceTask)) {
                return "再次随访任务创建失败,找不到对应任务 taskid = " + serviceSubtask.getTaskid();
            }
            if (ObjectUtils.isEmpty(serviceTask.getNexttaskid())) {
                return "再次随访任务创建失败,任务缺少 nexttaskid, taskid = " + serviceSubtask.getTaskid();
            }
            ServiceTask nextServiceTask = serviceTaskService.selectServiceTaskByTaskid(serviceTask.getNexttaskid());
            if (ObjectUtils.isEmpty(nextServiceTask)) {
                return "再次随访任务创建失败,找不到对应任务 nexttaskid = " + serviceTask.getNexttaskid();
            }
            PatMedInhosp patMedInhosp = selectOutHospRecord(serviceSubtask);
            if (ObjectUtils.isEmpty(patMedInhosp)) {
                return "再次随访任务创建失败,任务缺少对应的出院记录, taskid = " + serviceSubtask.getTaskid();
            }
            PatArchive patArchive = patArchiveService.selectPatArchiveByPatid(serviceSubtask.getPatid());
            if (ObjectUtils.isEmpty(patArchive)) {
                return "再次随访任务创建失败,未找到患者档案, subTaskId = " + serviceSubtask.getId();
            }
            // 随访中心科室:未配置(或科室不存在)时回退原任务科室,保持超时入口原有行为
            SysDept visitDept = selectCenterDept(serviceSubtask.getOrgid());
            String config = configService.selectConfigByKey("visit.early.day");
            ServiceSubtask serviceSubtaskAgain = patMedInhospService.boxedServiceSubtask(nextServiceTask,
                    patMedInhosp, patArchive, config, 1);
            if (ObjectUtils.isEmpty(serviceSubtaskAgain) || ObjectUtils.isEmpty(serviceSubtaskAgain.getTaskid())) {
                return "再次随访任务创建失败,患者出院记录不完整或下一任务配置异常, subTaskId = " + serviceSubtask.getId();
            }
            Date now = new Date();
            serviceSubtaskAgain.setId(null);
            serviceSubtaskAgain.setUpid(serviceSubtask.getId().intValue());
            serviceSubtaskAgain.setVisitCount(ObjectUtils.isNotEmpty(serviceSubtask.getVisitCount())
                    ? serviceSubtask.getVisitCount() + 1 : 2);
            serviceSubtaskAgain.setSendstate(2L);
            serviceSubtaskAgain.setIsVisitAgain(1);
            serviceSubtaskAgain.setCreateTime(now);
            serviceSubtaskAgain.setUpdateTime(now);
            serviceSubtaskAgain.setVisitType(serviceSubtask.getVisitType());
            if (ObjectUtils.isNotEmpty(visitDept)) {
                serviceSubtaskAgain.setVisitDeptCode(visitDept.getDeptCode());
                serviceSubtaskAgain.setVisitDeptName(visitDept.getDeptName());
            } else {
                serviceSubtaskAgain.setVisitDeptCode(serviceSubtask.getVisitDeptCode());
                serviceSubtaskAgain.setVisitDeptName(serviceSubtask.getVisitDeptName());
            }
            if (serviceSubtaskMapper.insertServiceSubtask(serviceSubtaskAgain) != 1) {
                return "再次随访任务创建失败,再请次重试";
            }
            // 初始化发送方式明细,补偿(compensateTask)和超时判断依赖该表
            patMedInhospService.addServiceSubtaskPreachform(serviceSubtaskAgain, null);
            // 条件更新原任务:0 行说明已被其他请求生成,抛异常回滚本次插入的重复数据
            if (serviceSubtaskMapper.updateIsVisitAgainById(serviceSubtask.getId(), 2) != 1) {
                throw new BaseException("无需再次随访,该任务已经再次随访过了");
            }
            // 原任务超时,置为发送失败
            ServiceSubtask originUpdate = new ServiceSubtask();
            originUpdate.setId(serviceSubtask.getId());
            originUpdate.setSendstate(5L);
            originUpdate.setUpdateTime(now);
            serviceSubtaskMapper.updateServiceSubtask(originUpdate);
            return "再次随访任务创建成功";
        } finally {
            unlockAgainTask(serviceSubtask.getId(), lockToken);
        }
    }
    /**
     * 按 orgid + inhospid 取出院记录(超时再次随访用)。
     */
    private PatMedInhosp selectOutHospRecord(ServiceSubtask serviceSubtask) {
        PatMedInhosp patMedInhospVo = new PatMedInhosp();
        patMedInhospVo.setOrgid(serviceSubtask.getOrgid());
        patMedInhospVo.setInhospid(serviceSubtask.getInhospid());
        patMedInhospVo.setCry(1);
        List<PatMedInhosp> patMedInhospList = patMedInhospService.selectPatMedInhospList(patMedInhospVo);
        if (CollectionUtils.isEmpty(patMedInhospList)) {
            return null;
        }
        return patMedInhospList.get(0);
    }
    /**
     * 取随访中心科室,未配置或科室不存在时返回 null(由调用方回退原任务科室)。
     */
    private SysDept selectCenterDept(String orgid) {
        String centerDept = configService.selectConfigByKey("sys.smartor.center.dept", orgid);
        if (StringUtils.isEmpty(centerDept)) {
            return null;
        }
        SysDept sysDeptVo = new SysDept();
        sysDeptVo.setDeptType("1");
        sysDeptVo.setOrgid(orgid);
        sysDeptVo.setDeptCode(centerDept);
        List<SysDept> sysDepts = sysDeptService.selectDeptList(sysDeptVo);
        return CollectionUtils.isEmpty(sysDepts) ? null : sysDepts.get(0);
    }
    /**
     * 获取二次随访生成锁。Redis 异常时降级为数据库幂等校验,不阻断业务。
     */
    private String tryLockAgainTask(Long subId) {
        String token = UUID.randomUUID().toString();
        try {
            Boolean locked = redisTemplate.opsForValue().setIfAbsent(
                    AGAIN_LOCK_KEY_PREFIX + subId, token, AGAIN_LOCK_SECONDS, TimeUnit.SECONDS);
            return Boolean.TRUE.equals(locked) ? token : null;
        } catch (Exception e) {
            log.warn("再次随访获取Redis锁失败,降级使用数据库幂等校验, subId={}", subId, e);
            return token;
        }
    }
    /**
     * 释放二次随访生成锁,仅释放自己持有的锁。
     */
    private void unlockAgainTask(Long subId, String token) {
        if (token == null) {
            return;
        }
        try {
            String lockKey = AGAIN_LOCK_KEY_PREFIX + subId;
            Object current = redisTemplate.opsForValue().get(lockKey);
            if (token.equals(current)) {
                redisTemplate.delete(lockKey);
            }
        } catch (Exception e) {
            log.warn("再次随访释放Redis锁失败, subId={}", subId, e);
        }
    }
    /**
     * 修改单一任务(随访)
     *
@@ -727,6 +1140,7 @@
        serviceSubtask.setUpdateTime(DateUtils.getNowDate());
        if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate() == 6)
            serviceSubtask.setFinishtime(new Date());
        return serviceSubtaskMapper.updateServiceSubtask(serviceSubtask);
    }
@@ -995,8 +1409,8 @@
            //将任务信息放到服务表中
            ServiceSubtask serviceSubtask = DtoConversionUtils.sourceToTarget(serviceTaskVO, ServiceSubtask.class);
            serviceSubtask.setTaskid(serviceTask.getTaskid().longValue());
            serviceSubtask.setTemplatename(tempName);
            serviceSubtask.setTemplateid(tempid);
            serviceSubtask.setTemplatename(ObjectUtils.isNotEmpty(tempid) ? tempName : serviceTask.getTemplatename());
            serviceSubtask.setTemplateid(ObjectUtils.isNotEmpty(tempid) ? tempid : serviceTask.getTemplateid());
            serviceSubtask.setLibtemplateid(ObjectUtils.isEmpty(serviceTask.getLibtemplateid()) ? null : Long.valueOf(serviceTask.getLibtemplateid()));
            serviceSubtask.setLibtemplatename(serviceTask.getLibtemplatename());
            //新增
@@ -1079,8 +1493,7 @@
                }
            }
        }
        else if (serviceTaskVO.getIsoperation() != null && serviceTaskVO.getIsoperation() == 2) {
        } else if (serviceTaskVO.getIsoperation() != null && serviceTaskVO.getIsoperation() == 2) {
            //任务修改
            if (ObjectUtils.isNotEmpty(serviceTaskVO.getSendTimeslot()))
                serviceTask.setSendTimeSlot(JSON.toJSONString(serviceTaskVO.getSendTimeslot()));
@@ -1108,7 +1521,7 @@
                    redisCache.removeElementFromList("cache-3", serviceSubtask.getId().toString());
                    redisCache.removeElementFromList("cache-4", serviceSubtask.getId().toString());
                    //将出入院表的数据,还原成还未处理的状态
                    if (serviceSubtask.getServiceType().equals("2")) {
                    if (serviceSubtask.getServiceType().equals("2") || serviceSubtask.getServiceType().equals("13")) {
                        ServiceTask st = serviceTaskService.selectServiceTaskByTaskid(serviceSubtask.getTaskid());
                        //如果任务是长期任务,需要将该患者的出入院数据还原成还未处理的状态
                        if (st != null && st.getLongTask() == 1) {
@@ -1132,8 +1545,9 @@
                        }
                    } else if (serviceSubtask.getServiceType().equals("19")) {
                        ServiceTask st = serviceTaskService.selectServiceTaskByTaskid(serviceSubtask.getTaskid());
                        //如果任务是长期任务,需要将该患者的手术详情数据
                        if (st != null && st.getLongTask() == 1 && ObjectUtils.isNotEmpty(serviceSubtask.getOperationItemId())) {
                        //如果任务是长期任务,需要将该患者的出院详情状态还原成还未处理的状态
                        if (st != null && st.getLongTask() == 1
                                && ObjectUtils.isNotEmpty(serviceSubtask.getOperationItemId())) {
                            PatMedOperationItem patMedOperationItem = new PatMedOperationItem();
                            patMedOperationItem.setOpercheckFlag("0");
                            patMedOperationItem.setId(serviceSubtask.getOperationItemId());
@@ -1371,6 +1785,8 @@
                    ServiceSubtask serviceSubtask = DtoConversionUtils.sourceToTarget(serviceTaskVO, ServiceSubtask.class);
                    serviceSubtask.setLibtemplateid(ObjectUtils.isEmpty(serviceTaskVO.getLibtemplateid()) ? null : Long.valueOf(serviceTaskVO.getLibtemplateid()));
                    serviceSubtask.setLibtemplatename(serviceTaskVO.getLibtemplatename());
                    serviceSubtask.setTemplateid(serviceTask.getTemplateid());
                    serviceSubtask.setTemplatename(serviceTask.getTemplatename());
                    serviceSubtask.setSendname(patTaskRelevance.getName());
                    serviceSubtask.setAge(patTaskRelevance.getAge());
                    serviceSubtask.setSfzh(patTaskRelevance.getSfzh());
@@ -2832,7 +3248,7 @@
     * @return
     */
    @Override
    @Cacheable(value = "sfStatistics", key = "T(org.springframework.util.DigestUtils).md5DigestAsHex(#serviceSubtaskCountReq.toString().getBytes())", unless = "#result == null or #result.isEmpty()")
//    @Cacheable(value = "sfStatistics", key = "T(org.springframework.util.DigestUtils).md5DigestAsHex(#serviceSubtaskCountReq.toString().getBytes())", unless = "#result == null or #result.isEmpty()")
    public List<ServiceSubtaskStatistic> getSfStatistics(ServiceSubtaskCountReq serviceSubtaskCountReq) {
        log.info("getSfStatistics的入参为:{}", serviceSubtaskCountReq);
        String drcode = "drcode";
@@ -2866,12 +3282,10 @@
                collect = rawData.stream().collect(Collectors.groupingBy(subtask -> Optional.ofNullable(subtask.getDrcode()).orElse("Unknown")));
                break;
            case "management_doctor_code":
                rawData = rawData.stream()
                        .peek(item -> {
                            item.setDrname(item.getManagementDoctor());
                            item.setDrcode(item.getManagementDoctorCode());
                        })
                        .collect(Collectors.toList());
                rawData = rawData.stream().peek(item -> {
                    item.setDrname(item.getManagementDoctor());
                    item.setDrcode(item.getManagementDoctorCode());
                }).collect(Collectors.toList());
                collect = rawData.stream().collect(Collectors.groupingBy(subtask -> Optional.ofNullable(subtask.getManagementDoctorCode()).orElse("Unknown")));
                break;
            case "deptcode":
@@ -2956,6 +3370,8 @@
        ssRate.setOrgid(serviceSubtaskCountReq.getOrgid());
        ssRate.setStarttime(serviceSubtaskCountReq.getStartTime());
        ssRate.setEndtime(serviceSubtaskCountReq.getEndTime());
        ssRate.setStartOutHospTime(serviceSubtaskCountReq.getHospitalStartTime());
        ssRate.setEndOutHospTime(serviceSubtaskCountReq.getHospitalEndTime());
        ssRate.setVisitCount(serviceSubtaskCountReq.getVisitCount());
        ssRate.setServiceTypeList(serviceSubtaskCountReq.getServiceType());
        if (serviceSubtaskCountReq.getEndTime() != null && new Date().before(serviceSubtaskCountReq.getEndTime())) {
@@ -3047,6 +3463,8 @@
            if (serviceSubtaskCountReq.getEndTime() != null && new Date().before(serviceSubtaskCountReq.getEndTime())) {
                ss.setEndtime(new Date());
            }
            ss.setStartOutHospTime(serviceSubtaskCountReq.getHospitalStartTime());
            ss.setEndOutHospTime(serviceSubtaskCountReq.getHospitalEndTime());
            Double jsRate = serviceSubtaskMapper.selectTimelyRate(ss);
            statistic.setRate(jsRate);
            if (ObjectUtils.isNotEmpty(statistic)) {
@@ -3200,6 +3618,16 @@
                if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate() != 4) {
                    serviceSubtaskStatistic.setFollowUpNeeded(serviceSubtaskStatistic.getFollowUpNeeded() + 1L);
                }
                //及时随访人次:已完成且未超时
                if (isTimelyFollowUp(serviceSubtask)) {
                    serviceSubtaskStatistic.setTimelyFollowUp(serviceSubtaskStatistic.getTimelyFollowUp() + 1L);
                }
                //人工已拨通总量
                if (ObjectUtils.isNotEmpty(serviceSubtask.getIsManuallyCalled())
                        && serviceSubtask.getIsManuallyCalled().equals(1L)) {
                    serviceSubtaskStatistic.setManuallyCalled(serviceSubtaskStatistic.getManuallyCalled() + 1L);
                }
                //首次出院随访
                if (serviceSubtask.getVisitCount() != null && serviceSubtask.getVisitCount() == 1) {
@@ -3294,6 +3722,24 @@
                            serviceSubtaskStatistic.setWeChat(serviceSubtaskStatistic.getWeChat() + 1L);
                        }
                    }
                    //首次随访人工成功
                    if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("1")) {
                        serviceSubtaskStatistic.setManualSuccess(serviceSubtaskStatistic.getManualSuccess() + 1L);
                    }
                    //首次随访语音成功
                    if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("3")) {
                        serviceSubtaskStatistic.setVoiceSuccess(serviceSubtaskStatistic.getVoiceSuccess() + 1L);
                    }
                    //首次随访短信成功
                    if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("4")) {
                        serviceSubtaskStatistic.setSmsSuccess(serviceSubtaskStatistic.getSmsSuccess() + 1L);
                    }
                    //首次随访微信成功
                    if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("5")) {
                        serviceSubtaskStatistic.setWeChatSuccess(serviceSubtaskStatistic.getWeChatSuccess() + 1L);
                    }
                    if (serviceSubtaskStatistic.getNeedFollowUp() > 0) {
                        double rate = (double) (serviceSubtaskStatistic.getFollowUpSuccess() + serviceSubtaskStatistic.getFollowUpFail()) / serviceSubtaskStatistic.getNeedFollowUp();
                        serviceSubtaskStatistic.setFollowUpRate(percentFormat.format(rate));
@@ -3389,6 +3835,24 @@
                            serviceSubtaskStatistic.setWeChatAgain(serviceSubtaskStatistic.getWeChatAgain() + 1L);
                        }
                    }
                    //再次随访人工成功
                    if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("1")) {
                        serviceSubtaskStatistic.setManualAgainSuccess(serviceSubtaskStatistic.getManualAgainSuccess() + 1L);
                    }
                    //再次随访语音成功
                    if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("3")) {
                        serviceSubtaskStatistic.setVoiceAgainSuccess(serviceSubtaskStatistic.getVoiceAgainSuccess() + 1L);
                    }
                    //再次随访短信成功
                    if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("4")) {
                        serviceSubtaskStatistic.setSmsAgainSuccess(serviceSubtaskStatistic.getSmsAgainSuccess() + 1L);
                    }
                    //再次随访微信成功
                    if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("5")) {
                        serviceSubtaskStatistic.setWeChatAgainSuccess(serviceSubtaskStatistic.getWeChatAgainSuccess() + 1L);
                    }
                    if (serviceSubtaskStatistic.getNeedFollowUp() > 0) {
                        double rate = (double) (serviceSubtaskStatistic.getFollowUpSuccessAgain() + serviceSubtaskStatistic.getFollowUpFailAgain()) / serviceSubtaskStatistic.getNeedFollowUpAgain();
                        serviceSubtaskStatistic.setFollowUpRateAgain(percentFormat.format(rate));
@@ -3426,6 +3890,19 @@
    }
    /**
     * 是否属于「及时随访」:随访已完成且完成时状态为正常完成(未超时)。
     * <p>
     * finish_state:1-正常完成 2-延期完成 3-超时完成,只有 1 计入及时随访。
     *
     * @param serviceSubtask 随访子任务
     * @return true-计入及时随访人次
     */
    private boolean isTimelyFollowUp(ServiceSubtask serviceSubtask) {
        return serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L)
                && serviceSubtask.getFinishState() != null && serviceSubtask.getFinishState().equals(1L);
    }
    /**
     * 首次随访统计
     *
     * @param serviceSubtaskList
@@ -3456,6 +3933,10 @@
            //应随访人次
            if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate() != 4) {
                serviceSubtaskStatistic.setFollowUpNeeded(serviceSubtaskStatistic.getFollowUpNeeded() + 1L);
            }
            //及时随访人次:已完成且未超时
            if (isTimelyFollowUp(serviceSubtask)) {
                serviceSubtaskStatistic.setTimelyFollowUp(serviceSubtaskStatistic.getTimelyFollowUp() + 1L);
            }
            //首次出院随访
@@ -3543,6 +4024,24 @@
                        serviceSubtaskStatistic.setWeChat(serviceSubtaskStatistic.getWeChat() + 1L);
                    }
                }
                //首次随访人工成功
                if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("1")) {
                    serviceSubtaskStatistic.setManualSuccess(serviceSubtaskStatistic.getManualSuccess() + 1L);
                }
                //首次随访语音成功
                if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("3")) {
                    serviceSubtaskStatistic.setVoiceSuccess(serviceSubtaskStatistic.getVoiceSuccess() + 1L);
                }
                //首次随访短信成功
                if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("4")) {
                    serviceSubtaskStatistic.setSmsSuccess(serviceSubtaskStatistic.getSmsSuccess() + 1L);
                }
                //首次随访微信成功
                if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("5")) {
                    serviceSubtaskStatistic.setWeChatSuccess(serviceSubtaskStatistic.getWeChatSuccess() + 1L);
                }
                if (serviceSubtaskStatistic.getNeedFollowUp() > 0) {
                    double rate = (double) (serviceSubtaskStatistic.getFollowUpSuccess() + serviceSubtaskStatistic.getFollowUpFail()) / serviceSubtaskStatistic.getNeedFollowUp();
                    serviceSubtaskStatistic.setFollowUpRate(percentFormat.format(rate));
@@ -3607,6 +4106,10 @@
            //应随访人次
            if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate() != 4) {
                serviceSubtaskStatistic.setFollowUpNeeded(serviceSubtaskStatistic.getFollowUpNeeded() + 1L);
            }
            //及时随访人次:已完成且未超时
            if (isTimelyFollowUp(serviceSubtask)) {
                serviceSubtaskStatistic.setTimelyFollowUp(serviceSubtaskStatistic.getTimelyFollowUp() + 1L);
            }
            //再次出院随访
@@ -3694,6 +4197,24 @@
                        serviceSubtaskStatistic.setWeChatAgain(serviceSubtaskStatistic.getWeChatAgain() + 1L);
                    }
                }
                //再次随访人工成功
                if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("1")) {
                    serviceSubtaskStatistic.setManualAgainSuccess(serviceSubtaskStatistic.getManualAgainSuccess() + 1L);
                }
                //再次随访语音成功
                if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("3")) {
                    serviceSubtaskStatistic.setVoiceAgainSuccess(serviceSubtaskStatistic.getVoiceAgainSuccess() + 1L);
                }
                //再次随访短信成功
                if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("4")) {
                    serviceSubtaskStatistic.setSmsAgainSuccess(serviceSubtaskStatistic.getSmsAgainSuccess() + 1L);
                }
                //再次随访微信成功
                if (serviceSubtask.getSendstate() != null && serviceSubtask.getSendstate().equals(6L) && ObjectUtils.isNotEmpty(serviceSubtask.getCurrentPreachform()) && serviceSubtask.getCurrentPreachform().equals("5")) {
                    serviceSubtaskStatistic.setWeChatAgainSuccess(serviceSubtaskStatistic.getWeChatAgainSuccess() + 1L);
                }
                if (serviceSubtaskStatistic.getNeedFollowUp() > 0) {
                    double rate = (double) (serviceSubtaskStatistic.getFollowUpSuccessAgain() + serviceSubtaskStatistic.getFollowUpFailAgain()) / serviceSubtaskStatistic.getNeedFollowUpAgain();
                    serviceSubtaskStatistic.setFollowUpRateAgain(percentFormat.format(rate));
@@ -3846,7 +4367,8 @@
        serviceSubtaskStatistic.setDrname(serviceSubtaskList.get(0).getDrname());
        serviceSubtaskStatistic.setJoyCount(0);
        serviceSubtaskStatistic.setJoyAllCount(0);
        //出院人次
        serviceSubtaskStatistic.setDischargeCount(serviceSubtaskList.size());
        //获取随访统计
        if (subCounts == null) {
            subCounts = new ArrayList<>();
@@ -4031,12 +4553,15 @@
        iServiceOutPathService.insertServiceOutPath(serviceOutPath);
        //转成16进制
        String format = String.format("%03X", serviceOutPath.getId());
        String url = "";
        SendMagParam sendMagParam = new SendMagParam();
        url = localIP + ":" + req_path + "/sf?p=" + format;
        sendMagParam.setUrl(url);
        sendMagParam.setContent("【新华医院】您好,邀请您填写出院随访调查表,请点击" + sendMagParam.getUrl() + "填写。感谢您配合!");
        serviceOutPath.setRadix(format);
        serviceOutPath.setUpdateTime(new Date());
        serviceOutPath.setUrl(url);
        iServiceOutPathService.updateServiceOutPath(serviceOutPath);
        SendMagParam sendMagParam = new SendMagParam();
        sendMagParam.setUrl(localIP + ":" + req_path + "/sf?p=" + format);
        sendMagParam.setContent("【新华医院】您好,邀请您填写出院随访调查表,请点击" + sendMagParam.getUrl() + "填写。感谢您配合!");
        Map<String, String> map = new HashMap<>();
        map.put("phone", serviceSubtask.getPhone());
        map.put("content", sendMagParam.getContent());
@@ -4117,10 +4642,15 @@
     * pendingFollowUpInfo - visitCount = 1 && sendstate = 2
     * followUpSuccessInfo - visitCount = 1 && sendstate = 6
     * followUpFailInfo - visitCount = 1 && (sendstate = 5 || sendstate = 7)
     * timelyFollowUpInfo - sendstate = 6 && finish_state = 1(沿用请求的 visitCount 口径)
     * manualInfo - visitCount = 1 && currentPreachForm = "1"
     * voiceInfo - visitCount = 1 && currentPreachForm = "3"
     * smsInfo - visitCount = 1 && currentPreachForm = "4"
     * wechatInfo - visitCount = 1 && currentPreachForm = "5"
     * manualSuccessInfo - visitCount = 1 && currentPreachForm = "1" && sendstate = 6
     * voiceSuccessInfo - visitCount = 1 && currentPreachForm = "3" && sendstate = 6
     * smsSuccessInfo - visitCount = 1 && currentPreachForm = "4" && sendstate = 6
     * wechatSuccessInfo - visitCount = 1 && currentPreachForm = "5" && sendstate = 6
     * abnormalInfo - visitCount = 1 && excep = "1"
     * needFollowUpAgainInfo - visitCount > 1 && sendstate != 4
     * pendingFollowUpAgainInfo -  visitCount > 1 && sendstate = 2
@@ -4130,6 +4660,10 @@
     * voiceAgainInfo - visitCount > 1 && currentPreachForm = "3"
     * smsAgainInfo - visitCount > 1 && currentPreachForm = "4"
     * wechatAgainInfo -  visitCount > 1 && currentPreachForm = "5"
     * manualAgainSuccessInfo - visitCount > 1 && currentPreachForm = "1" && sendstate = 6
     * voiceAgainSuccessInfo - visitCount > 1 && currentPreachForm = "3" && sendstate = 6
     * smsAgainSuccessInfo - visitCount > 1 && currentPreachForm = "4" && sendstate = 6
     * wechatAgainSuccessInfo - visitCount > 1&& currentPreachForm = "5" && sendstate = 6
     * abnormalAgainInfo- visitCount = 1 && excep = "1"
     * taskSituation1Info - taskSituation = 1
     * taskSituation2Info - taskSituation = 2
@@ -4137,6 +4671,7 @@
     * taskSituation4Info - taskSituation = 4
     * taskSituation5Info - taskSituation = 5
     * taskSituation6Info - taskSituation = 7
     * manuallyCalledInfo - isManuallyCalled = 1L
     * filterCountList - taskSituation = 6 && sendstate = 4
     *
     */
@@ -4166,14 +4701,22 @@
    }
    private void applyHyperLinkInfoType(ServiceSubtaskCountReq serviceSubtaskCountReq, String hyperLinkInfoType) {
        //及时随访明细需要沿用请求的首次/再次口径
        Integer originVisitCount = serviceSubtaskCountReq.getVisitCount();
        serviceSubtaskCountReq.setVisitCount(null);
        serviceSubtaskCountReq.setSendstates(null);
        serviceSubtaskCountReq.setCurrentPreachform(null);
        serviceSubtaskCountReq.setExcep(null);
        serviceSubtaskCountReq.setTaskSituation(null);
        serviceSubtaskCountReq.setFinishState(null);
        switch (hyperLinkInfoType) {
            case "dischargeCountInfo":
                break;
            case "timelyFollowUpInfo":
                serviceSubtaskCountReq.setVisitCount(originVisitCount);
                serviceSubtaskCountReq.setSendstates(new ArrayList<>(Collections.singletonList(6L)));
                serviceSubtaskCountReq.setFinishState(1L);
                break;
            case "followUpNeededAllInfo":
                serviceSubtaskCountReq.setSendstates(new ArrayList<>(Arrays.asList(1L, 2L, 3L, 5L, 6L, 7L)));
@@ -4209,8 +4752,28 @@
                serviceSubtaskCountReq.setVisitCount(1);
                serviceSubtaskCountReq.setCurrentPreachform("4");
                break;
            case "wechatInfo":
            case "weChatInfo":
                serviceSubtaskCountReq.setVisitCount(1);
                serviceSubtaskCountReq.setCurrentPreachform("5");
                break;
            case "manualSuccessInfo":
                serviceSubtaskCountReq.setVisitCount(1);
                serviceSubtaskCountReq.setSendstates(new ArrayList<>(Collections.singletonList(6L)));
                serviceSubtaskCountReq.setCurrentPreachform("1");
                break;
            case "voiceSuccessInfo":
                serviceSubtaskCountReq.setVisitCount(1);
                serviceSubtaskCountReq.setSendstates(new ArrayList<>(Collections.singletonList(6L)));
                serviceSubtaskCountReq.setCurrentPreachform("3");
                break;
            case "smsSuccessInfo":
                serviceSubtaskCountReq.setVisitCount(1);
                serviceSubtaskCountReq.setSendstates(new ArrayList<>(Collections.singletonList(6L)));
                serviceSubtaskCountReq.setCurrentPreachform("4");
                break;
            case "weChatSuccessInfo":
                serviceSubtaskCountReq.setVisitCount(1);
                serviceSubtaskCountReq.setSendstates(new ArrayList<>(Collections.singletonList(6L)));
                serviceSubtaskCountReq.setCurrentPreachform("5");
                break;
            case "abnormalInfo":
@@ -4245,8 +4808,28 @@
                serviceSubtaskCountReq.setVisitCount(2);
                serviceSubtaskCountReq.setCurrentPreachform("4");
                break;
            case "wechatAgainInfo":
            case "weChatAgainInfo":
                serviceSubtaskCountReq.setVisitCount(2);
                serviceSubtaskCountReq.setCurrentPreachform("5");
                break;
            case "manualAgainSuccessInfo":
                serviceSubtaskCountReq.setVisitCount(1);
                serviceSubtaskCountReq.setSendstates(new ArrayList<>(Collections.singletonList(6L)));
                serviceSubtaskCountReq.setCurrentPreachform("1");
                break;
            case "voiceAgainSuccessInfo":
                serviceSubtaskCountReq.setVisitCount(2);
                serviceSubtaskCountReq.setSendstates(new ArrayList<>(Collections.singletonList(6L)));
                serviceSubtaskCountReq.setCurrentPreachform("3");
                break;
            case "smsAgainSuccessInfo":
                serviceSubtaskCountReq.setVisitCount(2);
                serviceSubtaskCountReq.setSendstates(new ArrayList<>(Collections.singletonList(6L)));
                serviceSubtaskCountReq.setCurrentPreachform("4");
                break;
            case "weChatAgainSuccessInfo":
                serviceSubtaskCountReq.setVisitCount(2);
                serviceSubtaskCountReq.setSendstates(new ArrayList<>(Collections.singletonList(6L)));
                serviceSubtaskCountReq.setCurrentPreachform("5");
                break;
            case "abnormalAgainInfo":
@@ -4275,6 +4858,9 @@
                serviceSubtaskCountReq.setTaskSituation(6);
                serviceSubtaskCountReq.setSendstates(new ArrayList<>(Collections.singletonList(4L)));
                break;
            case "manuallyCalledInfo":
                serviceSubtaskCountReq.setIsManuallyCalled(1L);
                break;
            default:
                break;
        }
@@ -4288,7 +4874,7 @@
     * @return
     */
    @Override
    @Cacheable(value = "getSfStatisticsScript", key = "T(org.springframework.util.DigestUtils).md5DigestAsHex(#serviceSubtaskCountReq.toString().getBytes())", unless = "#result == null or #result.isEmpty()")
//    @Cacheable(value = "getSfStatisticsScript", key = "T(org.springframework.util.DigestUtils).md5DigestAsHex(#serviceSubtaskCountReq.toString().getBytes())", unless = "#result == null or #result.isEmpty()")
    public List<ServiceSubtaskStatistic> getSfStatisticsScript(ServiceSubtaskCountReq serviceSubtaskCountReq) {
        log.info("getSfStatisticsScript的入参为:{}", serviceSubtaskCountReq);
        List<ServiceSubtaskStatistic> serviceSubtaskStatistics = new ArrayList<>();
@@ -4296,13 +4882,13 @@
        // 根据条件进行分组
        Map<String, List<ServiceSubtask>> collect = new HashMap<>();
        String groupKey = "drcode";
        if (serviceSubtaskCountReq.getLeavehospitaldistrictcodes() != null && !serviceSubtaskCountReq.getLeavehospitaldistrictcodes().isEmpty()) {
        if (serviceSubtaskCountReq.getStatisticaltype() != null && serviceSubtaskCountReq.getStatisticaltype() == 1) {
            if (serviceSubtaskCountReq.getDrcode() != null && !serviceSubtaskCountReq.getDrcode().isEmpty()) {
                groupKey = "drcode";
            } else {
                groupKey = "leavehospitaldistrictcode";
            }
        } else if (serviceSubtaskCountReq.getDeptcodes() != null && !serviceSubtaskCountReq.getDeptcodes().isEmpty()) {
        } else if (serviceSubtaskCountReq.getStatisticaltype() != null && serviceSubtaskCountReq.getStatisticaltype() == 2) {
            if (serviceSubtaskCountReq.getDrcode() != null && !serviceSubtaskCountReq.getDrcode().isEmpty()) {
                groupKey = "drcode";
            } else {
@@ -4418,8 +5004,7 @@
    }
    @Override
    public Map<String, ServiceSubtaskScriptCount> getSfStatisticsScriptDetails(ServiceSubtaskCountReq serviceSubtaskCountReq) {
        Map<String, ServiceSubtaskScriptCount> result = new HashMap<>();
    public Map<String, Object> getSfStatisticsScriptDetails(ServiceSubtaskCountReq serviceSubtaskCountReq) {
        List<ServiceSubtaskScriptCount> allCounts = new ArrayList<>();
        List<ServiceSubtaskScriptCount> allItemCounts = new ArrayList<>();
        String type = serviceSubtaskCountReq.getType();
@@ -4443,7 +5028,23 @@
            allItemCounts = serviceSubtaskMapper.getSfStatisticsScriptItemDetails(serviceSubtaskCountReq);
        }
        for (ServiceSubtaskScriptCount count : allCounts) {
        //返回结构是 Map,且不传 type 时会执行两条 SQL,PageHelper 没法对整体分页,
        //所以在题目合并完成之后按题目(scriptid)在这里分页,保证 total 和每页数据都是题目维度的。
        allCounts.sort(Comparator
                .comparing(ServiceSubtaskScriptCount::getSubtaskType, Comparator.nullsLast(String::compareTo))
                .thenComparing(ServiceSubtaskScriptCount::getScriptid, Comparator.nullsLast(Long::compareTo)));
        int pageNum = ObjectUtils.isNotEmpty(serviceSubtaskCountReq.getPageNum()) && serviceSubtaskCountReq.getPageNum() > 0
                ? serviceSubtaskCountReq.getPageNum() : 1;
        int pageSize = ObjectUtils.isNotEmpty(serviceSubtaskCountReq.getPageSize()) && serviceSubtaskCountReq.getPageSize() > 0
                ? serviceSubtaskCountReq.getPageSize() : 10;
        int total = allCounts.size();
        int fromIndex = (int) Math.min((long) (pageNum - 1) * pageSize, total);
        int toIndex = Math.min(fromIndex + pageSize, total);
        List<ServiceSubtaskScriptCount> pageCounts = allCounts.subList(fromIndex, toIndex);
        Map<String, ServiceSubtaskScriptCount> pageData = new LinkedHashMap<>();
        for (ServiceSubtaskScriptCount count : pageCounts) {
            Map<String, ServiceSubtaskScriptCount> itemCountMap = new HashMap<>();
            //问卷加上空白选项
            if (ObjectUtils.isNotEmpty(count.getTemplateid()) && ObjectUtils.isNotEmpty(count.getSubtaskType()) && count.getSubtaskType().equals("2")) {
@@ -4474,31 +5075,42 @@
                }
            }
            allItemCounts.forEach(itemCount -> {
                if (ObjectUtils.isNotEmpty(count.getScriptid()) && ObjectUtils.isNotEmpty(itemCount.getScriptid())) {
                    if (count.getScriptid().equals(itemCount.getScriptid())) {
                        //放入统计信息
                        itemCount.setScriptContent(count.getScriptContent());
                        itemCount.setScriptType(count.getScriptType());
                        itemCount.setSubtaskType(count.getSubtaskType());
                        itemCount.setCompletedQuantity(count.getCompletedQuantity());
                        itemCount.setAllQuantity(count.getAllQuantity());
                        itemCount.setCompletedPercentage(count.getCompletedPercentage());
                        itemCount.setTemplateid(count.getTemplateid());
                        //计算选择比例
                        int chosenQuantity = ObjectUtils.isNotEmpty(itemCount.getChosenQuantity()) ? itemCount.getChosenQuantity() : 0;
                        int completedQuantity = itemCount.getCompletedQuantity();
                        if (ObjectUtils.isNotEmpty(completedQuantity) && completedQuantity != 0) {
                            BigDecimal chosenPercentage = (new BigDecimal(chosenQuantity)).divide(new BigDecimal(completedQuantity), 2, RoundingMode.HALF_UP);
                            itemCount.setChosenPercentage(chosenPercentage.toString());
                        }
                        itemCountMap.put(itemCount.getOptionText(), itemCount);
                //明细行已按“题目内容+任务类型”聚合并带出 script_content,不能用 scriptid 匹配:
                //同一道题会被复制到多个任务模板,每个模板的 scriptid 都不同
                boolean sameQuestion = ObjectUtils.isNotEmpty(count.getScriptContent())
                        && ObjectUtils.isNotEmpty(itemCount.getScriptContent())
                        && count.getScriptContent().equals(itemCount.getScriptContent())
                        && Objects.equals(count.getSubtaskType(), itemCount.getSubtaskType());
                if (sameQuestion) {
                    //放入统计信息
                    itemCount.setScriptContent(count.getScriptContent());
                    itemCount.setScriptType(count.getScriptType());
                    itemCount.setSubtaskType(count.getSubtaskType());
                    itemCount.setCompletedQuantity(count.getCompletedQuantity());
                    itemCount.setAllQuantity(count.getAllQuantity());
                    itemCount.setCompletedPercentage(count.getCompletedPercentage());
                    itemCount.setTemplateid(count.getTemplateid());
                    //计算选择比例
                    int chosenQuantity = ObjectUtils.isNotEmpty(itemCount.getChosenQuantity()) ? itemCount.getChosenQuantity() : 0;
                    int completedQuantity = itemCount.getCompletedQuantity();
                    if (ObjectUtils.isNotEmpty(completedQuantity) && completedQuantity != 0) {
                        BigDecimal chosenPercentage = (new BigDecimal(chosenQuantity)).divide(new BigDecimal(completedQuantity), 2, RoundingMode.HALF_UP);
                        itemCount.setChosenPercentage(chosenPercentage.toString());
                    }
                    itemCountMap.put(itemCount.getOptionText(), itemCount);
                }
            });
            List<ServiceSubtaskScriptCount> itemCounts = new ArrayList<>(itemCountMap.values());
            count.setDetails(itemCounts);
            result.put(count.getScriptid().toString(), count);
            pageData.put(count.getScriptid().toString(), count);
        }
        Map<String, Object> result = new HashMap<>();
        // total 是题目总数(已按题目合并),rows/data 是当前页数据
        result.put("total", total);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        result.put("rows", new ArrayList<>(pageCounts));
        result.put("data", pageData);
        return result;
    }
@@ -4600,6 +5212,7 @@
        total.setPendingFollowUp(0L);
        total.setFollowUpSuccess(0L);
        total.setFollowUpFail(0L);
        total.setTimelyFollowUp(0L);
        total.setManual(0L);
        total.setSms(0L);
        total.setWeChat(0L);
@@ -4631,6 +5244,7 @@
            total.setPendingFollowUp(total.getPendingFollowUp() + (stat.getPendingFollowUp() != null ? stat.getPendingFollowUp() : 0L));
            total.setFollowUpSuccess(total.getFollowUpSuccess() + (stat.getFollowUpSuccess() != null ? stat.getFollowUpSuccess() : 0L));
            total.setFollowUpFail(total.getFollowUpFail() + (stat.getFollowUpFail() != null ? stat.getFollowUpFail() : 0L));
            total.setTimelyFollowUp(total.getTimelyFollowUp() + (stat.getTimelyFollowUp() != null ? stat.getTimelyFollowUp() : 0L));
            total.setManual(total.getManual() + (stat.getManual() != null ? stat.getManual() : 0L));
            total.setSms(total.getSms() + (stat.getSms() != null ? stat.getSms() : 0L));
            total.setWeChat(total.getWeChat() + (stat.getWeChat() != null ? stat.getWeChat() : 0L));
@@ -4922,15 +5536,17 @@
        serviceOutPath.setOrgid(serviceSubtask.getOrgid());
        iServiceOutPathService.insertServiceOutPath(serviceOutPath);
        String format = String.format("%03X", serviceOutPath.getId());
        serviceOutPath.setRadix(format);
        serviceOutPath.setUpdateTime(new Date());
        iServiceOutPathService.updateServiceOutPath(serviceOutPath);
        String url = "";
        SendMagParam sendMagParam = new SendMagParam();
        sendMagParam.setType("4");
        sendMagParam.setPhone(serviceSubtask.getPhone());
        sendMagParam.setUrl(StringUtils.isNotEmpty(req_path) ? localIP + ":" + req_path + "/wt?p=" + format : localIP + "/wt?p=" + format);
        url = StringUtils.isNotEmpty(req_path) ? localIP + ":" + req_path + "/wt?p=" + format : localIP + "/wt?p=" + format;
        sendMagParam.setUrl(url);
        serviceOutPath.setRadix(format);
        serviceOutPath.setUpdateTime(new Date());
        serviceOutPath.setUrl(url);
        iServiceOutPathService.updateServiceOutPath(serviceOutPath);
        SysConfig sysConfig = new SysConfig();
        sysConfig = sysConfigMapper.checkConfigKeyUnique("wj.sms.template");
@@ -4955,13 +5571,475 @@
    }
    @Override
    public List<ServiceSubtaskDetailRatioExport> statQuestionOption(List<Long> taskIds, Date startOutHospTime, Date endOutHospTime) {
    public Map<String, Object> weChatSubTask(Long subid) {
        log.info("smsSubTask的入参为:{}", subid);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", "500");
        resultMap.put("msg", "发送失败");
        //获取患者的基本信息
        ServiceSubtask serviceSubtask = selectServiceSubtaskById(subid);
        RSAPublicKeyExample rsaPublicKeyExample = new RSAPublicKeyExample();
        String patid = rsaPublicKeyExample.encryptedData(serviceSubtask.getPatid().toString(), pub_key);
        String subId = rsaPublicKeyExample.encryptedData(serviceSubtask.getId().toString(), pub_key);
        String taskId = rsaPublicKeyExample.encryptedData(serviceSubtask.getTaskid().toString(), pub_key);
        //丽水中医院发送的是微信公众号
        resultMap = wechatSubTask(subid);
        return resultMap;
    }
    public Map<String,Object> wechatSubTask(Long subid){
        log.info("wechatSubTask的入参为:{}", subid);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", "500");
        resultMap.put("msg", "发送失败");
        try{
            //获取随访的基本信息
            ServiceSubtask serviceSubtask = selectServiceSubtaskById(subid);
            //获取患者信息
            PatArchive patArchive = patArchiveMapper.selectPatArchiveByPatid(serviceSubtask.getPatid());
            RSAPublicKeyExample rsaPublicKeyExample = new RSAPublicKeyExample();
            String patid = rsaPublicKeyExample.encryptedData(serviceSubtask.getPatid().toString(), pub_key);
            String subId = rsaPublicKeyExample.encryptedData(serviceSubtask.getId().toString(), pub_key);
            String taskId = rsaPublicKeyExample.encryptedData(serviceSubtask.getTaskid().toString(), pub_key);
            String url = localIP + ":" + req_path + "/outsideChainwt?param1=" + taskId + "&param2=" + patid + "&param3="
                    + URLEncoder.encode(serviceSubtask.getTaskName(), StandardCharsets.UTF_8.toString()) + "&param5=false"
                    + "$param6=" + subId;
            ServiceOutPath serviceOutPath = new ServiceOutPath();
            serviceOutPath.setParam1(taskId);
            serviceOutPath.setParam2(patid);
            serviceOutPath.setParam3(serviceSubtask.getTaskName());
            serviceOutPath.setParam6(subId);
            serviceOutPath.setCreateTime(new Date());
            serviceOutPath.setOrgid(serviceSubtask.getOrgid());
            iServiceOutPathService.insertServiceOutPath(serviceOutPath);
            String format = String.format("%03X", serviceOutPath.getId());
            serviceOutPath.setRadix(format);
            serviceOutPath.setUpdateTime(new Date());
            serviceOutPath.setUrl(url);
            iServiceOutPathService.updateServiceOutPath(serviceOutPath);
            //获取微信公众号请求信息根据机构ID
            List<String> wxqqxx = WxGZHEnum.getDescByCode(serviceSubtask.getOrgid());
            if (CollectionUtils.isEmpty(wxqqxx) || wxqqxx.size() < 4) {
                resultMap.put("code", -1);
                resultMap.put("message", "发送异常:" + "【公众号】该机构的公众号配置信息不全,无法通过公众号发送");
                return resultMap;
            }
            if (StringUtils.isEmpty(serviceSubtask.getPatidHis())) {
                resultMap.put("code", -1);
                resultMap.put("message", "发送异常:" + "【公众号】公众号发送失败,his系统的患者id为空");
                return resultMap;
            }
            String wxCode = "";
            wxCode = getWXCode(serviceSubtask.getSfzh(), url, serviceSubtask.getTaskName(), serviceSubtask.getTaskDesc(), patArchive.getTelcode(), serviceSubtask.getSendname(), patArchive.getPatidHis(), wxqqxx);
            Map map = JSONObject.parseObject(wxCode, Map.class);
            Boolean wxCodeSuccess = false;
            if (!map.isEmpty() && map.get("succ") != null) {
                wxCodeSuccess = (boolean) map.get("succ");
            }
            //发送完成后,修改状态
            serviceSubtask.setSendstate(3L);
            if (wxCodeSuccess) {
                serviceSubtask.setResult("success");
                resultMap.put("code", "200");
                resultMap.put("msg", "发送成功");
            } else {
                log.error("【sfHandlle】公众号发送失败,患者信息:{},错误信息:{}", serviceSubtask, map.get("msg"));
                resultMap.put("code", -1);
                resultMap.put("message", "【公众号】公众号发送失败");
                return resultMap;
            }
        } catch (Exception e) {
            String guid = UUID.randomUUID().toString();
            log.error("【sfHandlle】长期任务公众号发送失败,原因:{},GUID:{}", e.getMessage(), guid);
            resultMap.put("code", -1);
            resultMap.put("message", "【公众号】长期任务公众号发送失败,原因:" + e.getMessage());
            return resultMap;
        }
        return resultMap;
    }
    @Override
    public List<ServiceSubtaskDetailRatioExport> statQuestionOption(List<Long> taskIds, Date startFinishTime, Date endFinishTime, Date startOutHospTime, Date endOutHospTime, String scriptContent, Double scoreStart, Double scoreEnd, String valueType, List<Long> subtaskIds) {
        //先清理一下重复数据
        List<Long> repeatIds = serviceSubtaskDetailMapper.selectRepeatDetailIds();
        if (!CollectionUtils.isEmpty(repeatIds)) {
            serviceSubtaskDetailMapper.deleteRepeatDetailByIds(repeatIds);
        }
        return serviceSubtaskMapper.statQuestionOption(taskIds, startOutHospTime, endOutHospTime);
        List<ServiceSubtaskDetailRatioExport> serviceSubtaskDetailRatioExports = serviceSubtaskMapper.statQuestionOption(taskIds, startOutHospTime, endOutHospTime, startFinishTime, endFinishTime, scoreStart, scoreEnd, scriptContent, valueType, subtaskIds);
        // 处理 targetvalue:按 & 分割成多条记录
        List<ServiceSubtaskDetailRatioExport> result = new ArrayList<>();
        for (ServiceSubtaskDetailRatioExport export : serviceSubtaskDetailRatioExports) {
            if (StringUtils.isNotEmpty(export.getTargetvalue()) && export.getTargetvalue().contains("&")) {
                String[] values = export.getTargetvalue().split("&");
                // 如果有多条目标值,拆分成多行
                for (String value : values) {
                    //先去 result 中查一下,有没有这个 questiontext 和对应的 targetvalue
                    //注意必须带上 taskid 一起匹配:否则会把别的任务的数据填到本任务的行上,
                    //导致导出的「数量/比例」和该行的「任务名称/任务编号」对不上(同一任务同一题出现两个不同分母)
                    ServiceSubtaskDetailRatioExport existingExport = result.stream().filter(e -> Objects.equals(e.getTaskid(), export.getTaskid()) && e.getQuestiontext().equals(export.getQuestiontext()) && value.trim().equals(e.getTargetvalue())).findFirst().orElse(null);
                    if (existingExport != null && existingExport.getRatio().equals("0") && existingExport.getCount().equals("0")) {
                        //如果存在,则将 result 里的这个问题所对应的 Targetvalue=value 这条数据更新成当前这条数据
                        if (value.equals(export.getOptionresult())) {
                            existingExport.setRatio(export.getRatio());
                            existingExport.setScore(export.getScore());
                            existingExport.setCount(export.getCount());
                            existingExport.setOptionresult(export.getOptionresult());
                        }
                    } else if (existingExport != null && !existingExport.getRatio().equals("0")) {
                        continue;
                    } else {
                        ServiceSubtaskDetailRatioExport newExport = DtoConversionUtils.sourceToTarget(export, ServiceSubtaskDetailRatioExport.class);
                        newExport.setTargetvalue(value.trim()); // targetvalue 显示单个选项
                        if (!value.equals(export.getOptionresult())) {
                            newExport.setOptionresult(null);
                            newExport.setCount("0");
                            newExport.setRatio("0");
                        }
                        result.add(newExport);
                    }
                }
            } else {
                // targetvalue 不包含 &,直接添加到结果
                result.add(export);
            }
        }
        return result;
    }
    @Override
    public List<ServiceSubtaskDetailRatioExport> statMydQuestionOptionForExport(List<Long> subtaskIds, String questiontext) {
        List<ServiceSubtaskDetailRatioExport> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(subtaskIds)) {
            return result;
        }
        List<ServiceSubtaskOptionStatDTO> statList = serviceSubtaskMapper.statMydQuestionOptionForExport(subtaskIds, questiontext);
        if (CollectionUtils.isEmpty(statList)) {
            return result;
        }
        return buildMydOptionRows(statList);
    }
    /**
     * 把「任务+题目+选项」的作答统计拼成导出的「问题详情占比」行
     * <ul>
     *     <li>选项清单:题目配置过的选项在 targetvalue(用 & 连接)里,全部列出,没人选的显示 0</li>
     *     <li>数量:患者选中的选项在 asrtext 里(多选题是「A&B」),每个选中项各记一次人数,一个患者只算一条明细</li>
     *     <li>比例:数量 / 该题作答患者数,所以单选题各选项数量之和 = 该题作答患者数</li>
     *     <li>分数:该选项明细的 score 之和;多选行按选中项份数均分,保证各选项分数之和 = 明细分数之和</li>
     * </ul>
     */
    private static List<ServiceSubtaskDetailRatioExport> buildMydOptionRows(List<ServiceSubtaskOptionStatDTO> statList) {
        List<ServiceSubtaskDetailRatioExport> result = new ArrayList<>();
        // 按「任务 + 题目」分组,保持 SQL 的顺序(先题目后任务)
        Map<String, List<ServiceSubtaskOptionStatDTO>> grouped = new LinkedHashMap<>();
        for (ServiceSubtaskOptionStatDTO stat : statList) {
            String key = stat.getTaskid() + "\u0001" + stat.getQuestiontext();
            grouped.computeIfAbsent(key, k -> new ArrayList<>()).add(stat);
        }
        for (List<ServiceSubtaskOptionStatDTO> group : grouped.values()) {
            ServiceSubtaskOptionStatDTO first = group.get(0);
            // 选项 -> 人数(long[1] 便于累加),顺序即出现顺序
            Map<String, long[]> countMap = new LinkedHashMap<>();
            Map<String, BigDecimal> scoreMap = new LinkedHashMap<>();
            for (ServiceSubtaskOptionStatDTO stat : group) {
                // targetvalue = 本题所有选项的清单,没人选的也要列出来
                List<String> options = splitOptions(stat.getTargetvalue());
                // asrtext = 患者实际选中的选项,多选题会是「选中项1&选中项2」
                List<String> chosenOptions = splitOptions(stat.getOptionresult());
                for (String option : options) {
                    countMap.computeIfAbsent(option, k -> new long[1]);
                    scoreMap.computeIfAbsent(option, k -> BigDecimal.ZERO);
                }
                long patientCount = stat.getPatientCount() == null ? 0L : stat.getPatientCount();
                BigDecimal scoreSum = stat.getScoreSum() == null ? BigDecimal.ZERO : stat.getScoreSum();
                if (!chosenOptions.isEmpty()) {
                    BigDecimal[] scoreParts = splitScore(scoreSum, chosenOptions.size());
                    for (int i = 0; i < chosenOptions.size(); i++) {
                        String chosen = chosenOptions.get(i);
                        // 选中的选项可能不在配置清单里(历史数据),补一行
                        countMap.computeIfAbsent(chosen, k -> new long[1]);
                        scoreMap.computeIfAbsent(chosen, k -> BigDecimal.ZERO);
                        countMap.get(chosen)[0] += patientCount;
                        scoreMap.put(chosen, scoreMap.get(chosen).add(scoreParts[i]));
                    }
                } else if (options.size() == 1) {
                    // 没有 asrtext(未答/无应答)时,只有唯一选项才能确定归属
                    countMap.get(options.get(0))[0] += patientCount;
                    scoreMap.put(options.get(0), scoreMap.get(options.get(0)).add(scoreSum));
                }
            }
            long total = 0L;
            for (long[] count : countMap.values()) total += count[0];
            for (Map.Entry<String, long[]> entry : countMap.entrySet()) {
                long count = entry.getValue()[0];
                ServiceSubtaskDetailRatioExport row = new ServiceSubtaskDetailRatioExport();
                row.setQuestiontext(first.getQuestiontext());
                row.setOptionresult(entry.getKey());
                row.setTargetvalue(entry.getKey());
                row.setCount(String.valueOf(count));
                row.setRatio(formatRatio(count, total));
                row.setScore(formatScore(scoreMap.get(entry.getKey())));
                row.setTaskname(first.getTaskName());
                row.setTaskid(first.getTaskid());
                row.setValueType(first.getValueType());
                result.add(row);
            }
        }
        return result;
    }
    /**
     * 把一条明细的分数按选中项份数均分,余数补给第一个,保证各份之和 = 原分数
     */
    private static BigDecimal[] splitScore(BigDecimal total, int parts) {
        BigDecimal[] result = new BigDecimal[parts];
        if (parts <= 0) {
            return result;
        }
        BigDecimal each = total.divide(BigDecimal.valueOf(parts), 2, RoundingMode.HALF_UP);
        for (int i = 0; i < parts; i++) {
            result[i] = each;
        }
        result[0] = result[0].add(total.subtract(each.multiply(BigDecimal.valueOf(parts))));
        return result;
    }
    /**
     * 拆分题目配置的选项(多个选项用 & 连接),顺带去掉全角/半角空白
     */
    private static List<String> splitOptions(String targetvalue) {
        List<String> options = new ArrayList<>();
        if (StringUtils.isEmpty(targetvalue)) {
            return options;
        }
        for (String part : targetvalue.split("&")) {
            String option = trimAll(part);
            if (StringUtils.isNotEmpty(option) && !options.contains(option)) {
                options.add(option);
            }
        }
        return options;
    }
    /**
     * 比例:数量 / 该题作答患者数,保留两位小数
     */
    private static String formatRatio(long count, long total) {
        if (total <= 0) {
            return "0.00%";
        }
        return BigDecimal.valueOf(count * 100.0 / total).setScale(2, RoundingMode.HALF_UP).toPlainString() + "%";
    }
    /**
     * 分数之和:去掉多余的小数位(0.00 -> 0)
     */
    private static String formatScore(BigDecimal score) {
        if (score == null) {
            return "0";
        }
        BigDecimal value = score.stripTrailingZeros();
        if (value.scale() < 0) {
            value = value.setScale(0);
        }
        return value.toPlainString();
    }
    /*
     * 根据科室或病区统计问卷选项(科室、题目查询的科室评分表)
     */
    @Override
    public Map<String, Map<String, List<QuestionCountKsOrBqDTO>>> statQuestionOptionByKsOrBq(QuestionCountKsOrBqVO vo) {
        // 1. 查明细
        List<QuestionCountKsOrBqDTO> sourceList = serviceSubtaskMapper.statQuestionOptionByKsOrBq(vo);
        if (CollectionUtils.isEmpty(sourceList)) {
            return Collections.emptyMap();
        }
        // 2. 判断按科室还是按病区
        boolean byDept = vo.getLeaveldeptcodes() != null;
        boolean byDistrict = !byDept && vo.getLeavehospitaldistrictcodes() != null;
        if (!byDept && !byDistrict) {
            return Collections.emptyMap();
        }
        // 3. key = 科室/病区 + 题目 + 选项
        Map<String, QuestionCountKsOrBqDTO> map = new LinkedHashMap<>();
        for (QuestionCountKsOrBqDTO dto : sourceList) {
            if (StringUtils.isEmpty(dto.getTargetvalue())) {
                continue;
            }
            // 分组名:科室 或 病区
            String groupName = byDept ? dto.getDeptname() : dto.getLeavehospitaldistrictname();
            if (StringUtils.isEmpty(groupName)) {
                continue;
            }
            String asrtext = trimAll(dto.getAsrtext());            // 用户实际选中的选项
            String questionText = trimAll(dto.getQuestionText());  // 题目
            if (StringUtils.isEmpty(questionText)) {
                continue;
            }
            // 拆分 targetvalue,每个选项都要有一条记录
            for (String raw : dto.getTargetvalue().split("&")) {
                String option = trimAll(raw);
                if (option.isEmpty()) {
                    continue;
                }
                // key = 科室/病区 + 题目 + 选项
                String key = buildKey(groupName, questionText, option);
                QuestionCountKsOrBqDTO item = map.get(key);
                if (item == null) {
                    item = DtoConversionUtils.sourceToTarget(dto, QuestionCountKsOrBqDTO.class);
                    item.setTargetvalue(option);
                    item.setAsrtext(option);
                    item.setQuestionText(dto.getQuestionText());
                    item.setAnswerCount("0");
                    item.setSingleScore("0");
                    map.put(key, item);
                }
                // 只有当前选项 == 用户实际选中的选项,才累加
                if (option.equals(asrtext)) {
                    int count = parseCount(item.getAnswerCount()) + 1;
                    item.setAnswerCount(String.valueOf(count));
                    BigDecimal totalScore = new BigDecimal(item.getSingleScore())
                            .add(new BigDecimal(dto.getSingleScore() == null ? "0" : dto.getSingleScore()));
                    item.setSingleScore(totalScore.toPlainString());
                }
            }
        }
        // 4. 计算平均分
        for (QuestionCountKsOrBqDTO dto : map.values()) {
            String answerCount = dto.getAnswerCount();
            String singleScore = dto.getSingleScore();
            BigDecimal avg;
            if (StringUtils.isEmpty(answerCount)
                    || BigDecimal.ZERO.compareTo(new BigDecimal(answerCount.trim())) == 0) {
                avg = BigDecimal.ZERO;
            } else {
                avg = new BigDecimal(singleScore == null ? "0" : singleScore)
                        .divide(new BigDecimal(answerCount.trim()), 2, RoundingMode.HALF_UP);
            }
            dto.setAvgScore(avg.toPlainString());
        }
        // 5. 转成 Map<String, Map<String, List<QuestionCountKsOrBqDTO>>>
        //    第一层 key:科室/病区
        //    第二层 key:题目
        //    第二层 value:该题目下的所有选项列表
        Map<String, Map<String, List<QuestionCountKsOrBqDTO>>> result = new LinkedHashMap<>();
        for (QuestionCountKsOrBqDTO dto : map.values()) {
            // 分组名
            String groupName = byDept ? dto.getDeptname() : dto.getLeavehospitaldistrictname();
            if (StringUtils.isEmpty(groupName)) {
                continue;
            }
            // 题目名
            String questionText = dto.getQuestionText();
            if (StringUtils.isEmpty(questionText)) {
                continue;
            }
            // 第一层:科室/病区
            Map<String, List<QuestionCountKsOrBqDTO>> questionMap =
                    result.computeIfAbsent(groupName, k -> new LinkedHashMap<>());
            // 第二层:题目
            List<QuestionCountKsOrBqDTO> optionList =
                    questionMap.computeIfAbsent(questionText, k -> new ArrayList<>());
            optionList.add(dto);
        }
        return result;
    }
    @Override
    public List<ServiceSubtaskDetailRatioExport> statQuestionOptionBySubtaskIds(List<Long> subtaskIds, Date startOutHospTime, Date endOutHospTime, Date startFinishTime, Date endFinishTime, String scriptContent, Double scoreStart, Double scoreEnd, String valueType) {
        //先清理一下重复数据
        List<Long> repeatIds = serviceSubtaskDetailMapper.selectRepeatDetailIds();
        if (!CollectionUtils.isEmpty(repeatIds)) {
            serviceSubtaskDetailMapper.deleteRepeatDetailByIds(repeatIds);
        }
        List<ServiceSubtaskDetailRatioExport> serviceSubtaskDetailRatioExports = serviceSubtaskMapper.statQuestionOptionBySubtaskIds(subtaskIds, startOutHospTime, endOutHospTime, startFinishTime, endFinishTime, scoreStart, scoreEnd, scriptContent, valueType);
        // 处理 targetvalue:按 & 分割成多条记录
        List<ServiceSubtaskDetailRatioExport> result = new ArrayList<>();
        for (ServiceSubtaskDetailRatioExport export : serviceSubtaskDetailRatioExports) {
            if (StringUtils.isNotEmpty(export.getTargetvalue()) && export.getTargetvalue().contains("&")) {
                String[] values = export.getTargetvalue().split("&");
                // 如果有多条目标值,拆分成多行
                for (String value : values) {
                    //先去 result 中查一下,有没有这个 questiontext 和对应的 targetvalue
                    ServiceSubtaskDetailRatioExport existingExport = result.stream().filter(e -> {
                        if (e == null || export == null) {
                            return false;
                        }
                        String q1 = e.getQuestiontext() != null ? e.getQuestiontext() : "";
                        String q2 = export.getQuestiontext() != null ? export.getQuestiontext() : "";
                        String t1 = value.trim();
                        String t2 = e.getTargetvalue() != null ? e.getTargetvalue() : "";
                        return q1.equals(q2) && t1.equals(t2);
                    }).findFirst().orElse(null);
                    if (existingExport != null && "0".equals(existingExport.getRatio()) && "0".equals(existingExport.getCount())) {
                        //如果存在,则将 result 里的这个问题所对应的 Targetvalue=value 这条数据更新成当前这条数据
                        if (value.equals(export.getOptionresult())) {
                            existingExport.setRatio(export.getRatio());
                            existingExport.setScore(export.getScore());
                            existingExport.setCount(export.getCount());
                            existingExport.setOptionresult(export.getOptionresult());
                        }
                    } else if (existingExport != null && !"0".equals(existingExport.getRatio())) {
                        continue;
                    } else {
                        ServiceSubtaskDetailRatioExport newExport = DtoConversionUtils.sourceToTarget(export, ServiceSubtaskDetailRatioExport.class);
                        newExport.setTargetvalue(value.trim()); // targetvalue 显示单个选项
                        if (!value.equals(export.getOptionresult())) {
                            newExport.setOptionresult(null);
                            newExport.setCount("0");
                            newExport.setRatio("0");
                        }
                        result.add(newExport);
                    }
                }
            } else {
                // targetvalue 不包含 &,直接添加到结果
                result.add(export);
            }
        }
        return result;
    }
    /**
@@ -5185,6 +6263,34 @@
        return content;
    }
    /**
     * 满意度趋势查询
     *
     * @param mydTrendReqVO
     * @return
     */
    @Override
    public List<MydTrendReqDTO> mydTrend(MydTrendReqVO mydTrendReqVO) {
        List<MydTrendReqDTO> list = serviceSubtaskMapper.mydTrend(mydTrendReqVO.getStartFinishTime(), mydTrendReqVO.getEndFinishTime(), mydTrendReqVO.getType());
        if (mydTrendReqVO.getType().equals("week")) list = getWeekDate(mydTrendReqVO, list);
        if (mydTrendReqVO.getType().equals("year")) list = getYearDate(mydTrendReqVO, list);
        if (mydTrendReqVO.getType().equals("month")) list = getMonthDate(mydTrendReqVO, list);
        if (mydTrendReqVO.getType().equals("day")) list = getDayDate(mydTrendReqVO, list);
        return list;
    }
    @Override
    public List<MydTrendReqDTO> sltdMydTotalByDimension(MydTrendReqVO mydTrendReqVO) {
        List<MydTrendReqDTO> list = null;
        if (mydTrendReqVO.getDimensionType().equals("1"))
            list = serviceSubtaskMapper.sltdMydTotalByDimension(mydTrendReqVO.getStartFinishTime(), mydTrendReqVO.getEndFinishTime(), mydTrendReqVO.getType());
        else if (mydTrendReqVO.getDimensionType().equals("2"))
            list = serviceSubtaskMapper.sltdMydTotalByYQ(mydTrendReqVO.getStartFinishTime(), mydTrendReqVO.getEndFinishTime(), mydTrendReqVO.getType());
        return list;
    }
    public ServiceSubtask boxedServiceSubtask(ServiceTask serviceTask, ServiceTaskdept serviceTaskdept, PatArchive patArchive) {
        ServiceSubtask serviceSubtask = DtoConversionUtils.sourceToTarget(serviceTask, ServiceSubtask.class);
        serviceSubtask.setTaskid(serviceTask.getTaskid());
@@ -5266,12 +6372,171 @@
        }
    }
    public PhoneCallBackSHVO getFirstQues(PhoneCallReqYQVO phoneCallReqYQVO) {
        //用于返回
        PhoneCallBackSHVO phoneCallBackSHVO = new PhoneCallBackSHVO();
        //根据手机号获取用户的的子任务信息
        ServiceSubtaskEntity serviceSubtaskVO = new ServiceSubtaskEntity();
        serviceSubtaskVO.setPhone(phoneCallReqYQVO.getPhone());
        serviceSubtaskVO.setType("1");
        serviceSubtaskVO.setSendstate(2L);
        List<ServiceSubtask> serviceSubtasks = serviceSubtaskMapper.selectServiceSubtaskList(serviceSubtaskVO);
        if (CollectionUtils.isNotEmpty(serviceSubtasks)) {
            ServiceSubtask serviceSubtask = serviceSubtasks.get(0);
            IvrTaskTemplate ivrTaskTemplate = ivrTaskTemplateService.selectIvrTaskTemplateByID(serviceSubtask.getTemplateid());
            //通过任务模板中的"第一次问题编号"获取第一个问题;
            IvrTaskTemplateScript ivrTaskTemplateScript = null;
            IvrTaskTemplateScript ivrTaskTemplateScript1 = new IvrTaskTemplateScript();
            ivrTaskTemplateScript1.setTemplateID(ivrTaskTemplate.getId());
            List<IvrTaskTemplateScript> ivrTaskTemplateScripts = iIvrTaskTemplateScriptService.selectIvrTaskTemplateScriptList(ivrTaskTemplateScript1);
            for (IvrTaskTemplateScript ivrTaskTemplateScript2 : ivrTaskTemplateScripts) {
                if (ivrTaskTemplate.getFirstQuestionNum() == Long.valueOf(ivrTaskTemplateScript2.getSort())) {
                    ivrTaskTemplateScript = ivrTaskTemplateScript2;
                    break;
                }
            }
            //获取开场白
            ServiceTask serviceTask = serviceTaskService.selectServiceTaskByTaskid(serviceSubtask.getTaskid());
            phoneCallBackSHVO.setSubId(serviceSubtask.getId());
            phoneCallBackSHVO.setScriptId(ivrTaskTemplateScript.getId());
            phoneCallBackSHVO.setSort(ivrTaskTemplateScript.getSort());
            phoneCallBackSHVO.setTaskTemplateid(ivrTaskTemplateScript.getTemplateID());
            phoneCallBackSHVO.setScriptContent(serviceTask.getKcb() + "," + ivrTaskTemplateScript.getScriptContent());
        }
        return phoneCallBackSHVO;
    }
    /**
     * 三汇ASR结果处理
     *
     * @param phoneCallResultYQVO
     * @return
     */
    public PhoneCallBackSHVO processResust(PhoneCallResultYQVO phoneCallResultYQVO) {
        PhoneCallBackSHVO phoneCallBackSHVO = new PhoneCallBackSHVO();
        //通过scriptid,获取所有的结果
        String url = configService.selectConfigByKey("sys.voice.match.ai.url", phoneCallResultYQVO.getOrgid());
        ServiceSubtask serviceSubtask = serviceSubtaskMapper.selectServiceSubtaskById(phoneCallResultYQVO.getSubId());
        IvrTaskTemplate ivrTaskTemplate = ivrTaskTemplateService.selectIvrTaskTemplateByID(serviceSubtask.getTemplateid());
        IvrTaskTemplateScriptVO ivrTaskTemplateScriptVO = iIvrTaskTemplateScriptService.getTaskTempScriptInfoByid(Long.valueOf(phoneCallResultYQVO.getScriptId()));
        Integer i = matchOptionIndex(url, phoneCallResultYQVO.getScriptContent(), phoneCallResultYQVO.getAsrResult(), ivrTaskTemplateScriptVO.getIvrTaskScriptTargetoptionList(), phoneCallResultYQVO.getUuid());
        if (i >= 0) {
            String optiondesc = ivrTaskTemplateScriptVO.getIvrTaskScriptTargetoptionList().get(i).getOptiondesc();
            //将患者的回答写进service_subtask_detail中
            ServiceSubTaskDetailReq serviceSubTaskDetailReq = new ServiceSubTaskDetailReq();
            List<ServiceSubtaskDetail> serviceSubtaskDetailList = new ArrayList<>();
            ivrTaskTemplateScriptVO.setQuestionResult(optiondesc);
            PhoneCallReqYQVO phoneCallReqYQVO = new PhoneCallReqYQVO();
            phoneCallReqYQVO.setTaskid("" + serviceSubtask.getId());
            phoneCallReqYQVO.setPhone(phoneCallResultYQVO.getPhone());
            phoneCallReqYQVO.setAsrtext(phoneCallResultYQVO.getAsrResult());
            ServiceSubtaskDetail serviceSubtaskDetail = getServiceSubtaskDetail(phoneCallReqYQVO, ivrTaskTemplateScriptVO, serviceSubtask, ivrTaskTemplate);
            //修改一下语音路径(改成前端可以访问的,存到数据库中)
            if (StringUtils.isNotEmpty(serviceSubtaskDetail.getQuestionvoice())) {
                String questionvoice = serviceSubtaskDetail.getQuestionvoice();
                String[] split = questionvoice.split("\\\\");
                if (split.length > 0) {
                    String lastPart = split[split.length - 1];
                    serviceSubtaskDetail.setQuestionvoice(voicePathPrefix + lastPart);
                }
            }
            serviceSubtaskDetailList.add(serviceSubtaskDetail);
            serviceSubTaskDetailReq.setServiceSubtaskDetailList(serviceSubtaskDetailList);
            serviceSubTaskDetailReq.setGuid(phoneCallResultYQVO.getGuid());
            serviceSubTaskDetailReq.setOrgid(phoneCallResultYQVO.getOrgid());
            saveQuestionAnswerPhone(serviceSubTaskDetailReq);
            IvrTaskTemplateScript ivrTaskTemplateScript = new IvrTaskTemplateScript();
            ivrTaskTemplateScript.setTemplateID(ivrTaskTemplateScriptVO.getTemplateID());
            List<IvrTaskTemplateScript> ivrTaskTemplateScripts = iIvrTaskTemplateScriptService.selectIvrTaskTemplateScriptList(ivrTaskTemplateScript);
            //获取下一题
            for (IvrTaskTemplateScript script : ivrTaskTemplateScripts) {
                if (ivrTaskTemplateScriptVO.getNextScriptno() == null || ivrTaskTemplateScriptVO.getNextScriptno() == 0) {
                    ServiceTask serviceTask = serviceTaskService.selectServiceTaskByTaskid(serviceSubtask.getTaskid());
                    phoneCallBackSHVO.setScriptContent(serviceTask.getJsy());
                    phoneCallBackSHVO.setTaskTemplateid(script.getTemplateID());
                    phoneCallBackSHVO.setSort(script.getSort());
                    phoneCallBackSHVO.setScriptId(script.getId());
                    phoneCallBackSHVO.setSubId(serviceSubtask.getId());
                    phoneCallBackSHVO.setStatus("0");
                } else if (script.getSort() == ivrTaskTemplateScriptVO.getNextScriptno().intValue()) {
                    phoneCallBackSHVO.setScriptContent(script.getScriptContent());
                    phoneCallBackSHVO.setTaskTemplateid(script.getTemplateID());
                    phoneCallBackSHVO.setSort(script.getSort());
                    phoneCallBackSHVO.setScriptId(script.getId());
                    phoneCallBackSHVO.setSubId(serviceSubtask.getId());
                    break;
                }
            }
            //把缓存清除
            redisCache.deleteObject(phoneCallResultYQVO.getSubId() + "-" + phoneCallResultYQVO.getScriptId());
        } else {
            //再将重复询问
            //记录一下这个问题被问题的次数
            Object cacheObject = redisCache.getCacheObject(phoneCallResultYQVO.getSubId() + "-" + phoneCallResultYQVO.getScriptId());
            if (cacheObject == null || (Integer) cacheObject < ivrTaskTemplate.getMateNum()) {
                // 获取选项集合中的 optiondesc 用于引导患者
                List<IvrTaskTemplateTargetoption> optionList = ivrTaskTemplateScriptVO.getIvrTaskScriptTargetoptionList();
                String optionDescStr = "";
                if (optionList != null && !optionList.isEmpty()) {
                    optionDescStr = optionList.stream().map(IvrTaskTemplateTargetoption::getTargetvalue).filter(StringUtils::isNotEmpty).collect(Collectors.joining("或"));
                }
                String scriptContent = "请问" + phoneCallResultYQVO.getScriptContent();
                if (StringUtils.isNotEmpty(optionDescStr)) {
                    scriptContent += ",你可以回答:" + optionDescStr;
                }
                phoneCallBackSHVO.setScriptContent(scriptContent);
                phoneCallBackSHVO.setTaskTemplateid(phoneCallResultYQVO.getTaskTemplateid());
                phoneCallBackSHVO.setSort(phoneCallResultYQVO.getSort());
                phoneCallBackSHVO.setScriptId(phoneCallResultYQVO.getScriptId());
                phoneCallBackSHVO.setSubId(phoneCallResultYQVO.getSubId());
                if (cacheObject == null)
                    redisCache.setCacheObject(phoneCallResultYQVO.getSubId() + "-" + phoneCallResultYQVO.getScriptId(), 1, 120, TimeUnit.MINUTES);
                else
                    redisCache.setCacheObject(phoneCallResultYQVO.getSubId() + "-" + phoneCallResultYQVO.getScriptId(), (Integer) cacheObject + 1, 120, TimeUnit.MINUTES);
            } else if ((Integer) cacheObject >= ivrTaskTemplate.getMateNum()) {
                //如果已经问了规定次数,就不问了,继续问下一题(这个要商量一下,是继续问下一题,还是停了,是不是要做个开关)
                IvrTaskTemplateScript ivrTaskTemplateScript = new IvrTaskTemplateScript();
                ivrTaskTemplateScript.setTemplateID(ivrTaskTemplateScriptVO.getTemplateID());
                List<IvrTaskTemplateScript> ivrTaskTemplateScripts = iIvrTaskTemplateScriptService.selectIvrTaskTemplateScriptList(ivrTaskTemplateScript);
                //获取下一题
                for (IvrTaskTemplateScript script : ivrTaskTemplateScripts) {
                    if (script.getSort() == ivrTaskTemplateScriptVO.getNextScriptno().intValue()) {
                        phoneCallBackSHVO.setScriptContent(script.getScriptContent());
                        phoneCallBackSHVO.setTaskTemplateid(script.getTemplateID());
                        phoneCallBackSHVO.setSort(script.getSort());
                        phoneCallBackSHVO.setScriptId(script.getId());
                        phoneCallBackSHVO.setSubId(serviceSubtask.getId());
                        break;
                    }
                }
                //把缓存清除
                redisCache.deleteObject(phoneCallResultYQVO.getSubId() + "-" + phoneCallResultYQVO.getScriptId());
            }
        }
        return phoneCallBackSHVO;
    }
    public PhoneCallBackYQVO AiMatch(String url, PhoneCallReqYQVO phoneCallReqYQVO, PhoneCallBackYQVO phoneCallBackYQVO, IvrTaskTemplateScriptVO ivrTaskTemplateScriptVO, ServiceSubtask serviceSubtask, IvrTaskTemplate ivrTaskTemplate, List<IvrTaskTemplateScript> ivrTaskTemplateScripts, String scriptId, Integer flag, String uuid) {
        PhoneCallBackYQVO back = null;
        List<IvrTaskTemplateTargetoption> options = ivrTaskTemplateScriptVO.getIvrTaskScriptTargetoptionList();
        String voiceText = phoneCallReqYQVO.getAsrtext();
        String questionText = StringUtils.isNotEmpty(ivrTaskTemplateScriptVO.getIvrtext()) ? ivrTaskTemplateScriptVO.getIvrtext() : ivrTaskTemplateScriptVO.getScriptContent();
        Integer matched = -1;
        log.info("AI匹配:url = {},questionText = {},voiceText = {},options = {},uuid ={}",
                url,questionText,voiceText,options,uuid);
        matched = matchOptionIndex(url, questionText, voiceText, options, uuid);
        //说明匹配正确了
        if (matched != null && matched >= 0) {
@@ -5365,7 +6630,8 @@
                phoneCallBackYQVO.setValue(phoneCallBackYQVO.getCommonValue() + serviceTask.getJsy());
                //记录状态
                setFailPreachForm(serviceSubtask, "3", "电话拨打已完成", "9");
                return phoneCallBackYQVO;
                back = phoneCallBackYQVO;
                return back;
            }
            flag = 1;
@@ -5373,9 +6639,10 @@
            redisCache.deleteObject(phoneCallReqYQVO.getUuid() + "PlayEventCallbackPlaystop");
//                        //获取下一题
            log.error("获取下一题的信息:{}", ivrTaskTemplateScriptVO);
            if (ivrTaskTemplateScriptVO.getBranchFlag().equals("1") || ivrTaskTemplateScriptVO.getBranchFlag().equals("0") && ivrTaskTemplateScriptVO.getNextScriptno() != null && ivrTaskTemplateScriptVO.getNextScriptno() != 0) {
            //branchFlag为null时按分支0处理,避免NPE
            if ("1".equals(ivrTaskTemplateScriptVO.getBranchFlag()) || "0".equals(ivrTaskTemplateScriptVO.getBranchFlag()) && ivrTaskTemplateScriptVO.getNextScriptno() != null && ivrTaskTemplateScriptVO.getNextScriptno() != 0) {
                Long nextQuestion = null;
                if (ivrTaskTemplateScriptVO.getBranchFlag().equals("1")) {
                if ("1".equals(ivrTaskTemplateScriptVO.getBranchFlag())) {
                    nextQuestion = chosenOption.getNextQuestion();
                    //更新分数
                    double score = redisCache.getCacheObject(phoneCallReqYQVO.getUuid() + "SCORE");
@@ -5408,15 +6675,9 @@
                    redisCache.setCacheObject(phoneCallReqYQVO.getUuid() + "- jsy", serviceTask.getJsy(), 120, TimeUnit.MINUTES);
                    phoneCallBackYQVO.setType("text");
                    phoneCallBackYQVO.setValue(phoneCallBackYQVO.getCommonValue() + serviceTask.getJsy());
                    //将结果写进detail表
                    ServiceSubTaskDetailReq ssdReq = new ServiceSubTaskDetailReq();
                    List<ServiceSubtaskDetail> serviceSubtaskDetailList2 = new ArrayList<>();
                    serviceSubtaskDetailList.add(getServiceSubtaskDetail(phoneCallReqYQVO, ivrTaskTemplateScriptVO, serviceSubtask, ivrTaskTemplate));
                    serviceSubTaskDetailReq.setServiceSubtaskDetailList(serviceSubtaskDetailList2);
                    ssdReq.setGuid(phoneCallReqYQVO.getGuid());
                    ssdReq.setOrgid(phoneCallReqYQVO.getOrgid());
                    saveQuestionAnswerPhone(ssdReq);
                    return phoneCallBackYQVO;
                    //明细在本题匹配成功时已落库(见上方 saveQuestionAnswerPhone),这里不再重复保存
                    back = phoneCallBackYQVO;
                    return back;
                }
                for (IvrTaskTemplateScript script : ivrTaskTemplateScripts) {
@@ -5433,6 +6694,15 @@
                        redisCache.deleteObject(phoneCallReqYQVO.getTaskid().trim() + "&&" + "mate" + "&&" + phoneCallReqYQVO.getUuid());
                    }
                }
                //下一题脚本没找到时,兜底重问当前题,避免调用方误判为未处理而退回正则识别
                if (StringUtils.isEmpty(phoneCallBackYQVO.getValue())) {
                    log.error("下一题脚本未找到,重问当前题,nextQuestion:{}", nextQuestion);
                    phoneCallBackYQVO.setType("text");
                    phoneCallBackYQVO.setSilent_interval(ivrTaskTemplate.getSilencetime().intValue());
                    phoneCallBackYQVO.setValue(phoneCallBackYQVO.getCommonValue() + getObject(serviceSubtask, questionText));
                }
                back = phoneCallBackYQVO;
                return back;
            } else if (ivrTaskTemplateScriptVO.getNextScriptno() == null || ivrTaskTemplateScriptVO.getNextScriptno() == 0) {
                ServiceTask serviceTask1 = serviceTaskService.selectServiceTaskByTaskid(serviceSubtask.getTaskid());
                phoneCallBackYQVO.setType("text");
@@ -5461,46 +6731,152 @@
                //在redis中保存一下结束语,在调用挂电话的方法时删除
                ServiceTask serviceTask = serviceTaskService.selectServiceTaskByTaskid(serviceSubtask.getTaskid());
                redisCache.setCacheObject(phoneCallReqYQVO.getUuid() + "- jsy", serviceTask.getJsy(), 120, TimeUnit.MINUTES);
//                                return phoneCallBackYQVO;
                //结束语已拼进返回值,挂机由平台按返回值执行
                back = phoneCallBackYQVO;
                return back;
            }
        } else {
            log.info("没有匹配上----------------------------");
            //flag=0,说明没 匹配上,也要把患者说的话记录下来
            if (matched == ivrTaskTemplateScriptVO.getIvrTaskScriptTargetoptionList().size() - 1 && flag == 0) {
                ServiceSubTaskDetailReq serviceSubTaskDetailReq = new ServiceSubTaskDetailReq();
                List<ServiceSubtaskDetail> serviceSubtaskDetailList = new ArrayList<>();
                ServiceSubtaskDetail serviceSubtaskDetail = getServiceSubtaskDetail(phoneCallReqYQVO, ivrTaskTemplateScriptVO, serviceSubtask, ivrTaskTemplate);
                //修改一下语音路径(改成前端可以访问的,存到数据库中)
                if (StringUtils.isNotEmpty(serviceSubtaskDetail.getQuestionvoice())) {
                    String questionvoice = serviceSubtaskDetail.getQuestionvoice();
                    String[] split = questionvoice.split("\\\\");
                    if (split.length > 0) {
                        String lastPart = split[split.length - 1];
                        serviceSubtaskDetail.setQuestionvoice(voicePathPrefix + lastPart);
            //AI没有匹配上:由AI分支自己按"没问清就重问"的次数处理,不再退回正则识别
            log.info("ai没有匹配上----------------------------");
            //没匹配上也要把患者说的话记录下来(matchedtext置空,与正则路径口径一致)
            ServiceSubTaskDetailReq serviceSubTaskDetailReq = new ServiceSubTaskDetailReq();
            List<ServiceSubtaskDetail> serviceSubtaskDetailList = new ArrayList<>();
            ServiceSubtaskDetail serviceSubtaskDetail = getServiceSubtaskDetail(phoneCallReqYQVO, ivrTaskTemplateScriptVO, serviceSubtask, ivrTaskTemplate);
            //修改一下语音路径(改成前端可以访问的,存到数据库中)
            if (StringUtils.isNotEmpty(serviceSubtaskDetail.getQuestionvoice())) {
                String questionvoice = serviceSubtaskDetail.getQuestionvoice();
                String[] split = questionvoice.split("\\\\");
                if (split.length > 0) {
                    String lastPart = split[split.length - 1];
                    serviceSubtaskDetail.setQuestionvoice(voicePathPrefix + lastPart);
                }
            }
            serviceSubtaskDetailList.add(serviceSubtaskDetail);
            //如果没有 匹配上,这个必须为null
            serviceSubtaskDetailList.get(0).setMatchedtext("");
            serviceSubTaskDetailReq.setServiceSubtaskDetailList(serviceSubtaskDetailList);
            serviceSubTaskDetailReq.setGuid(phoneCallReqYQVO.getGuid());
            serviceSubTaskDetailReq.setOrgid(phoneCallReqYQVO.getOrgid());
            saveQuestionAnswerPhone(serviceSubTaskDetailReq);
            String mateKey = phoneCallReqYQVO.getTaskid().trim() + "&&" + "mate" + "&&" + phoneCallReqYQVO.getUuid();
            Integer count = null;
            Object countObj = redisCache.getCacheObject(mateKey);
            if (ObjectUtils.isNotEmpty(countObj)) count = (Integer) countObj;
            if (count != null && count >= ivrTaskTemplate.getMateNum()) {
                //没匹配次数已经用满,不能再重问了
                boolean noNextQuestion = ("0".equals(ivrTaskTemplateScriptVO.getBranchFlag()) || "1".equals(ivrTaskTemplateScriptVO.getBranchFlag()))
                        && (ivrTaskTemplateScriptVO.getNextScriptno() == null || ivrTaskTemplateScriptVO.getNextScriptno() == 0);
                if (noNextQuestion) {
                    //已经是最后一题,直接挂机
                    ServiceTask serviceTask1 = serviceTaskService.selectServiceTaskByTaskid(serviceSubtask.getTaskid());
                    phoneCallBackYQVO.setType("text");
                    phoneCallBackYQVO.setSilent_interval(ivrTaskTemplate.getSilencetime().intValue());
                    phoneCallBackYQVO.setValue(phoneCallBackYQVO.getCommonValue() + serviceTask1.getJsy());
                    //更新一下分数
                    Double score = null;
                    Object scoreObj = redisCache.getCacheObject(phoneCallReqYQVO.getUuid() + "SCORE");
                    if (ObjectUtils.isNotEmpty(scoreObj)) score = (Double) scoreObj;
                    serviceSubtask.setScore(String.valueOf(score));
                    serviceSubtask.setFinishtime(new Date());
                    serviceSubtask.setSendstate(6L);
                    serviceSubtask.setRemark("电话拨打已完成");
                    serviceSubtaskMapper.updateServiceSubtask(serviceSubtask);
                    //记录状态
                    setFailPreachForm(serviceSubtask, "3", "电话拨打已完成", "9");
                    //在redis中保存一下结束语,在调用挂电话的方法时删除
                    ServiceTask serviceTask = serviceTaskService.selectServiceTaskByTaskid(serviceSubtask.getTaskid());
                    redisCache.setCacheObject(phoneCallReqYQVO.getUuid() + "- jsy", serviceTask.getJsy(), 120, TimeUnit.MINUTES);
                    //去redis中,把该子任务ID删除
                    Long id = serviceSubtask.getId();
                    Map<String, String> map = delRedisValue(null, id.toString());
                    if (ObjectUtils.isNotEmpty(map)) {
                        redisCache.setCacheObject(map.get("cacheName"), map.get("val"));
                        redisCache.deleteObject(serviceSubtask.getId() + "-" + serviceSubtask.getPhone());
                        redisCache.deleteObject(phoneCallReqYQVO.getUuid() + "SCORE");
                    }
                } else {
                    //还有下一题,按nextScriptno继续提问
                    for (IvrTaskTemplateScript script : ivrTaskTemplateScripts) {
                        if (script.getSort() == ivrTaskTemplateScriptVO.getNextScriptno().intValue()) {
                            phoneCallBackYQVO.setType("text");
                            phoneCallBackYQVO.setSilent_interval(ivrTaskTemplate.getSilencetime().intValue());
                            String scriptContent = StringUtils.isNotEmpty(script.getIvrtext()) ? script.getIvrtext() : script.getScriptContent();
                            phoneCallBackYQVO.setValue(phoneCallBackYQVO.getCommonValue() + getObject(serviceSubtask, scriptContent));
                            //将该患者的Redis中的题目ID,进行修改
                            redisCache.setCacheObject(phoneCallReqYQVO.getTaskid().trim() + "-" + phoneCallReqYQVO.getPhone().trim(), script.getId().toString(), 120, TimeUnit.MINUTES);
                            //更新一下分数
                            Double score = null;
                            Object scoreObj = redisCache.getCacheObject(phoneCallReqYQVO.getUuid() + "SCORE");
                            if (ObjectUtils.isNotEmpty(scoreObj)) score = (Double) scoreObj;
                            score = BigDecimal.valueOf(score).add(new BigDecimal(script.getScore())).doubleValue();
                            redisCache.setCacheObject(phoneCallReqYQVO.getUuid() + "SCORE", score, 120, TimeUnit.MINUTES);
                            //换题成功,没匹配次数清零
                            redisCache.deleteObject(mateKey);
                        }
                    }
                }
                serviceSubtaskDetailList.add(serviceSubtaskDetail);
                //如果没有 匹配上,这个必须为null
                serviceSubtaskDetailList.get(0).setMatchedtext("");
                serviceSubTaskDetailReq.setServiceSubtaskDetailList(serviceSubtaskDetailList);
                serviceSubTaskDetailReq.setGuid(phoneCallReqYQVO.getGuid());
                serviceSubTaskDetailReq.setOrgid(phoneCallReqYQVO.getOrgid());
                saveQuestionAnswerPhone(serviceSubTaskDetailReq);
            } else {
                //还没问满次数,用noMatchText引导患者重答
                redisCache.setCacheObject(mateKey, count == null ? 1 : count + 1, 120, TimeUnit.MINUTES);
                phoneCallBackYQVO.setType("text");
                phoneCallBackYQVO.setSilent_interval(ivrTaskTemplate.getSilencetime().intValue());
                phoneCallBackYQVO.setValue(ivrTaskTemplateScriptVO.getNoMatchText() + getObject(serviceSubtask, StringUtils.isNotEmpty(ivrTaskTemplateScriptVO.getIvrtext()) ? ivrTaskTemplateScriptVO.getIvrtext() : ivrTaskTemplateScriptVO.getScriptContent()));
            }
            back = phoneCallBackYQVO;
            return back;
        }
        return back;
    }
    /**
     * 问题结果占比
     *
     * @param sltdMydTotalVO
     * @param serviceSubtaskRes
     * @return
     */
    public List<ServiceSubtaskDetailRatioExport> getDetailRatio(SltdMydTotalVO sltdMydTotalVO, List<ServiceSubtaskRes> serviceSubtaskRes) {
        List<ServiceSubtaskDetailRatioExport> serviceSubtaskDetailRatioExports = null;
        List<String> serviceTypeList = sltdMydTotalVO.getServiceTypeList();
        if (CollectionUtils.isEmpty(serviceTypeList)) {
            log.warn("getDetailRatio 未传 serviceTypeList,无法统计问题占比");
            return serviceSubtaskDetailRatioExports;
        }
        // 判断口径:2=随访(按 taskid 统计),6/14=满意度(按 subtask id 统计)
        boolean hasFollowUp = serviceTypeList.contains("2");
        boolean hasSatisfaction = serviceTypeList.contains("6") || serviceTypeList.contains("14");
        if (hasFollowUp && hasSatisfaction) {
            //serviceType,即有随访又有满意度,暂时没法统计
            log.warn("getDetailRatio 暂不支持同时统计随访(2)与满意度(6/14),serviceTypeList={}", serviceTypeList);
            return serviceSubtaskDetailRatioExports;
        }
        if (hasFollowUp) {
            //获取serviceSubtaskList中的所有taskid
            List<Long> taskIds = serviceSubtaskRes.stream().map(ServiceSubtaskRes::getTaskid).filter(ObjectUtils::isNotEmpty).distinct().collect(Collectors.toList());
            //同时带上本次导出的子任务 id:让「问题详情占比」只统计这批患者,与「患者随访信息表单」口径一致
            List<Long> subtaskIds = serviceSubtaskRes.stream().map(ServiceSubtaskRes::getId).filter(ObjectUtils::isNotEmpty).distinct().collect(Collectors.toList());
            serviceSubtaskDetailRatioExports = statQuestionOption(taskIds, sltdMydTotalVO.getStartFinishTime(), sltdMydTotalVO.getEndFinishTime(), sltdMydTotalVO.getStartOutHospTime(), sltdMydTotalVO.getEndOutHospTime(), sltdMydTotalVO.getQuestionContent(), sltdMydTotalVO.getStartScore(), sltdMydTotalVO.getEndScore(), sltdMydTotalVO.getValueType(), subtaskIds);
        } else if (hasSatisfaction) {
            //满意度统计 (通过 subtask 的 id 去统计)
            List<Long> subtaskIds = serviceSubtaskRes.stream().map(ServiceSubtaskRes::getId).collect(Collectors.toList());
            serviceSubtaskDetailRatioExports = statQuestionOptionBySubtaskIds(subtaskIds, sltdMydTotalVO.getStartOutHospTime(), sltdMydTotalVO.getEndOutHospTime(), sltdMydTotalVO.getStartFinishTime(), sltdMydTotalVO.getEndFinishTime(), sltdMydTotalVO.getQuestionContent(), sltdMydTotalVO.getStartScore(), sltdMydTotalVO.getEndScore(), sltdMydTotalVO.getValueType());
        } else {
            log.warn("getDetailRatio 暂不支持的 serviceTypeList={}(仅支持 2 或 6/14)", serviceTypeList);
        }
        return serviceSubtaskDetailRatioExports;
    }
    //获取任务组信息
    private void findServiceTaskScheduleVO(ServiceTaskVO serviceTaskVO){
        if(StringUtils.isNotEmpty(serviceTaskVO.getAppltype()) && serviceTaskVO.getAppltype().equals("5")){
    private void findServiceTaskScheduleVO(ServiceTaskVO serviceTaskVO) {
        if (StringUtils.isNotEmpty(serviceTaskVO.getAppltype()) && serviceTaskVO.getAppltype().equals("5")) {
            //任务组信息
            ServiceTaskSchedule schedule = serviceTaskScheduleService.selectByTaskid(serviceTaskVO.getTaskid());
            if (ObjectUtils.isNotEmpty(schedule)) {
                ServiceTaskScheduleVO serviceTaskScheduleVO = DtoConversionUtils.sourceToTarget(schedule, ServiceTaskScheduleVO.class);
                List<ServiceTaskScheduleDetail> scheduleDetailList =
                        serviceTaskScheduleService.selectDetailByScheduleid(schedule.getId());
                List<ServiceTaskScheduleDetail> scheduleDetailList = serviceTaskScheduleService.selectDetailByScheduleid(schedule.getId());
                serviceTaskScheduleVO.setDetailList(scheduleDetailList);
                serviceTaskVO.setServiceTaskScheduleVO(serviceTaskScheduleVO);
            }
@@ -5532,4 +6908,341 @@
        }
        log.info("ai匹配成功,匹配结果是:" + matchedText);
    }
    private static String trimAll(String s) {
        if (s == null) {
            return "";
        }
        int start = 0;
        int end = s.length();
        while (start < end && isBlankChar(s.charAt(start))) {
            start++;
        }
        while (end > start && isBlankChar(s.charAt(end - 1))) {
            end--;
        }
        return s.substring(start, end);
    }
    private static Boolean isBlankChar(char c) {
        return c == '\u3000'          // 全角空格
                || c == ' '            // 半角空格
                || c == '\t' || c == '\n' || c == '\r' || c == '\f' || Character.isWhitespace(c);
    }
    private String buildKey(String groupName, String questionText, String option) {
        return groupName + "\u0001" + questionText + "\u0001" + option;
    }
    private static int parseCount(String s) {
        if (StringUtils.isEmpty(s)) {
            return 0;
        }
        try {
            return Integer.parseInt(s.trim());
        } catch (NumberFormatException e) {
            return 0;
        }
    }
    private List<MydTrendReqDTO> getWeekDate(MydTrendReqVO mydTrendReqVO, List<MydTrendReqDTO> list) {
        // 1. 计算总周数(和 SQL 里的公式保持一致)
        long days = (mydTrendReqVO.getEndFinishTime().getTime() - mydTrendReqVO.getStartFinishTime().getTime()) / (1000L * 60 * 60 * 24);
        int totalWeeks = (int) (days / 7) + 1;
        // 2. 已有数据:period -> totalScore
        Map<Integer, String> exist = new HashMap<>();
        for (MydTrendReqDTO row : list) {
            // period 是数字,可能是 Integer / Long / BigDecimal,统一转 int
            int p = Integer.parseInt(StringUtils.isNotEmpty(row.getPeriod()) ? row.getPeriod() : "0");
            exist.put(p, row.getTotalScore() != null ? row.getTotalScore() : "0");
            // 下面这行按你的原逻辑保留(虽然看起来有点多余)
            exist.put(p, String.valueOf(row.getTotalScore() != null ? row.getTotalScore() : 0));
        }
        // 3. 补全 1..totalWeeks
        List<MydTrendReqDTO> result = new ArrayList<>(totalWeeks);
        // 获取整体的开始时间
        long startTimeMillis = mydTrendReqVO.getStartFinishTime().getTime();
        long endTimeMillis = mydTrendReqVO.getEndFinishTime().getTime();
        long oneWeekMillis = 7L * 24 * 60 * 60 * 1000; // 一周的毫秒数
        for (int i = 1; i <= totalWeeks; i++) {
            MydTrendReqDTO row = new MydTrendReqDTO();
            row.setPeriod(String.valueOf(i));
            row.setTotalScore(exist.getOrDefault(i, "0"));
            // -------- 新增:设置每周的 startDate 和 endDate --------
            // 当前周开始时间 = 整体开始时间 + (i - 1) * 7天
            long currentStartMillis = startTimeMillis + (long) (i - 1) * oneWeekMillis;
            // 当前周结束时间 = 当前周开始时间 + 7天 - 1毫秒(保证是这一周的最后一刻)
            long currentEndMillis = currentStartMillis + oneWeekMillis - 1;
            // 如果是最后一周,结束时间不能超过整体的 endTime
            if (i == totalWeeks) {
                currentEndMillis = endTimeMillis;
            }
            row.setStartDate(new Date(currentStartMillis));
            row.setEndDate(new Date(currentEndMillis));
            // ----------------------------------------------------
            result.add(row);
        }
        return result;
    }
    private List<MydTrendReqDTO> getYearDate(MydTrendReqVO mydTrendReqVO, List<MydTrendReqDTO> list) {
        // 获取整体开始和结束时间
        Date startTime = mydTrendReqVO.getStartFinishTime();
        Date endTime = mydTrendReqVO.getEndFinishTime();
        // 1. 计算年份范围
        // 使用 Calendar 获取起始年份和结束年份
        Calendar cal = Calendar.getInstance();
        cal.setTime(startTime);
        int startYear = cal.get(Calendar.YEAR);
        cal.setTime(endTime);
        int endYear = cal.get(Calendar.YEAR);
        // 总年数 (包含首尾)
        int totalYears = endYear - startYear + 1;
        // 2. 已有数据:period -> totalScore (假设 period 存的是年份字符串,如 "2024")
        Map<String, String> exist = new HashMap<>();
        for (MydTrendReqDTO row : list) {
            String period = row.getPeriod() != null ? row.getPeriod() : "";
            exist.put(period, row.getTotalScore() != null ? row.getTotalScore() : "0");
        }
        // 3. 补全所有年份
        List<MydTrendReqDTO> result = new ArrayList<>(totalYears);
        for (int i = 0; i < totalYears; i++) {
            int currentYear = startYear + i;
            String periodKey = String.valueOf(currentYear);
            MydTrendReqDTO row = new MydTrendReqDTO();
            row.setPeriod(periodKey);
            // 如果没有该年份的数据,默认给 "0"
            row.setTotalScore(exist.getOrDefault(periodKey, "0"));
            // -------- 设置该年份的 startDate 和 endDate --------
            Calendar yearCal = Calendar.getInstance();
            // 设置为该年的 1月1日 00:00:00
            yearCal.set(currentYear, Calendar.JANUARY, 1, 0, 0, 0);
            yearCal.set(Calendar.MILLISECOND, 0);
            row.setStartDate(yearCal.getTime());
            // 设置为该年的 12月31日 23:59:59
            yearCal.set(currentYear, Calendar.DECEMBER, 31, 23, 59, 59);
            yearCal.set(Calendar.MILLISECOND, 999);
            row.setEndDate(yearCal.getTime());
            // ----------------------------------------------------
            result.add(row);
        }
        return result;
    }
    private List<MydTrendReqDTO> getMonthDate(MydTrendReqVO mydTrendReqVO, List<MydTrendReqDTO> list) {
        // 获取整体开始和结束时间
        Date startTime = mydTrendReqVO.getStartFinishTime();
        Date endTime = mydTrendReqVO.getEndFinishTime();
        // 1. 计算月份范围
        Calendar cal = Calendar.getInstance();
        cal.setTime(startTime);
        int startYear = cal.get(Calendar.YEAR);
        int startMonth = cal.get(Calendar.MONTH); // 注意:Calendar.MONTH 从 0 开始
        cal.setTime(endTime);
        int endYear = cal.get(Calendar.YEAR);
        int endMonth = cal.get(Calendar.MONTH);
        // 总月数 = (结束年 - 开始年) * 12 + (结束月 - 开始月) + 1
        int totalMonths = (endYear - startYear) * 12 + (endMonth - startMonth) + 1;
        // 2. 已有数据:period -> totalScore (period 存的是月份字符串,如 "2024-06")
        Map<String, String> exist = new HashMap<>();
        for (MydTrendReqDTO row : list) {
            String period = row.getPeriod() != null ? row.getPeriod() : "";
            exist.put(period, row.getTotalScore() != null ? row.getTotalScore() : "0");
        }
        // 3. 补全所有月份
        List<MydTrendReqDTO> result = new ArrayList<>(totalMonths);
        Calendar monthCal = Calendar.getInstance();
        monthCal.set(startYear, startMonth, 1, 0, 0, 0);
        monthCal.set(Calendar.MILLISECOND, 0);
        for (int i = 0; i < totalMonths; i++) {
            int currentYear = monthCal.get(Calendar.YEAR);
            int currentMonth = monthCal.get(Calendar.MONTH) + 1; // 转成 1-12 月
            // 拼接 period,格式:yyyy-MM,比如 "2024-06"
            // 如果你希望是 "2024-6",可以把 String.format 改成 currentMonth
            String periodKey = String.format("%04d-%02d", currentYear, currentMonth);
            MydTrendReqDTO row = new MydTrendReqDTO();
            row.setPeriod(periodKey);
            row.setTotalScore(exist.getOrDefault(periodKey, "0"));
            // -------- 设置该月的 startDate 和 endDate --------
            // 当月开始时间:1号 00:00:00.000
            Calendar startCal = (Calendar) monthCal.clone();
            row.setStartDate(startCal.getTime());
            // 当月结束时间:下个月1号 00:00:00.000 减 1 毫秒
            Calendar endCal = (Calendar) monthCal.clone();
            endCal.add(Calendar.MONTH, 1);
            endCal.add(Calendar.MILLISECOND, -1);
            row.setEndDate(endCal.getTime());
            // ----------------------------------------------------
            result.add(row);
            // 进入下一个月
            monthCal.add(Calendar.MONTH, 1);
        }
        return result;
    }
    private List<MydTrendReqDTO> getDayDate(MydTrendReqVO mydTrendReqVO, List<MydTrendReqDTO> list) {
        // 获取整体开始和结束时间
        Date startTime = mydTrendReqVO.getStartFinishTime();
        Date endTime = mydTrendReqVO.getEndFinishTime();
        // 1. 计算总天数
        long oneDayMillis = 24L * 60 * 60 * 1000;
        // 注意:这里只算日期差,不考虑时分秒,否则可能差一天
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(startTime);
        startCal.set(Calendar.HOUR_OF_DAY, 0);
        startCal.set(Calendar.MINUTE, 0);
        startCal.set(Calendar.SECOND, 0);
        startCal.set(Calendar.MILLISECOND, 0);
        Calendar endCal = Calendar.getInstance();
        endCal.setTime(endTime);
        endCal.set(Calendar.HOUR_OF_DAY, 0);
        endCal.set(Calendar.MINUTE, 0);
        endCal.set(Calendar.SECOND, 0);
        endCal.set(Calendar.MILLISECOND, 0);
        long days = (endCal.getTimeInMillis() - startCal.getTimeInMillis()) / oneDayMillis;
        int totalDays = (int) days + 1;
        // 2. 已有数据:period -> totalScore (period 存的是日期字符串,如 "2024-06-01")
        Map<String, String> exist = new HashMap<>();
        for (MydTrendReqDTO row : list) {
            String period = row.getPeriod() != null ? row.getPeriod() : "";
            exist.put(period, row.getTotalScore() != null ? row.getTotalScore() : "0");
        }
        // 3. 补全所有日期
        List<MydTrendReqDTO> result = new ArrayList<>(totalDays);
        Calendar dayCal = (Calendar) startCal.clone();
        for (int i = 0; i < totalDays; i++) {
            // 拼接 period,格式:yyyy-MM-dd
            String periodKey = String.format("%04d-%02d-%02d", dayCal.get(Calendar.YEAR), dayCal.get(Calendar.MONTH) + 1, dayCal.get(Calendar.DAY_OF_MONTH));
            MydTrendReqDTO row = new MydTrendReqDTO();
            row.setPeriod(periodKey);
            row.setTotalScore(exist.getOrDefault(periodKey, "0"));
            // -------- 设置该天的 startDate 和 endDate --------
            Calendar startOfDay = (Calendar) dayCal.clone();
            row.setStartDate(startOfDay.getTime());
            Calendar endOfDay = (Calendar) dayCal.clone();
            endOfDay.set(Calendar.HOUR_OF_DAY, 23);
            endOfDay.set(Calendar.MINUTE, 59);
            endOfDay.set(Calendar.SECOND, 59);
            endOfDay.set(Calendar.MILLISECOND, 999);
            row.setEndDate(endOfDay.getTime());
            // ----------------------------------------------------
            result.add(row);
            // 进入下一天
            dayCal.add(Calendar.DAY_OF_MONTH, 1);
        }
        return result;
    }
    /**
     * 门诊满意度综合得分排名(按科室或病区)
     * <p>
     * 综合满意度 = Σ(评分明细权重) / 评分明细条数 × 100%,
     * 权重只取 1、0.8、0.6、0.4、0.2 五档(很满意、满意、一般、不满意、很不满意)。
     *
     * @param mzMydScoreRankVO 查询条件
     * @return 排名结果,名次从 1 开始顺序编号
     */
    @Override
    public List<MzMydScoreRankDTO> mzMydScoreRank(MzMydScoreRankVO mzMydScoreRankVO) {
        if (StringUtils.isEmpty(mzMydScoreRankVO.getDimensionType())) {
            mzMydScoreRankVO.setDimensionType("1");
        }
        if (CollectionUtils.isEmpty(mzMydScoreRankVO.getServiceTypes())) {
          List<String> list=new ArrayList<>(Arrays.asList("14"));
            mzMydScoreRankVO.setServiceTypes(list);
        }
        List<MzMydScoreRankDTO> list = serviceSubtaskMapper.selectMzMydScoreRank(mzMydScoreRankVO);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        // 名次:SQL 已按综合得分降序返回,这里顺序编号
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRank(i + 1);
        }
        return list;
    }
    private String getWXCode(String idcard, String url, String taskName, String taskDesc, String phone, String setPatientname, String setPatientid, List<String> wxqqxx) {
        XinHuaWXReq xinHuaWXReq = new XinHuaWXReq();
        xinHuaWXReq.setIdcard(idcard);
        xinHuaWXReq.setUrl(url);
        xinHuaWXReq.setPatientid(setPatientid);
        xinHuaWXReq.setPatientname(setPatientname);
        xinHuaWXReq.setMobile(phone);
        xinHuaWXReq.setMedcardno(null);
        xinHuaWXReq.setTitlename(taskName);
        xinHuaWXReq.setContent(taskDesc);
        xinHuaWXReq.setAppid(wxqqxx.get(1));
        log.info("【getWXCode】微信公众号请求参数:{}", xinHuaWXReq);
        String body = new Gson().toJson(xinHuaWXReq);
        String encode = encode(wxqqxx.get(2).concat(body));
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("sign", encode);
        String result = HttpUtils.sendPostByHeader(wxqqxx.get(3), body, headerMap);
        log.info("【getWXCode】微信公众号返回参数:{}", result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = (String) jsonObject.toString();
        return code;
    }
    public String encode(String arg) {
        if (arg == null) {
            arg = "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(arg.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toHex(md5.digest());
    }
}