liusheng
2026-10-12 26d1f59f0266672398975ba0337bb3d8267c2d95
smartor/src/main/java/com/smartor/service/impl/ServiceSubtaskServiceImpl.java
@@ -9,25 +9,24 @@
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.satisfaction.api.SatisfactionFacade;
import com.ruoyi.message.sms.provider.sltd.ws.MessageSend;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.sms.smsUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.message.SendResult;
import com.ruoyi.message.sms.SmsSendRequest;
import com.ruoyi.message.sms.SmsSenderFactory;
import com.ruoyi.message.wechat.WechatSendRequest;
import com.ruoyi.message.wechat.WechatSenderFactory;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.service.ISysConfigService;
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.DTO.*;
import com.smartor.domain.*;
import com.smartor.domain.VO.*;
import com.smartor.domain.entity.ServiceSubtaskEntity;
@@ -74,6 +73,16 @@
@Slf4j
@Service
public class ServiceSubtaskServiceImpl implements IServiceSubtaskService {
    /**
     * 满意度模块对外门面(常驻 Bean)。
     * <p>
     * 随访统计里的「满意度指数」({@code getSfStatisticsJoy})只能通过它取数;
     * 满意度模块关闭时门面返回全零 Map,不影响随访统计的其它字段与启动。
     */
    @Autowired
    private SatisfactionFacade satisfactionFacade;
    @Autowired
    private ServiceSubtaskMapper serviceSubtaskMapper;
@@ -170,10 +179,16 @@
    private ISysConfigService configService;
    @Autowired
    private MtSubmitSmUtil mtSubmitSmUtil;
    private SysConfigMapper sysConfigMapper;
    /**
     * 消息发送方工厂(短信/微信公众号),替代原来直接调用各站点发送代码的写法
     */
    @Autowired
    private SmsSenderFactory smsSenderFactory;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    private WechatSenderFactory wechatSenderFactory;
    @Autowired
    private RedisTemplate redisTemplate;
@@ -195,9 +210,6 @@
    @Value("${req_path}")
    private String req_path;
    @Value("${xhsmsPath}")
    private String xhsmsPath;
    @Value("${phoneUpEveryHour}")
    private Integer phoneUpEveryHour;
@@ -603,7 +615,6 @@
//        return map;
//    }
    /**
     * 统计任务各种状态的数量(已优化)
     * 优化说明:
@@ -850,7 +861,6 @@
            svyTaskTemplateService.deleteSvyTaskTemplateBySvyid(serviceSubtask.getTemplateid());
        } else if (serviceSubtask.getType().equals("1"))
            ivrTaskTemplateService.deleteIvrTaskTemplateByID(serviceSubtask.getTemplateid());
        String tempName = svyTaskTemplateService.selectSvyTaskTemplateBySvyid(Long.valueOf(taskTempid)).getSvyname();
        serviceSubtask.setTemplateid(taskTempid.longValue());
@@ -2470,7 +2480,6 @@
        return phoneCallBackYQVO;
    }
    private String getObject(ServiceSubtask serviceSubtask, String scriptContent) {
        Map<String, Map<String, String>> param = getParam(serviceSubtask.getTaskid());
        for (Map<String, String> map : param.values()) {
@@ -2487,7 +2496,6 @@
        return scriptContent;
    }
    /**
     * 获取任务里的通配符
@@ -2537,7 +2545,6 @@
        }
        return map;
    }
    /**
     * 雨绮任务拉取
@@ -2607,7 +2614,6 @@
        log.info("-----------实际拉取的电话数据量:{}", CollectionUtils.isNotEmpty(pullTaskVOList) ? pullTaskVOList.size() : null);
        return pullTaskVOList;
    }
    private List<PullTaskVO> getPullTaskList(List<String> subIds, String cacheName) {
        log.error("任务拉取subIds的值是多少:{}", subIds);
@@ -2680,7 +2686,6 @@
        return pullTaskVOList;
    }
    @Override
    public Integer saveQuestionAnswerPhone(ServiceSubTaskDetailReq serviceSubTaskDetailReq) {
@@ -2940,7 +2945,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";
@@ -3062,6 +3067,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())) {
@@ -3076,7 +3083,6 @@
        }
        return jsRates;
    }
    public List<ServiceSubtaskStatistic> getSfStatisticsExport(ServiceSubtaskCountReq serviceSubtaskCountReq) {
        List<ServiceSubtaskStatistic> sfStatistics = getSfStatistics(serviceSubtaskCountReq);
@@ -3153,6 +3159,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)) {
@@ -3162,13 +3170,15 @@
        if (CollectionUtils.isNotEmpty(serviceSubtaskStatistics)) {
            for (ServiceSubtaskStatistic serviceSubtaskStatistic : serviceSubtaskStatistics) {
                //所有满意度数量
                //满意度模块化后:满意度指数据此改为调用满意度模块门面;
                //模块关闭时门面返回全零 Map(与被迁移实现的实际输出一致),不影响随访统计其它字段。
                if (CollectionUtils.isNotEmpty(serviceSubtaskCountReq.getDeptcodes())) {
                    Map<String, Object> satisfactionIndex = getSatisfactionIndex("1", serviceSubtaskStatistic.getDeptcode(), orgid, serviceSubtaskCountReq.getIvrCategoryid(), serviceSubtaskCountReq.getSvyCategoryid());
                    Map<String, Object> satisfactionIndex = satisfactionFacade.getSatisfactionIndex("1", serviceSubtaskStatistic.getDeptcode(), orgid, serviceSubtaskCountReq.getIvrCategoryid(), serviceSubtaskCountReq.getSvyCategoryid());
                    serviceSubtaskStatistic.setJoyAllCount(satisfactionIndex.get("mydtmzl") != null ? (Integer) satisfactionIndex.get("mydtmzl") : 0);
                    serviceSubtaskStatistic.setJoyCount(satisfactionIndex.get("mydtbl") != null ? (Integer) satisfactionIndex.get("mydtbl") : 0);
                    serviceSubtaskStatistic.setJoyTotal((Double) satisfactionIndex.get("wcbl"));
                } else if (CollectionUtils.isNotEmpty(serviceSubtaskCountReq.getLeavehospitaldistrictcodes())) {
                    Map<String, Object> satisfactionIndex = getSatisfactionIndex("2", serviceSubtaskStatistic.getLeavehospitaldistrictcode(), orgid, serviceSubtaskCountReq.getIvrCategoryid(), serviceSubtaskCountReq.getSvyCategoryid());
                    Map<String, Object> satisfactionIndex = satisfactionFacade.getSatisfactionIndex("2", serviceSubtaskStatistic.getLeavehospitaldistrictcode(), orgid, serviceSubtaskCountReq.getIvrCategoryid(), serviceSubtaskCountReq.getSvyCategoryid());
                    serviceSubtaskStatistic.setJoyAllCount(satisfactionIndex.get("mydtmzl") != null ? (Integer) satisfactionIndex.get("mydtmzl") : 0);
                    serviceSubtaskStatistic.setJoyCount(satisfactionIndex.get("mydtbl") != null ? (Integer) satisfactionIndex.get("mydtbl") : 0);
                    serviceSubtaskStatistic.setJoyTotal((Double) satisfactionIndex.get("wcbl"));
@@ -3178,103 +3188,6 @@
        return serviceSubtaskStatistics;
    }
    /**
     * 获取满意度题目总量
     * type : 1-科室   2病区
     * code: 科室或病区code
     *
     * @return
     */
    private Map<String, Object> getSatisfactionIndex(String type, String code, String orgid, Long ivrCategoryid, Long svyCategoryid) {
        Map<String, Object> map = new HashMap<>();
        List<ServiceTask> serviceTasks = null;
        if (type.equals("1")) {
            ServiceTask serviceTask = new ServiceTask();
            serviceTask.setDeptcode(code);
            serviceTask.setOrgid(orgid);
            serviceTasks = serviceTaskService.selectServiceTaskList(serviceTask);
        } else if (type.equals("2")) {
            ServiceTask serviceTask = new ServiceTask();
            serviceTask.setLeavehospitaldistrictcode(code);
            serviceTask.setOrgid(orgid);
            serviceTasks = serviceTaskService.selectServiceTaskList(serviceTask);
        }
        //获取满意度题目总量
        BigDecimal mydtmzlsum = new BigDecimal(0);
        //获取满意度题目填报量
        BigDecimal mydtblsum = new BigDecimal(0);
        if (CollectionUtils.isNotEmpty(serviceTasks)) {
            //获取满意度题目总量
            for (ServiceTask serviceTask : serviceTasks) {
                if (serviceTask.getType().equals("1")) {
                    //语音
                    Long templateid = serviceTask.getTemplateid();
                    IvrTaskTemplateScript ivrTaskTemplateScript = new IvrTaskTemplateScript();
                    ivrTaskTemplateScript.setTemplateID(templateid);
                    ivrTaskTemplateScript.setOrgid(serviceTask.getOrgid());
                    //先默认为1吧,assortid=1  代表是满意度
                    ivrTaskTemplateScript.setScriptAssortid(ivrCategoryid);
                    List<IvrTaskTemplateScript> ivrTaskTemplateScripts = iIvrTaskTemplateScriptService.selectIvrTaskTemplateScriptList(ivrTaskTemplateScript);
                    if (CollectionUtils.isNotEmpty(ivrTaskTemplateScripts)) {
                        //需要先计算出发送量,再乘以单个问券满意度题目数量,得到满意度题目总量(包含了未做的)
                        ServiceSubtaskEntity serviceSubtaskVO = new ServiceSubtaskEntity();
                        serviceSubtaskVO.setTaskid(serviceTask.getTaskid());
                        List<Long> sendstates = new ArrayList<>(Arrays.asList(3L, 5L, 6L));
                        serviceSubtaskVO.setSendstates(sendstates);
                        List<ServiceSubtask> serviceSubtaskList = serviceSubtaskMapper.selectServiceSubtaskBySendstate(serviceSubtaskVO);
                        if (CollectionUtils.isNotEmpty(serviceSubtaskList)) {
                            int mydtmzlCount = ivrTaskTemplateScripts.size() * serviceSubtaskList.size();
                            mydtmzlsum.add(new BigDecimal(mydtmzlCount));
                        }
                    }
                } else if (serviceTask.getType().equals("2")) {
                    //问卷
                    SvyTaskTemplateScript svyTaskTemplateScript = new SvyTaskTemplateScript();
                    svyTaskTemplateScript.setTemplateID(serviceTask.getTemplateid());
                    svyTaskTemplateScript.setOrgid(serviceTask.getOrgid());
                    svyTaskTemplateScript.setCategoryid(svyCategoryid);
                    List<SvyTaskTemplateScript> svyTaskTemplateScriptList = svyTaskTemplateScriptService.selectSvyTaskTemplateScriptList(svyTaskTemplateScript);
                    if (CollectionUtils.isNotEmpty(svyTaskTemplateScriptList)) {
                        ServiceSubtaskEntity serviceSubtaskEntity = new ServiceSubtaskEntity();
                        serviceSubtaskEntity.setTaskid(serviceTask.getTaskid());
                        List<Long> sendstates = new ArrayList<>(Arrays.asList(3L, 5L, 6L));
                        serviceSubtaskEntity.setSendstates(sendstates);
                        List<ServiceSubtask> serviceSubtaskList = serviceSubtaskMapper.selectServiceSubtaskBySendstate(serviceSubtaskEntity);
                        if (CollectionUtils.isNotEmpty(serviceSubtaskList)) {
                            int mydtmzlCount = svyTaskTemplateScriptList.size() * serviceSubtaskList.size();
                            mydtmzlsum.add(new BigDecimal(mydtmzlCount));
                        }
                    }
                }
                //获取满意度题目填报量
                ServiceSubtaskDetail serviceSubtaskDetail = new ServiceSubtaskDetail();
                serviceSubtaskDetail.setTaskid(serviceTask.getTaskid());
                if (serviceTask.getType().equals("1")) serviceSubtaskDetail.setCategoryid(ivrCategoryid);
                if (serviceTask.getType().equals("2")) serviceSubtaskDetail.setCategoryid(svyCategoryid);
                serviceSubtaskDetail.setOrgid(serviceTask.getOrgid());
                List<ServiceSubtaskDetail> serviceSubtaskDetails = serviceSubtaskDetailMapper.selectServiceSubtaskDetailList(serviceSubtaskDetail);
                if (CollectionUtils.isNotEmpty(serviceSubtaskDetails))
                    mydtblsum.add(new BigDecimal(serviceSubtaskDetails.size()));
            }
        }
        //满意度题目总量
        map.put("mydtmzl", mydtmzlsum.intValue());
        map.put("mydtbl", mydtblsum.intValue());
        map.put("wcbl", 0.0);
        if (mydtmzlsum.intValue() != 0) {
            map.put("wcbl", mydtblsum.divide(mydtmzlsum, 2, RoundingMode.HALF_UP).doubleValue());
        }
        return map;
    }
    private ServiceSubtaskStatistic getStatistic(List<ServiceSubtask> serviceSubtaskList, String followUpCountStyle, Integer visitCount) {
        ServiceSubtaskStatistic serviceSubtaskStatistic = new ServiceSubtaskStatistic();
@@ -3906,7 +3819,6 @@
        return serviceSubtaskStatistic;
    }
    private ServiceSubtaskStatistic getStatisticJoy(List<ServiceSubtask> serviceSubtaskList, List<ServiceSubtaskCount> joySubCount) {
        ServiceSubtaskStatistic serviceSubtaskStatistic = new ServiceSubtaskStatistic();
        //格式化为两位小数的百分比
@@ -4029,7 +3941,6 @@
        if (subCounts == null) {
            subCounts = new ArrayList<>();
        }
        for (ServiceSubtask serviceSubtask : serviceSubtaskList) {
            List<ServiceSubtaskCount> subCountTemp = subCounts.stream().filter(r -> r.getSubTaskId().equals(serviceSubtask.getId())).collect(Collectors.toList());
@@ -4218,10 +4129,8 @@
        serviceOutPath.setUpdateTime(new Date());
        serviceOutPath.setUrl(url);
        iServiceOutPathService.updateServiceOutPath(serviceOutPath);
        Map<String, String> map = new HashMap<>();
        map.put("phone", serviceSubtask.getPhone());
        map.put("content", sendMagParam.getContent());
        HttpUtil.postJsonRequest(xhsmsPath, new Gson().toJson(map));
        //短信发送已收口到 ruoyi-message 模块;与原实现一致:不判断发送结果
        smsSenderFactory.send(active, SmsSendRequest.of(serviceSubtask.getPhone(), sendMagParam.getContent(), serviceSubtask.getOrgid()));
        redisCache.setCacheObject(subTaskId + "recordAccept-hungup", "1", 10, TimeUnit.MINUTES);
        if (StringUtils.isNotEmpty(serviceSubtask.getRemark()))
            serviceSubtask.setRemark("电话发送拒接,短信补偿发送成功");
@@ -4509,7 +4418,6 @@
        }
    }
    /**
     * 获取随访统计比例
     *
@@ -4731,7 +4639,6 @@
        return result;
    }
    /**
     * @param serviceSubtask
     * @param preachform
@@ -4762,7 +4669,6 @@
            serviceSubtaskPreachform1.setSendstate(failSendstate);
            serviceSubtaskPreachform1.setRemark(remark);
            serviceSubtaskPreachformMapper.updateServiceSubtaskPreachform(serviceSubtaskPreachform1);
            //如果当前的preachform已经是最后一个了,那直接将serviceSubtask的sendstate状态改成5就行了(全失败了)
            if (serviceSubtaskPreachform1.getSort() == spSize.size() && failSendstate.equals("4")) {
@@ -4809,7 +4715,6 @@
        }
        return visitTime;
    }
    /**
     * 计算总计行
@@ -5177,9 +5082,11 @@
            sendMagParam.setContent(smsContemt.replace("${wjurl}", sendMagParam.getUrl()));
        }
        //短信发送:各站点对接方式差异较大,已收口到 ruoyi-message 模块
        if (active.equals("nhfy")) {
            Map<String, Object> smsResult = mtSubmitSmUtil.submitSm(sendMagParam.getPhone(), sendMagParam.getContent());
            if (smsResult != null && smsResult.get("result") != null && smsResult.get("result").toString().equals("0")) {
            SendResult smsResult = smsSenderFactory.send(active,
                    SmsSendRequest.of(sendMagParam.getPhone(), sendMagParam.getContent(), serviceSubtask.getOrgid()));
            if (smsResult.isOk()) {
                resultMap.put("code", "200");
                resultMap.put("msg", "发送成功");
                serviceSubtask.setRemark(StringUtils.isNotEmpty(serviceSubtask.getRemark()) ? serviceSubtask.getRemark() + ";短信发送成功(手动提交)" : "短信发送成功(手动提交)");
@@ -5224,36 +5131,33 @@
            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;
            }
            //his患者id校验(与原实现一致:先校验这一项)
            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");
            }
            //机构配置校验、报文签名与返回判定均已收口到 ruoyi-message 的发送方实现
            WechatSendRequest wechatRequest = new WechatSendRequest();
            wechatRequest.setOrgid(serviceSubtask.getOrgid());
            wechatRequest.setIdCard(serviceSubtask.getSfzh());
            wechatRequest.setUrl(url);
            wechatRequest.setTitle(serviceSubtask.getTaskName());
            wechatRequest.setContent(serviceSubtask.getTaskDesc());
            wechatRequest.setPhone(patArchive.getTelcode());
            wechatRequest.setPatientName(serviceSubtask.getSendname());
            wechatRequest.setPatidHis(patArchive.getPatidHis());
            SendResult wechatResult = wechatSenderFactory.send(active, wechatRequest);
            //发送完成后,修改状态
            serviceSubtask.setSendstate(3L);
            if (wxCodeSuccess) {
            if (wechatResult.isOk()) {
                serviceSubtask.setResult("success");
                resultMap.put("code", "200");
                resultMap.put("msg", "发送成功");
            } else {
                log.error("【sfHandlle】公众号发送失败,患者信息:{},错误信息:{}", serviceSubtask, map.get("msg"));
                log.error("【sfHandlle】公众号发送失败,患者信息:{},错误信息:{}", serviceSubtask, wechatResult.getMessage());
                resultMap.put("code", -1);
                resultMap.put("message", "【公众号】公众号发送失败");
                return resultMap;
@@ -5266,400 +5170,6 @@
            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);
        }
        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;
    }
    /**
     * 标准化问卷答案文本:去掉 A/B/C/D 单字母前缀和后续空格
     * 例如 "A 是" -> "是","B 否" -> "否"
     */
    private String normalizeOptionAnswer(String answer) {
        if (StringUtils.isBlank(answer)) {
            return "";
        }
        String trimmed = answer.trim();
        if (trimmed.length() >= 3 && trimmed.charAt(1) == ' ') {
            char firstChar = trimmed.charAt(0);
            if (firstChar >= 'A' && firstChar <= 'Z') {
                return trimmed.substring(2).trim();
            }
        }
        return trimmed;
    }
    private Boolean saveServiceSubtaskDetail(ServiceSubtask serviceSubtask) {
@@ -5865,34 +5375,6 @@
        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());
@@ -5935,7 +5417,39 @@
        Date newDate = new Date();
        serviceSubtask.setLongSendTime(newDate);
        serviceSubtask.setVisitTime(newDate);
        // 院区:/scanGenerateSubtask 是匿名接口(SecurityConfig permitAll),取不到登录用户;
        // 而 service_task.campusid 在本库是占位值 '1',直接沿用会让统计接口(@AddOrgId 按院区过滤)查不到数据。
        // 这里用任务配置的病区(其次科室)反查 sys_dept.campusid 落库,保证问卷统计能按院区取到。
        String campusIdByDept = queryCampusIdByDeptCode(serviceSubtask.getLeavehospitaldistrictcode(), serviceTask.getOrgid());
        if (StringUtils.isEmpty(campusIdByDept)) {
            campusIdByDept = queryCampusIdByDeptCode(serviceSubtask.getDeptcode(), serviceTask.getOrgid());
        }
        if (StringUtils.isNotEmpty(campusIdByDept)) {
            serviceSubtask.setCampusid(campusIdByDept);
        }
        // 只配了科室(没有病区)的满意度任务:这道答卷在按病区筛选的报表里统计不到,留日志便于运维发现
        if (StringUtils.isEmpty(serviceSubtask.getLeavehospitaldistrictcode())
                && ("6".equals(serviceSubtask.getServiceType()) || "14".equals(serviceSubtask.getServiceType()))) {
            log.warn("【扫码生成任务】满意度子任务没有病区,按病区筛选的报表将统计不到该答卷:taskid={}, deptcode={}, campusid={}",
                    serviceSubtask.getTaskid(), serviceSubtask.getDeptcode(), serviceSubtask.getCampusid());
        }
        return serviceSubtask;
    }
    /**
     * 按科室/病区编码反查所属院区(查不到返回 null)
     */
    private String queryCampusIdByDeptCode(String deptCode, String orgid) {
        if (StringUtils.isEmpty(deptCode)) {
            return null;
        }
        try {
            SysDept sysDept = sysDept2Mapper.selectDeptByCode(deptCode, orgid);
            return sysDept == null ? null : sysDept.getCampusid();
        } catch (Exception e) {
            log.warn("按编码反查院区失败:deptCode={}, orgid={}, err={}", deptCode, orgid, e.getMessage());
            return null;
        }
    }
    /**
@@ -5974,7 +5488,6 @@
        }
    }
    public PhoneCallBackSHVO getFirstQues(PhoneCallReqYQVO phoneCallReqYQVO) {
        //用于返回
        PhoneCallBackSHVO phoneCallBackSHVO = new PhoneCallBackSHVO();
@@ -6012,7 +5525,6 @@
        }
        return phoneCallBackSHVO;
    }
    /**
     * 三汇ASR结果处理
@@ -6086,7 +5598,6 @@
            Object cacheObject = redisCache.getCacheObject(phoneCallResultYQVO.getSubId() + "-" + phoneCallResultYQVO.getScriptId());
            if (cacheObject == null || (Integer) cacheObject < ivrTaskTemplate.getMateNum()) {
                // 获取选项集合中的 optiondesc 用于引导患者
                List<IvrTaskTemplateTargetoption> optionList = ivrTaskTemplateScriptVO.getIvrTaskScriptTargetoptionList();
                String optionDescStr = "";
@@ -6130,13 +5641,14 @@
        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) {
@@ -6430,45 +5942,6 @@
        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")) {
@@ -6509,340 +5982,8 @@
        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());
    }
    // ---------------------------------------------------------------------
    // 说明:原私有 getWXCode / encode 已随发送方一起收口到 ruoyi-message 模块
    // (XinHuaMpApi),此处已删除,避免三份拷贝各写一套签名逻辑。
    // ---------------------------------------------------------------------
}