LAPTOP-KB9HII50\70708 1 hónapja
szülő
commit
ed369d572c

+ 59 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/common/OpenController.java

@ -0,0 +1,59 @@
package com.yihu.jw.hospital.module.common;
import com.yihu.jw.hospital.prescription.service.DsyyPrescriptionService;
import com.yihu.jw.restmodel.hospital.prescription.WlyyOutpatientVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
 * 开放免加密接口
 * Created by yeshijie on 2025/6/23.
 */
@RestController
@RequestMapping(value ="/open/exportExcel")
@Api(value = "开放接口", description = "开放接口", tags = {"开放接口"})
public class OpenController extends BaseController{
    @Autowired
    private DsyyPrescriptionService dsyyPrescriptionService;
    @PostMapping(value = "/selectReportInfo")
    @ApiOperation(value = "查询出院小结、门诊病历")
    public Envelop selectReportInfo(@ApiParam(name = "serviceCode", value = "接口编码", required = false)
                                        @RequestParam(value = "serviceCode",required = false)String serviceCode,
                                    @ApiParam(name = "patientId", value = "患者id", required = false)
                                        @RequestParam(value = "patientId",required = false)String patientId,
                                    @ApiParam(name = "visitNo", value = "就诊次数", required = false)
                                        @RequestParam(value = "visitNo",required = false)String visitNo,
                                    @ApiParam(name = "page", value = "页数", required = false)
                                        @RequestParam(value = "page",required = false)Integer page,
                                    @ApiParam(name = "size", value = "页码", required = false)
                                        @RequestParam(value = "size",required = false)Integer size) throws Exception {
        return ObjEnvelop.getSuccess("请求成功",dsyyPrescriptionService.selectReportInfo(serviceCode,patientId,visitNo,page,size));
    }
    @PostMapping(value = "findCardNo")
    @ApiOperation(value = "获取患者卡列表")
    public Envelop findCardNo(@ApiParam(name = "idcard", value = "idcard", required = true)
                                    @RequestParam(value = "idcard",required = true)String idcard) throws Exception {
        return ListEnvelop.getSuccess("请求成功",dsyyPrescriptionService.findCardNo(idcard));
    }
    @GetMapping(value = "selectOutpatientInfoByHisId")
    @ApiOperation(value = " 查询单条门诊就诊记录")
    public ObjEnvelop selectOutpatientInfoByHisId(@ApiParam(name = "hisPid", value = "居民id")
                                         @RequestParam(value = "hisPid", required = false) String hisPid,
                                         @ApiParam(name = "conNo", value = "就诊次数")
                                         @RequestParam(value = "conNo", required = false) String conNo) throws Exception {
        WlyyOutpatientVO obj = dsyyPrescriptionService.selectOutpatientInfoByHisId(hisPid, conNo);
        return ObjEnvelop.getSuccess("",obj);
    }
}

+ 2 - 1
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/service/FollowUpService.java

@ -104,11 +104,12 @@ public class FollowUpService {
                "f.doctor_code doctorCode,f.doctor_name doctorName,pl.disease_name businessTypeName,pl.disease businessType,ip.id itemPlanId, " +
                "h.dept_code deptCode,h.dept_name deptName,f.`status`,date_format(f.followup_date, '%Y-%m-%d %H:%i:%s') followupDate,'诊后康复' businessSource," +
                "date_format(f.followup_plan_date, '%Y-%m-%d %H:%i:%s') followupPlanDate,date_format(pl.create_time, '%Y-%m-%d %H:%i:%s') turnDownDate," +
                "pl.plan_doctor_name planDoctorName,h2.dept_name turnDownDeptName ";
                "if(i.from_source=2,i.doctor_name,pl.plan_doctor_name) planDoctorName,if(i.from_source=2,i.dept_name,h2.dept_name) turnDownDeptName ";
        String countSql = "select count(DISTINCT f.id) ";
        String filter = " from wlyy_followup f " +
                "LEFT JOIN base_service_item_plan ip on  f.id = ip.relation_code and ip.relation_type='6' " +
                "LEFT JOIN wlyy_patient_rehabilitation_plan pl on pl.id = ip.plan_id " +
                "LEFT JOIN wlyy_rehabilitation_patient_info i on pl.patient_info_code = i.code " +
                "INNER JOIN base_patient p on p.id = f.patient_code " +
                "LEFT JOIN base_doctor_hospital h on f.doctor_code=h.doctor_code and h.del=1 " +
                "LEFT JOIN base_doctor_hospital h2 on pl.plan_doctor=h2.doctor_code and h2.del=1 " +

+ 157 - 17
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/RehabilitationManageController.java

@ -7,6 +7,7 @@ import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationOperateRecords
import com.yihu.jw.hospital.module.rehabilitation.service.RehabilitationGuidanceService;
import com.yihu.jw.hospital.module.rehabilitation.service.RehabilitationManageService;
import com.yihu.jw.hospital.module.rehabilitation.service.SynchronizePatientService;
import com.yihu.jw.hospital.prescription.service.DsyyPrescriptionService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
@ -15,13 +16,19 @@ import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
import com.yihu.jw.util.excel.ExportUtl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@ -42,6 +49,156 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
    private SynchronizePatientService synchronizePatientService;
    @Autowired
    private RehabilitationGuidanceService rehabilitationGuidanceService;
    @Autowired
    private ExportUtl exportUtl;
    @Autowired
    private DsyyPrescriptionService dsyyPrescriptionService;
    @PostMapping(value = "/selectReportInfo")
    @ApiOperation(value = "查询出院小结、门诊病历")
    public Envelop selectReportInfo(@ApiParam(name = "serviceCode", value = "接口编码", required = false)
                                    @RequestParam(value = "serviceCode",required = false)String serviceCode,
                                    @ApiParam(name = "patientId", value = "患者id", required = false)
                                    @RequestParam(value = "patientId",required = false)String patientId,
                                    @ApiParam(name = "visitNo", value = "就诊次数", required = false)
                                    @RequestParam(value = "visitNo",required = false)String visitNo,
                                    @ApiParam(name = "page", value = "页数", required = false)
                                    @RequestParam(value = "page",required = false)Integer page,
                                    @ApiParam(name = "size", value = "页码", required = false)
                                    @RequestParam(value = "size",required = false)Integer size){
        try {
            return ObjEnvelop.getSuccess("查询成功",dsyyPrescriptionService.selectReportInfo(serviceCode,patientId,visitNo,page,size));
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @GetMapping(value = "rehabilitationInfoPage")
    @ApiOperation("康复下转记录")
    public Envelop rehabilitationInfoPage(
            @ApiParam(name = "name", value = "患者id/就诊卡号/病人姓名", required = false) @RequestParam(value = "name", required = false) String name,
            @ApiParam(name = "mobile", value = "手机号", required = false) @RequestParam(value = "mobile", required = false) String mobile,
            @ApiParam(name = "idcard", value = "身份证", required = false) @RequestParam(value = "idcard", required = false) String idcard,
            @ApiParam(name = "eventType", value = "患者类型", required = false) @RequestParam(value = "eventType", required = false) String eventType,
            @ApiParam(name = "status", value = "状态",  required = false) @RequestParam(value = "status", required = false) String status,
            @ApiParam(name = "startTime", value = "下转开始时间",  required = false) @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(name = "endTime", value = "下转结束时间",  required = false) @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(name = "page", value = "起始页", required = true) @RequestParam(value = "page", required = true, defaultValue = "1") Integer page,
            @ApiParam(name = "size", value = "每页显示数据条数", required = true) @RequestParam(value = "size", required = true, defaultValue = "10") Integer size
    ) {
        try {
            return rehabilitationManageService.rehabilitationInfoPage(page,size,name,mobile,idcard,eventType,status,startTime,endTime);
        } catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError("操作失败");
        }
    }
    @GetMapping(value = "open/exportExcel/exportRehabilitationInfoPage")
    @ApiOperation(value = " 导出康复下转记录")
    public void exportRehabilitationInfoPage(
            @ApiParam(name = "name", value = "患者id/就诊卡号/病人姓名", required = false) @RequestParam(value = "name", required = false) String name,
            @ApiParam(name = "mobile", value = "手机号", required = false) @RequestParam(value = "mobile", required = false) String mobile,
            @ApiParam(name = "idcard", value = "身份证", required = false) @RequestParam(value = "idcard", required = false) String idcard,
            @ApiParam(name = "eventType", value = "患者类型", required = false) @RequestParam(value = "eventType", required = false) String eventType,
            @ApiParam(name = "status", value = "状态",  required = false) @RequestParam(value = "status", required = false) String status,
            @ApiParam(name = "startTime", value = "下转开始时间",  required = false) @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(name = "endTime", value = "下转结束时间",  required = false) @RequestParam(value = "endTime", required = false) String endTime,
            HttpServletResponse response) {
        try {
            List<Map<String, Object>> list = rehabilitationManageService.rehabilitationInfoPage(null,null,name,mobile,
                    idcard,eventType,status,startTime,endTime).getDetailModelList();
            response.setContentType("octets/stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + new String("rehabilitationInfoPage.xls"));
            OutputStream os = response.getOutputStream();
            pushTotalExcel(os, list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void pushTotalExcel(OutputStream os, List<Map<String, Object>> list) throws Exception {
        WritableWorkbook wwb = jxl.Workbook.createWorkbook(os);
        try {
            WritableSheet ws;
            ws = wwb.createSheet("sheet", 1);
            //
            String[] header = {"患者ID", "门诊/住院号", "科室", "医生", "患者类型", "就诊卡号", "病人姓名","联系电话","证件类型","证件号码"
                    ,"下转状态","下转时间","专病名称","康复计划名称"};
            int k = 0;
            for (String h : header) {
                exportUtl.addCell(ws, 0, k, h);//表名,行,列,header
                k++;
            }
            int i = 1;
            for (Map<String, Object> m : list) {
                int j = 0;
                exportUtl.addCell(ws, i, j++, m.get("hisPid"));
                exportUtl.addCell(ws, i, j++, m.get("visitNo"));
                exportUtl.addCell(ws, i, j++, m.get("deptName"));
                exportUtl.addCell(ws, i, j++, m.get("doctorName"));
                exportUtl.addCell(ws, i, j++, m.get("eventTypeName"));
                exportUtl.addCell(ws, i, j++, m.get("ssc"));
                exportUtl.addCell(ws, i, j++, m.get("name"));
                exportUtl.addCell(ws, i, j++, m.get("mobile"));
                exportUtl.addCell(ws, i, j++, m.get("cardTypeName"));
                exportUtl.addCell(ws, i, j++, m.get("idcard"));
                exportUtl.addCell(ws, i, j++, m.get("statusName"));
                exportUtl.addCell(ws, i, j++, m.get("turnDownTime"));
                exportUtl.addCell(ws, i, j++, m.get("diseaseName"));
                exportUtl.addCell(ws, i, j++, m.get("templatePlanName"));
                i++;
            }
            wwb.write();
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (wwb != null) wwb.close();
            throw e;
        }
    }
    @PostMapping(value = "synchronizePationSingle")
    @ApiOperation("手动重新下转")
    public MixEnvelop synchronizePationSingle(
            @ApiParam(name = "id", value = "id", required = true) @RequestParam(value = "id", required = true) Long id) {
        try {
            String res = synchronizePatientService.synchronizePationSingle(id);
            if (StringUtils.isBlank(res)) {
                return MixEnvelop.getSuccess("操作成功,康复计划生成");
            } else {
                return MixEnvelop.getError(res);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("操作成功");
        }
    }
    @PostMapping(value = "synchronizePation")
    @ApiOperation("康复管理自动下转")
    public Envelop synchronizePation(
            @ApiParam(name = "status", value = "状态", required = false)
            @RequestParam(value = "status", required = false) String status) {
        try {
            StringBuilder res = synchronizePatientService.synchronizePation(status);
            if (StringUtils.isBlank(res)) {
                return Envelop.getSuccess("操作成功,康复计划生成");
            } else {
                return Envelop.getError(res.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError("操作成功");
        }
    }
    @PostMapping(value = "updItemPlanStatus")
    @ApiOperation("电话关怀,状态更新成待补录")
@ -176,23 +333,6 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
        }
    }
    @PostMapping(value = "synchronizePationSingle")
    @ApiOperation("手动重新下转")
    public MixEnvelop synchronizePationSingle(
            @ApiParam(name = "id", value = "id", required = true) @RequestParam(value = "id", required = true) Long id) {
        try {
            String res = synchronizePatientService.synchronizePationSingle(id);
            if (StringUtils.isBlank(res)) {
                return MixEnvelop.getSuccess("操作成功,康复计划生成");
            } else {
                return MixEnvelop.getError(res);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("操作成功");
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.findRehabilitationPlanList)
    @ApiOperation(value = "康复管理-康复计划列表")

+ 3 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationPatientInfoDao.java

@ -47,6 +47,9 @@ public interface RehabilitationPatientInfoDao extends PagingAndSortingRepository
    @Query(value="select r from RehabilitationPatientInfoDO r where r.code=?1 ")
    RehabilitationPatientInfoDO findByCode(String code);
    @Query(value="select r from RehabilitationPatientInfoDO r where r.idcard=?1 and r.conNo=?2 and r.visitNo=?3")
    RehabilitationPatientInfoDO findByVisitNo(String idcard,String conNo,String visitNo);
//    @Modifying
//    @Query(value="update RehabilitationPatientInfoDO r set r.status=?1 where r.code = ?2")
//    int updateState(Integer state, String code);

+ 2 - 1
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationInfoService.java

@ -946,12 +946,13 @@ public class RehabilitationInfoService {
                "        WHEN d.from_source='2' THEN '自动下转' " +
                "        WHEN d.from_source='3' THEN '扫码添加' " +
                "      END 'fromSourceName', " +
                "   d.ijk_id, d.status 'patientStatus',  " +
                "   d.ijk_id, d.status 'patientStatus',d4.dict_value 'patientStatusName',  " +
                "   d.problem_code," +
                "   q.disease 'diseaseId',q.disease_name 'diseaseName'  " +
                " FROM base_patient p  " +
                " INNER JOIN wlyy_rehabilitation_patient_info d ON p.id = d.patient  " +
                " LEFT JOIN wlyy_patient_rehabilitation_plan q ON d.`code`=q.patient_info_code  " +
                " LEFT JOIN wlyy_hospital_sys_dict d4 on d4.dict_name='rehabilitation_info_status' and d4.dict_code = d.`status`" +
                " WHERE  1 = 1 ";
        String countSql = " select count(1) from base_patient p " +
                " INNER JOIN wlyy_rehabilitation_patient_info d ON p.id = d.patient " +

+ 167 - 67
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationManageService.java

@ -10,10 +10,12 @@ import com.yihu.jw.entity.base.servicePackage.ServiceItemPlanDO;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.followup.Followup;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.specialist.RehabilitationServiceItemDO;
import com.yihu.jw.entity.specialist.SpecialistPatientRelationDO;
import com.yihu.jw.entity.specialist.rehabilitation.*;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.module.common.service.LabelService;
import com.yihu.jw.hospital.module.followup.dao.FollowUpDao;
import com.yihu.jw.hospital.module.followup.service.FollowUpService;
@ -100,6 +102,74 @@ public class RehabilitationManageService {
    private FollowUpDao followupDao;
    @Autowired
    private LabelService labelService;
    @Autowired
    private WlyyHospitalSysDictDao sysDictDao;
    /**
     * 康复下转记录
     * @param page 第几页
     * @param size 分页大小
     * @param name 患者id/就诊卡号/病人姓名
     * @param mobile 手机号
     * @param idcard 证件号码
     * @param eventType 患者类型 字典 eventType
     * @param status 下转状态 字典 rehabilitation_info_status
     * @param startTime 下转开始时间 yyyy-mm-dd
     * @param endTime 下转结束时间 yyyy-mm-dd
     * @return
     */
    public PageEnvelop rehabilitationInfoPage(Integer page, Integer size,String name,String mobile,String idcard,String eventType
            ,String status,String startTime,String endTime){
        String sql = "SELECT i.id,i.code,i.patient,i.his_pid hisPid,i.visit_no visitNo,i.dept_name deptName,i.doctor_name doctorName " +
                ",i.event_type eventType,d1.dict_value eventTypeName,i.ssc,i.name,i.mobile,pa.card_type cardType " +
                ",d2.dict_value cardTypeName,i.idcard " +
                ",i.`status`,d4.dict_value statusName,date_format(i.create_time, '%Y-%m-%d %H:%i:%s') turnDownTime " +
                ",i.disease_name diseaseName,i.template_plan_name templatePlanName,i.con_no conNo";
        String countSql = "SELECT count(i.id)";
        String filter = " from wlyy_rehabilitation_patient_info i " +
//                " LEFT JOIN wlyy_patient_rehabilitation_plan p on p.patient_info_code = i.code " +
                " LEFT JOIN base_patient pa on pa.id = i.patient " +
                " LEFT JOIN wlyy_hospital_sys_dict d1 on d1.dict_name='eventType' and d1.dict_code = i.event_type " +
                " LEFT JOIN wlyy_hospital_sys_dict d2 on d2.dict_name='idcard_type' and d2.dict_code = pa.card_type " +
//                " LEFT JOIN wlyy_hospital_sys_dict d3 on d3.dict_name='rehabilitation_plan_status' and d3.dict_code = p.`status` " +
                " LEFT JOIN wlyy_hospital_sys_dict d4 on d4.dict_name='rehabilitation_info_status' and d4.dict_code = i.`status`" +
                " WHERE 1=1 and i.from_source=2 ";
        if(StringUtils.isNotBlank(name)){
            filter += " and (i.name like '%"+name+"%' or i.his_pid like '%"+name+"%' or i.ssc like '%"+name+"%')";
        }
        if(StringUtils.isNotBlank(mobile)){
            filter += " and i.mobile like '%"+mobile+"%' ";
        }
        if(StringUtils.isNotBlank(idcard)){
            filter += " and i.idcard like '%"+idcard+"%' ";
        }
        if(StringUtils.isNotBlank(eventType)){
            filter += " and i.event_type = '"+eventType+"' ";
        }
        if(StringUtils.isNotBlank(status)){
            filter += " and i.status = '"+status+"' ";
        }
        if(StringUtils.isNotBlank(startTime)){
            filter += " and i.create_time >= '"+startTime+"' ";
        }
        if(StringUtils.isNotBlank(endTime)){
            filter += " and i.create_time <= '"+endTime+" 23:59:59' ";
        }
        String orderBy = " ";
        if(page!=null){
            orderBy = " limit "+(page-1)*size+","+size;
        }else {
            page = 1;
            size = 9999;
        }
        long count = jdbcTemplate.queryForObject(countSql+filter,Long.class);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql+filter+orderBy);
        return PageEnvelop.getSuccessListWithPage("查询成功",list,page,size,count);
    }
    //近期康复记录
    public Envelop recentServiceItemPlanRecords(String patient, Integer page, Integer size) {
@ -160,7 +230,7 @@ public class RehabilitationManageService {
                detailDO.setDept(newDetail.getDept());
                detailDO.setDeptName(newDetail.getDeptName());
                //生成执行计划列表
                planDOList = addServicePlan(serviceItemMap, planDO1, detailDO, planDOList);
                planDOList = addServicePlan(serviceItemMap, planDO1, detailDO, planDOList,null,null);
            }
        }
        rehabilitationDetailDao.saveAll(detailDOS);
@ -182,7 +252,7 @@ public class RehabilitationManageService {
    }
    public List<ServiceItemPlanDO> addServicePlan(Map<String, String> serviceItemMap, PatientRehabilitationPlanDO planDO,
                                                  RehabilitationDetailDO detailDO, List<ServiceItemPlanDO> planDOList) {
                                                  RehabilitationDetailDO detailDO, List<ServiceItemPlanDO> planDOList,String mzTime,String zyTime) {
        String planId = planDO.getId();
        String pateint = planDO.getPatient();
        String relationType = detailDO.getHospitalServiceItemId();
@ -195,10 +265,40 @@ public class RehabilitationManageService {
        String doctor = detailDO.getDoctor();
        String doctorName = detailDO.getDoctorName();
        String frequency_code = detailDO.getFrequencyCode();
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime localDateTime = null;
        String startTime = null;
        if(plan_start_time_type==2){
            startTime = mzTime;
        }else if(plan_start_time_type==3){
            startTime = zyTime;
        }
        if(StringUtils.isNotBlank(startTime)){
            localDateTime = DateUtil.dateToLocalDateTime(DateUtil.strToDate(startTime));
        }else {
            localDateTime = LocalDateTime.now();
        }
        int addNum = 0;
        localDateTime = localDateTime.plusDays(addNum);
        List<String> timeList = CronUtils.getExecutionTimeByNum(frequency_code, Integer.parseInt(server_count), localDateTime);
        List<String> timeList = null;
        if("zdy".equals(frequency_code)){
            WlyyHospitalSysDictDO dictDO = sysDictDao.findOneByDictNameAndDictCode("plan_frequency",frequency_code);
            String dictValue = dictDO.getDictValue().replace("自定义","");
            com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(dictValue);
            Date now = DateUtil.localTimeToDate(localDateTime);
            timeList = new ArrayList<>();
            for (int i = 0; i <jsonArray.size(); i++){
                JSONObject json = jsonArray.getJSONObject(i);
                int times = json.getInteger("times");//次数
                int days = json.getInteger("days");//几天后
                for (int j = 0; j <times; j++){
                    String date = DateUtil.getNextDay2(now,days);
                    timeList.add(date);
                }
            }
        }else {
            timeList = CronUtils.getExecutionTimeByNum(frequency_code, Integer.parseInt(server_count), localDateTime);
        }
        for (int i = 0; i <timeList.size(); i++){
            String time = timeList.get(i);
            ServiceItemPlanDO itemPlanDO = new ServiceItemPlanDO();
@ -354,9 +454,9 @@ public class RehabilitationManageService {
                " from wlyy_rehabilitation_plan_detail a INNER JOIN wlyy_patient_rehabilitation_plan p " +
                " on a.plan_id = p.id  ";
        if (doctorType == 2) {//家医是根据签约关系过滤
            sql += " INNER JOIN wlyy.wlyy_sign_family f ON f.patient = p.patient \n" +
                    "\tand f.expenses_status=1\n" +
                    "\tAND f.STATUS >= 1 \n" +
            sql += " INNER JOIN wlyy.wlyy_sign_family f ON f.patient = p.patient  " +
                    "\tand f.expenses_status=1 " +
                    "\tAND f.STATUS >= 1  " +
                    "\tAND ( f.doctor = '" + doctorCode + "' OR f.doctor_health = '" + doctorCode + "' )  ";
        }
        sql += " where 1=1 ";
@ -375,7 +475,7 @@ public class RehabilitationManageService {
            sql += " AND EXISTS (select code from wlyy.wlyy_patient where  `code` = p.patient and ( `name` LIKE '%" + patientCondition + "%' or idcard like '%" + patientCondition + "%') )";
        }
        if (doctorType == 1) {
            sql += " AND (p.create_user = '" + doctorCode + "' \n" +
            sql += " AND (p.create_user = '" + doctorCode + "'  " +
                    "\tOR a.doctor = '" + doctorCode + "' ) ";
        }
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planAll2(sql);
@ -2361,15 +2461,15 @@ public class RehabilitationManageService {
    public org.json.JSONObject getPatientSpecialAndFamilyDoctor(String patientCode) {
        org.json.JSONObject result = new org.json.JSONObject();
        //专科列表
        String sql = "SELECT DISTINCT p.patient, p.name AS patient_name, d.`code` as special_code, d.`name` as special_name, d.photo,d.dept_name,d.hospital_name \n" +
                "FROM wlyy_patient_rehabilitation_plan p, wlyy_doctor d\n" +
        String sql = "SELECT DISTINCT p.patient, p.name AS patient_name, d.`code` as special_code, d.`name` as special_name, d.photo,d.dept_name,d.hospital_name  " +
                "FROM wlyy_patient_rehabilitation_plan p, wlyy_doctor d " +
                "WHERE p.patient = '" + patientCode + "' AND d.`code`= p.create_user GROUP BY p.patient, p.create_user";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName2(sql);
        List<Map<String, Object>> specialList = jdbcTemplate.queryForList(sql);
        result.put("specialList", specialList);
        //全科 健康管理师列表
        sql = "select s.patient,s.`name`,s.doctor,doc.photo as doctor_photo,s.doctor_name,s.doctor_health,s.doctor_health_name \n" +
                "\t\tfrom wlyy_sign_family s ,wlyy_doctor doc\n" +
        sql = "select s.patient,s.`name`,s.doctor,doc.photo as doctor_photo,s.doctor_name,s.doctor_health,s.doctor_health_name  " +
                "\t\tfrom wlyy_sign_family s ,wlyy_doctor doc " +
                "\t\twhere s.patient ='" + patientCode + "' and doc.`code` =s.doctor and s.type=2 and s.`status`=1;";
        Map<String, Object> doctor = jdbcTemplate.queryForMap(sql);
        String doctor_health = doctor.get("doctor_health") == null ? "" : doctor.get("doctor_health").toString();
@ -2390,36 +2490,36 @@ public class RehabilitationManageService {
     */
    public List<Map<String, Object>> selectAllCompleteServiceItemsByPatient(String patient) {
        List<Map<String, Object>> resutList = new ArrayList<>();
        String sql = "select A.id 'planId',pdl.id,pdl.frequency_code,A.patient,A.`name`,si.id 'code',si.`name` 'serviceName',opr.complete_time 'czrq' from  \n" +
        String sql = "select A.id 'planId',pdl.id,pdl.frequency_code,A.patient,A.`name`,si.id 'code',si.`name` 'serviceName',opr.complete_time 'czrq' from   " +
                "(select p.team_code as teamCode,d.code as doctor,p.create_time as createTime,p.id,p.patient,p.name " +
                "from wlyy_patient_rehabilitation_plan p\n" +
                "LEFT JOIN wlyy.wlyy_doctor d ON d.code = p.create_user\n" +
                "WHERE p.patient='" + patient + "'\n" +
                "union\n" +
                "from wlyy_patient_rehabilitation_plan p " +
                "LEFT JOIN wlyy.wlyy_doctor d ON d.code = p.create_user " +
                "WHERE p.patient='" + patient + "' " +
                "union " +
                "SELECT p.team_code as teamCode,d.CODE AS doctor,p.create_time AS createTime,p.id,p.patient,p.name " +
                "from \n" +
                "wlyy_patient_rehabilitation_plan p\n" +
                "LEFT JOIN wlyy.wlyy_doctor d ON d.CODE=p.create_user\n" +
                "LEFT JOIN (\n" +
                "SELECT sr.patient AS patient,sr.team_code AS team_code \n" +
                "FROM wlyy_specialist_patient_relation sr \n" +
                "JOIN wlyy.wlyy_doctor_special_share se ON se.special_code=sr.id \n" +
                "WHERE sr.patient='" + patient + "') d \n" +
                "ON d.patient=p.patient WHERE \n" +
                "p.patient='" + patient + "' \n" +
                "AND d.team_code=p.team_code \n" +
                "ORDER BY createTime DESC)A \n" +
                "INNER  JOIN wlyy_rehabilitation_plan_detail pdl ON A.id = pdl.plan_id\n" +
                "INNER JOIN wlyy_rehabilitation_service_item si on pdl.hospital_service_item_id = si.id\n" +
                "INNER JOIN wlyy_rehabilitation_operate_records opr on opr.rehabilitation_detail_id = pdl.id\n" +
                "from  " +
                "wlyy_patient_rehabilitation_plan p " +
                "LEFT JOIN wlyy.wlyy_doctor d ON d.CODE=p.create_user " +
                "LEFT JOIN ( " +
                "SELECT sr.patient AS patient,sr.team_code AS team_code  " +
                "FROM wlyy_specialist_patient_relation sr  " +
                "JOIN wlyy.wlyy_doctor_special_share se ON se.special_code=sr.id  " +
                "WHERE sr.patient='" + patient + "') d  " +
                "ON d.patient=p.patient WHERE  " +
                "p.patient='" + patient + "'  " +
                "AND d.team_code=p.team_code  " +
                "ORDER BY createTime DESC)A  " +
                "INNER  JOIN wlyy_rehabilitation_plan_detail pdl ON A.id = pdl.plan_id " +
                "INNER JOIN wlyy_rehabilitation_service_item si on pdl.hospital_service_item_id = si.id " +
                "INNER JOIN wlyy_rehabilitation_operate_records opr on opr.rehabilitation_detail_id = pdl.id " +
                "where pdl.hospital_service_item_id <>2 and  opr.`status`=1 order by opr.complete_time desc ";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName(sql);
        List<Map<String, Object>> planDetailList = jdbcTemplate.queryForList(sql);
        resutList.addAll(planDetailList);
        //康复咨询
        sql = "select ct.consult,ct.type,ct.patient,ct.name,ct.czrq,ct.symptoms,top.`status`,top.end_time,top.evaluate,top.evaluate_time,top.reply,top.reply_time, '2' as 'serviceId','康复咨询' as 'serviceName'\n" +
                "from wlyy_consult_team ct\n" +
                "INNER JOIN " + imDBName + ".topics top on top.id = ct.consult \n" +
        sql = "select ct.consult,ct.type,ct.patient,ct.name,ct.czrq,ct.symptoms,top.`status`,top.end_time,top.evaluate,top.evaluate_time,top.reply,top.reply_time, '2' as 'serviceId','康复咨询' as 'serviceName' " +
                "from wlyy_consult_team ct " +
                "INNER JOIN " + imDBName + ".topics top on top.id = ct.consult  " +
                "where ct.patient='" + patient + "' and ct.type=18 and ct.del=1";
        List<Map<String, Object>> kangFuList = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> map : kangFuList) {
@ -2506,9 +2606,9 @@ public class RehabilitationManageService {
            String manageStatus;
            //获取最近完成服务
            sql = "select si.`code`,si.name,opr.complete_time update_time " +
                    "from wlyy_rehabilitation_plan_detail pd \n" +
                    "INNER  JOIN wlyy_rehabilitation_service_item si on si.`code` = pd.hospital_service_item_id \n" +
                    "INNER JOIN wlyy_rehabilitation_operate_records opr on opr.rehabilitation_detail_id = pd.id\n" +
                    "from wlyy_rehabilitation_plan_detail pd  " +
                    "INNER  JOIN wlyy_rehabilitation_service_item si on si.`code` = pd.hospital_service_item_id  " +
                    "INNER JOIN wlyy_rehabilitation_operate_records opr on opr.rehabilitation_detail_id = pd.id " +
                    "where plan_id='" + mp.get("id").toString() + "' and opr.`status` =1 ORDER BY opr.complete_time DESC ";
            List<Map<String, Object>> serverItems = jdbcTemplate.queryForList(sql);
            if (serverItems != null && serverItems.size() != 0) {
@ -2656,11 +2756,11 @@ public class RehabilitationManageService {
                     * 这边是随访的
                     * 加入type=‘21’
                     */
                    String allPlanSql = "select  wf.id as id,wf.followup_no as followupNo,wf.followup_date as followupDate,wf.followup_plan_date as followupPlanDate,wf.followup_next_date as followupNextDate,\n" +
                            "wf.followup_type as followupType,wf.followup_class as followupClass,wf.followup_manager_status as followupManagerStatus,wf.doctor_code as doctorCode,wf.doctor_name as doctorName,\n" +
                            "wf.jwdoctor_code as jwdoctorCode,wf.org_code as orgCode,wf.org_name as orgName,wf.jworg_code as jworgCode,wf.patient_code as patientCode,wf.patient_name as patientName,wf.idcard,\n" +
                            "wf.data_from as dataFrom,wf.status,wf.followup_content_phone as followupContentPhone,wf.creater,wf.sign_type as signType,wf.admin_team_code as adminTeamCode,wf.sign_code as signCode,\n" +
                            "wf.prescription_code as prescriptionCode,wf.type from wlyy_followup wf where 1=1 and wf.status !=0\n";
                    String allPlanSql = "select  wf.id as id,wf.followup_no as followupNo,wf.followup_date as followupDate,wf.followup_plan_date as followupPlanDate,wf.followup_next_date as followupNextDate, " +
                            "wf.followup_type as followupType,wf.followup_class as followupClass,wf.followup_manager_status as followupManagerStatus,wf.doctor_code as doctorCode,wf.doctor_name as doctorName, " +
                            "wf.jwdoctor_code as jwdoctorCode,wf.org_code as orgCode,wf.org_name as orgName,wf.jworg_code as jworgCode,wf.patient_code as patientCode,wf.patient_name as patientName,wf.idcard, " +
                            "wf.data_from as dataFrom,wf.status,wf.followup_content_phone as followupContentPhone,wf.creater,wf.sign_type as signType,wf.admin_team_code as adminTeamCode,wf.sign_code as signCode, " +
                            "wf.prescription_code as prescriptionCode,wf.type from wlyy_followup wf where 1=1 and wf.status !=0 ";
                    allPlanSql += " and wf.type='21' ";
                    allPlanSql += "and wf.patient_code = '" + map.get("patient") + "' order by wf.followup_plan_date desc";
                    List<Map<String, Object>> allPlanList = jdbcTemplate.queryForList(allPlanSql);
@ -2668,8 +2768,8 @@ public class RehabilitationManageService {
                }
                if (map.get("code").toString().equalsIgnoreCase("7")) {
                    String allPrescrSql = "SELECT p.`name`, TIMESTAMPDIFF(YEAR,p.birthday,SYSDATE()) age, p.sex, p.photo, pr.`status`, pr.`code`, \n" +
                            "LEFT(pr.create_time,19) AS createTime, pr.doctor, pr.min_drug_day AS minDrugDay, LEFT(pr.pres_create_time,19) AS presCreateTime \n" +
                    String allPrescrSql = "SELECT p.`name`, TIMESTAMPDIFF(YEAR,p.birthday,SYSDATE()) age, p.sex, p.photo, pr.`status`, pr.`code`,  " +
                            "LEFT(pr.create_time,19) AS createTime, pr.doctor, pr.min_drug_day AS minDrugDay, LEFT(pr.pres_create_time,19) AS presCreateTime  " +
                            "FROM wlyy_prescription pr LEFT JOIN wlyy_patient p ON pr.patient = p.`code` WHERE 1=1 AND pr.patient = '" + map.get("patient") + "' AND pr.status = 100 GROUP BY pr.`code`;";
                    List<Map<String, Object>> allPrescrList = jdbcTemplate.queryForList(allPrescrSql);
                    count = allPrescrList.size();
@ -2686,11 +2786,11 @@ public class RehabilitationManageService {
                if (map.get("code").toString().equalsIgnoreCase("6")) { //康复随访
                    //该居民的所有随访计划,需要同步展示到康复计划-康复随访内
                    String allPlanSql = "select  wf.id as id,wf.followup_no as followupNo,wf.followup_date as followupDate,wf.followup_plan_date as followupPlanDate,wf.followup_next_date as followupNextDate,\n" +
                            "wf.followup_type as followupType,wf.followup_class as followupClass,wf.followup_manager_status as followupManagerStatus,wf.doctor_code as doctorCode,wf.doctor_name as doctorName,\n" +
                            "wf.jwdoctor_code as jwdoctorCode,wf.org_code as orgCode,wf.org_name as orgName,wf.jworg_code as jworgCode,wf.patient_code as patientCode,wf.patient_name as patientName,wf.idcard,\n" +
                            "wf.data_from as dataFrom,wf.status,wf.followup_content_phone as followupContentPhone,wf.creater,wf.sign_type as signType,wf.admin_team_code as adminTeamCode,wf.sign_code as signCode,\n" +
                            "wf.prescription_code as prescriptionCode,wf.type from wlyy_followup wf where 1=1 and wf.status !=0\n" +
                    String allPlanSql = "select  wf.id as id,wf.followup_no as followupNo,wf.followup_date as followupDate,wf.followup_plan_date as followupPlanDate,wf.followup_next_date as followupNextDate, " +
                            "wf.followup_type as followupType,wf.followup_class as followupClass,wf.followup_manager_status as followupManagerStatus,wf.doctor_code as doctorCode,wf.doctor_name as doctorName, " +
                            "wf.jwdoctor_code as jwdoctorCode,wf.org_code as orgCode,wf.org_name as orgName,wf.jworg_code as jworgCode,wf.patient_code as patientCode,wf.patient_name as patientName,wf.idcard, " +
                            "wf.data_from as dataFrom,wf.status,wf.followup_content_phone as followupContentPhone,wf.creater,wf.sign_type as signType,wf.admin_team_code as adminTeamCode,wf.sign_code as signCode, " +
                            "wf.prescription_code as prescriptionCode,wf.type from wlyy_followup wf where 1=1 and wf.status !=0 " +
                            "and wf.patient_code = '" + map.get("patient") + "' order by wf.followup_plan_date desc";
                    List<Map<String, Object>> allPlanList = jdbcTemplate.queryForList(allPlanSql);
                    codeCount = allPlanList.size();
@ -2699,22 +2799,22 @@ public class RehabilitationManageService {
                if (map.get("code").toString().equalsIgnoreCase("7")) { //康复复诊
                    //居民的处方续方,需要同步展示到康复计划-康复复诊内
                    String allPrescrSql = "SELECT p.`name`, TIMESTAMPDIFF(YEAR,p.birthday,SYSDATE()) age, p.sex, p.photo, pr.`status`, pr.`code`, \n" +
                            "LEFT(pr.create_time,19) AS createTime, pr.doctor, pr.min_drug_day AS minDrugDay, LEFT(pr.pres_create_time,19) AS presCreateTime \n" +
                    String allPrescrSql = "SELECT p.`name`, TIMESTAMPDIFF(YEAR,p.birthday,SYSDATE()) age, p.sex, p.photo, pr.`status`, pr.`code`,  " +
                            "LEFT(pr.create_time,19) AS createTime, pr.doctor, pr.min_drug_day AS minDrugDay, LEFT(pr.pres_create_time,19) AS presCreateTime  " +
                            "FROM wlyy_prescription pr LEFT JOIN wlyy_patient p ON pr.patient = p.`code` WHERE 1=1 AND pr.patient = '" + map.get("patient") + "' AND pr.status = 100 GROUP BY pr.`code`;";
                    List<Map<String, Object>> allPrescrList = jdbcTemplate.queryForList(allPrescrSql);
                    codeCount = allPrescrList.size();
                    map.put("allPrescrList", allPrescrList);
                }
                String sqlCount = "SELECT\n" +
                        "\tCOUNT(pd.id) AS total ,\n" +
                        "\tCOUNT(CASE WHEN pd.`status`=1 THEN 1 ELSE NULL END) AS compeletTotal\n" +
                        "FROM\n" +
                        "\twlyy_rehabilitation_plan_detail pd\n" +
                        "WHERE\n" +
                String sqlCount = "SELECT " +
                        "\tCOUNT(pd.id) AS total , " +
                        "\tCOUNT(CASE WHEN pd.`status`=1 THEN 1 ELSE NULL END) AS compeletTotal " +
                        "FROM " +
                        "\twlyy_rehabilitation_plan_detail pd " +
                        "WHERE " +
                        "\t pd.plan_id = '" + planId + "' " +
                        "AND pd.hospital_service_item_id='" + map.get("code") + "' and (pd.frequency_code IS NOT NULL AND pd.frequency_code<>'')\n";
                        "AND pd.hospital_service_item_id='" + map.get("code") + "' and (pd.frequency_code IS NOT NULL AND pd.frequency_code<>'') ";
                List<Map<String, Object>> mapList1 = jdbcTemplate.queryForList(sqlCount);
                if (mapList1 != null && mapList1.size() != 0) {
@ -2751,7 +2851,7 @@ public class RehabilitationManageService {
            if (map.get("code").toString().equalsIgnoreCase("2")) {//康复咨询
                String typeSql = " and a.type in (2,18)";
                //总康复咨询数量
                String sqlTotal = "select count(*)\n" +
                String sqlTotal = "select count(*) " +
                        "from wlyy_consult a,wlyy_consult_team b where a.code = b.consult and a.patient = '" + map.get("patient") + "' and a.del = '1' " + typeSql + " ";
                Integer consultTotal = jdbcTemplate.queryForObject(sqlTotal, Integer.class);
@ -2760,7 +2860,7 @@ public class RehabilitationManageService {
                map.put("healthList", healthList);
                map.put("total", consultTotal + healthList.size());
                //完成康复咨询数量
                sqlTotal = "select count(*)\n" +
                sqlTotal = "select count(*) " +
                        "from wlyy_consult a,wlyy_consult_team b where a.code = b.consult and a.patient = '" + map.get("patient") + "' and a.del = '1' " + typeSql + " and b.`status`=1";
                consultTotal = jdbcTemplate.queryForObject(sqlTotal, Integer.class);
                map.put("compeletTotal", consultTotal + healthList.size());
@ -2777,12 +2877,12 @@ public class RehabilitationManageService {
                }
                //未回复康复咨询数量
                sqlTotal = "SELECT count(*) FROM wlyy.wlyy_consult_team a WHERE a.type = 18\n" +
                        "AND EXISTS ( SELECT DISTINCT t.id consultId FROM " + imDBName + ".topics t, " + imDBName + ".participants p, " + imDBName + ".doctors d, " + imDBName + ".sessions s \n" +
                        "WHERE p.participant_id = d.id AND t.session_id = p.session_id AND t.session_id = s.id\n" +
                        "AND s.type =18  AND t.`reply` = 0  AND a.consult = t.id\n" +
                        "and a.id in( select b.id from wlyy_consult a,wlyy_consult_team b \n" +
                        "where a.code = b.consult and a.patient = '" + map.get("patient") + "' and a.del = '1' " + typeSql + " )\n" +
                sqlTotal = "SELECT count(*) FROM wlyy.wlyy_consult_team a WHERE a.type = 18 " +
                        "AND EXISTS ( SELECT DISTINCT t.id consultId FROM " + imDBName + ".topics t, " + imDBName + ".participants p, " + imDBName + ".doctors d, " + imDBName + ".sessions s  " +
                        "WHERE p.participant_id = d.id AND t.session_id = p.session_id AND t.session_id = s.id " +
                        "AND s.type =18  AND t.`reply` = 0  AND a.consult = t.id " +
                        "and a.id in( select b.id from wlyy_consult a,wlyy_consult_team b  " +
                        "where a.code = b.consult and a.patient = '" + map.get("patient") + "' and a.del = '1' " + typeSql + " ) " +
                        ")";
                Integer noReplay = jdbcTemplate.queryForObject(sqlTotal, Integer.class);
                map.put("noReplay", noReplay);

+ 8 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationPlanService.java

@ -594,6 +594,14 @@ public class RehabilitationPlanService extends BaseJpaService<RehabilitationPlan
            patientRehabilitationPlanDO.setStatus(0);
            patientRehabilitationPlanDO.setUpdateTime(new Date());
            patientRehabilitationPlanDao.save(patientRehabilitationPlanDO);
            //更新状态
            if (StringUtils.isNotBlank(patientRehabilitationPlanDO.getPatientInfoCode())) {
                RehabilitationPatientInfoDO infoDO = rehabilitationPatientInfoDao.findByCode(patientRehabilitationPlanDO.getPatientInfoCode());
                infoDO.setStatus(6);
                rehabilitationPatientInfoDao.save(infoDO);
            }
            return MixEnvelop.getSuccess(SpecialistMapping.api_success, patientRehabilitationPlanDO, detailDOList);
        }
        return MixEnvelop.getError("更新失败!");

+ 631 - 619
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/SynchronizePatientService.java

@ -8,19 +8,21 @@ import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.servicePackage.ServiceItemPlanDO;
import com.yihu.jw.entity.door.SignPatientLabelInfo;
import com.yihu.jw.entity.patient.BasePatientDischargeRecord;
import com.yihu.jw.entity.specialist.RehabilitationServiceItemDO;
import com.yihu.jw.entity.specialist.rehabilitation.*;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.hospital.module.rehabilitation.dao.PatientRehabilitationPlanDao;
import com.yihu.jw.hospital.module.rehabilitation.dao.RehabilitationDetailDao;
import com.yihu.jw.hospital.module.rehabilitation.dao.RehabilitationPatientInfoDao;
import com.yihu.jw.hospital.module.rehabilitation.dao.RehabilitationServiceItemDao;
import com.yihu.jw.hospital.module.specialist.dao.PatientMedicalRecordsRehabilitationDao;
import com.yihu.jw.hospital.prescription.service.DsyyPrescriptionService;
import com.yihu.jw.hospital.team.dao.SignPatientLabelInfoDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientDischargeRecordDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.rehabilitation.ServiceItemPlanDao;
import com.yihu.jw.restmodel.hospital.prescription.WlyyOutpatientVO;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.wlyy.service.WlyyBusinessService;
@ -34,7 +36,6 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@ -66,7 +67,7 @@ public class SynchronizePatientService  {
    @Autowired
    private PatientRecordService patientRecordService;
    @Autowired
    private SignPatientLabelInfoDao signPatientLabelInfoDao;
    private ServiceItemPlanDao serviceItemPlanDao;
    @Autowired
    private PatientRehabilitationPlanDao patientRehabilitationPlanDao;
    @Autowired
@ -81,193 +82,316 @@ public class SynchronizePatientService  {
    private DsyyPrescriptionService dsyyPrescriptionService;
    @Autowired
    private RehabilitationServiceItemDao serviceItemDao;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Autowired
    private PatientMedicalRecordsRehabilitationDao patientMedicalRecordsDao;
    //手动重新下转
    public String synchronizePationSingle(Long id) throws Exception{
        RehabilitationPatientInfoDO re = rehabilitationPatientInfoDao.findById(id).orElse(null);
        if(re==null){
        RehabilitationPatientInfoDO infoDO = rehabilitationPatientInfoDao.findById(id).orElse(null);
        if(infoDO==null){
            return "数据不存在";
        }
        if(re.getStatus()==1){
        //1 6 7 8  11
        if(infoDO.getStatus()==1||infoDO.getStatus()==6||infoDO.getStatus()==7||infoDO.getStatus()==8||infoDO.getStatus()==11){
            return "已下转成功,不允许操作";
        }
        List<RehabilitationPatientInfoDO> modifyList = new ArrayList<>();
        List<RehabilitationPatientInfoDO> tmpList = getPatientInfoList(re.getIdcard(), DateUtil.dateToStrShort(re.getCreateTime()));
        String name = infoDO.getName();
        String idcard = infoDO.getIdcard();
        String conNo = infoDO.getConNo();//就诊次数
        String visitNo = infoDO.getVisitNo();//就诊号
        String hisPid = infoDO.getHisPid();//就诊号
        JSONArray cardList = null;
        BasePatientDO patient = null;
        if(StringUtils.isBlank(re.getIdcard())){
            infoUpdate(tmpList,5,modifyList,null);
            saveModifyList(modifyList);
            return "下转数据错误,身份证号不存在";
        }
        if(StringUtils.isBlank(re.getPatient())){
            List<BasePatientDO> patientList = patientDao.getPatientByIdcardOrSsc(re.getIdcard());//获取患者信息
        if(StringUtils.isBlank(infoDO.getPatient())){
            List<BasePatientDO> patientList = patientDao.getPatientByIdcard(idcard);//获取患者信息
            cardList = dsyyPrescriptionService.findCardNo(idcard);
            if (patientList.size() == 0) {
                //未找到居民,从健康档案添加居民
                patient = patientService.addPaitentByIdcard(re.getIdcard(),re.getName(),re.getSsc(),re.getMobile(),re.getSex());
                //未找到居民,从his视图添加居民
                patient = dsyyPrescriptionService.addPaitentByIdcard(cardList,idcard,name);
                if (patient == null) {
                    infoUpdate(tmpList,5,modifyList,null);
                    saveModifyList(modifyList);
                    infoDO.setStatus(5);
                    rehabilitationPatientInfoDao.save(infoDO);
                    return "居民信息不存在";
                } else {
                    patientList = patientDao.getPatientByIdcardOrSsc(re.getIdcard());//重新获取该患者信息
                    patientList = patientDao.getPatientByIdcardOrSsc(idcard);//重新获取该患者信息
                    patient = patientList.get(0);
                }
            }
            infoUpdate4(tmpList,patient.getId(),modifyList);
        }else {
            patient = patientDao.findByIdAndDel(re.getPatient(),"1");
            patient = patientDao.findById(infoDO.getPatient()).orElse(null);
        }
        String dept = re.getDept();
        String diagnosis = re.getDiagnosis();
        //专病配置
        RehabilitationPlanTemplateDO planTemplateDO = findPlanTemplate(dept,diagnosis);
        if(planTemplateDO==null){
            return "未找到满足条件的专病配置";
        if(StringUtils.isBlank(hisPid)&&cardList==null){
            infoDO.setStatus(9);
            rehabilitationPatientInfoDao.save(infoDO);
            return "就诊卡信息不存在";
        }
        if(planTemplateDO.getIsFamily()==1){
            //判断签约的才推送i健康
            JSONObject isSign = businessService.isSign(re.getIdcard());
            if(isSign==null){
                return "请求i健康失败";
            }
            if(isSign.getJSONObject("obj")!=null){
                //推送i健康数据
                infoUpdate2(tmpList,planTemplateDO.getFamilyRelation(),modifyList);
                saveModifyList(modifyList);
                com.alibaba.fastjson.JSONObject jsonObject = businessService.pushPatientInfos(re);
                if(jsonObject==null||jsonObject.getInteger("status")==-1){
                    return "请求i健康失败";
        infoDO.setSex(patient.getSex());
        infoDO.setPatient(patient.getId());
        infoDO.setIdcard(patient.getIdcard());
        infoDO.setAge(IdCardUtil.getAgeByBirthdayOrIdcard(patient.getIdcard(), patient.getBirthday()));
        infoDO.setAddress(patient.getAddress());
        String ssc = null;
        String mobile = null;
        JSONObject jaMzbl = new JSONObject();
        JSONObject jaCy = new JSONObject();
        String eventType = infoDO.getEventType();//1门诊 2住院
        try {
            if(StringUtils.isBlank(eventType)){
                for (int i=0;i<cardList.size();i++){
                    JSONObject tmp = cardList.getJSONObject(i);
                    String SICK_ID = tmp.getString("SICK_ID");
                    String CARD_NO = tmp.getString("CARD_NO");
                    String LXDH = tmp.getString("LXDH");
                    //门诊病历
                    if(StringUtils.isBlank(eventType)){
                        String mzbl = dsyyPrescriptionService.selectReportInfo("JHIDS-USD-HLWMZBL-014",SICK_ID,conNo,1,1);
                        if(StringUtils.isNotBlank(mzbl)&&!"[]".equals(mzbl)){
                            jaMzbl = JSONArray.parseArray(mzbl).getJSONObject(0);
                            eventType = "1";
                            hisPid = SICK_ID;
                            ssc = CARD_NO;
                            mobile = LXDH;
                        }
                    }
                    if(StringUtils.isBlank(eventType)){
                        //出院小结
                        String cyxj = dsyyPrescriptionService.selectReportInfo("JHIDS-USD-HLWCYXJ-013",SICK_ID,conNo,1,1);
                        if(StringUtils.isNotBlank(cyxj)&&!"[]".equals(cyxj)){
                            jaCy = JSONArray.parseArray(cyxj).getJSONObject(0);
                            eventType = "2";
                            hisPid = SICK_ID;
                            ssc = CARD_NO;
                            mobile = LXDH;
                        }
                    }
                }
            }else if("1".equals(eventType)){
                String mzbl = dsyyPrescriptionService.selectReportInfo("JHIDS-USD-HLWMZBL-014",hisPid,conNo,1,1);
                if(StringUtils.isNotBlank(mzbl)&&!"[]".equals(mzbl)){
                    jaMzbl = JSONArray.parseArray(mzbl).getJSONObject(0);
                }
            }else if("2".equals(eventType)){
                String cyxj = dsyyPrescriptionService.selectReportInfo("JHIDS-USD-HLWCYXJ-013",hisPid,conNo,1,1);
                if(StringUtils.isNotBlank(cyxj)&&!"[]".equals(cyxj)){
                    jaCy = JSONArray.parseArray(cyxj).getJSONObject(0);
                }
                Long ijkId = jsonObject.getLong("data");
                infoUpdate3(tmpList,3,ijkId,modifyList,null);
                saveModifyList(modifyList);
                return "推送i健康成功";
            }
        }catch (Exception e){
            e.printStackTrace();
            return "获取患者无门诊病历/患者无出院小结失败";
        }
        String diseaseId = planTemplateDO.getDiseaseId();
        String diseaseName = planTemplateDO.getDiseaseName();
        String planTemplateId = planTemplateDO.getId();
        String planDoctorId = planTemplateDO.getPlanDoctor();//计划负责人
        BaseDoctorDO planDoctor = doctorDao.findByIdAndDel(planDoctorId);
        //同步病历 //如果同步病历失败,不做下转
        String result = "";
        if (demoFlag) {//测试线获取病历模板
            result = patientRecordService.getJosnFileResullt("event" + "2");
        } else {
            //同步住院病历信息
//            try {
//                JSONObject jsonEvent = new JSONObject();
//                List<Map<String, String>> resultMap = patientRecordService.getAllEvent_new(patient.getId(), "2", "1", "1", "2010-10-10 00:00:00", hos.getCode());
//                jsonEvent.put("data", JSON.parseArray(JSON.toJSONString(resultMap)));
//                result = jsonEvent.toString();
//            }catch (Exception e){
//                infoUpdate(tmpList,3,modifyList,null);
//                saveModifyList(modifyList);
//                return "同步患者病历:" + re.getIdcard() + "----无住院病历信息";
//            }
        }
        com.alibaba.fastjson.JSONObject rejson = com.alibaba.fastjson.JSONObject.parseObject(result);
        JSONArray temlist = rejson.getJSONArray("data");
        if (0 == temlist.size()) {
            infoUpdate(tmpList,3,modifyList,null);
            saveModifyList(modifyList);
            return "同步患者病历:" + re.getIdcard() + "----无住院病历信息";
        if(StringUtils.isBlank(eventType)){
            infoDO.setStatus(3);
            rehabilitationPatientInfoDao.save(infoDO);
            return "患者无门诊病历或患者无出院小结";
        }
        infoDO.setSsc(ssc);
        infoDO.setMobile(mobile);
        infoDO.setHisPid(hisPid);
        infoDO.setEventType(eventType);
        com.alibaba.fastjson.JSONObject tem = temlist.getJSONObject(0);
        String dept = "科室";
        String deptName = null;
        String diagnosis = "诊断";
        String doctorId = null;
        String doctorName = null;
        String doctorIdMz = null;//门诊医生
        String doctorNameMz = null;
        String doctorIdZy = null;//住院医生
        String doctorNameZy = null;
        String mzTime = null;
        String zyTime = null;
        PatientMedicalRecordsDO pmr = new PatientMedicalRecordsDO();
        pmr.setHospitalName(tem.getString("orgName"));
        pmr.setHospital(tem.getString("orgCode"));
        if (demoFlag) {//测试获取为病历模板 hospitalcode获取为自己的code
//            pmr.setHospital(hos.getCode());
        }
        pmr.setDischargeDiagnosis(re.getDiagnosis());
        pmr.setDischargeDiagnosisName(re.getDiagnosisName());
        pmr.setAdmittingDiagnosis(re.getDiagnosis());
        pmr.setJwpatient(tem.getString("patient"));
        pmr.setAdmittingDiagnosisName(re.getDiagnosisName());
        pmr.setEvent(tem.getString("id"));
        pmr.setDataFrom(tem.getString("dataFrom"));
        pmr.setAdvice("出院继续观察");
        if (tem.getString("dataFrom").equals("4"))//3中山 4智业
        {
//            if (StringUtils.isNoneBlank(diagnosisIn)){//入院诊断
//                pmr.setAdmittingDiagnosisName(diagnosisIn);
//            }
//            if (StringUtils.isNoneBlank(diagnosisOut)){//出院诊断
//                pmr.setDischargeDiagnosisName(diagnosisOut);
//            }
        }
        pmr.setPatient(patient.getId());
        pmr.setPatientName(patient.getName());
        pmr.setCode(getCode());
        pmr.setDataFrom("1");
        pmr.setCreateTime(new Date());
        pmr.setJwpatient(hisPid);
        pmr.setEventType(eventType);
        pmr.setConNo(conNo);
        if("1".equals(eventType)){
            //门诊
            String ASSISTEXAMINATION = jaMzbl.getString("ASSISTEXAMINATION");//辅助检查
            String JHDL_CREATED_AT = jaMzbl.getString("JHDL_CREATED_AT");//": "2025-06-18T16:32:52.000+0000",
            String MEDICALHISTORY = jaMzbl.getString("MEDICALHISTORY");//现病史
            String EMRPDF = jaMzbl.getString("EMRPDF");//电子病历详情pdf
            String PHYSICALEXAMINATION = jaMzbl.getString("PHYSICALEXAMINATION");//体格检查
            String JHDL_UPDATED_AT = jaMzbl.getString("JHDL_UPDATED_AT");//": "2025-06-18T16:32:52.000+0000",
            String VISIT_ID = jaMzbl.getString("VISIT_ID");//就诊次数
//                String JHDL_ROWKEY = jaMzbl.getString("JHDL_ROWKEY");//": 5620492334960637262,
            String PASTHISTORY = jaMzbl.getString("PASTHISTORY");//既往史
            String PATIENT_ID = jaMzbl.getString("PATIENT_ID");//居民id
//                String ID = jaMzbl.getString("ID");//": "42661889-5-6000861496-0-73-0-1",
            String COMPLAINT = jaMzbl.getString("COMPLAINT");//主诉
//                String JHDL_SRC_TAB = jaMzbl.getString("JHDL_SRC_TAB");//": "JHDL:01_HLW_MZBL",
//                String LAST_MODIFY_DATE_TIME = jaMzbl.getString("LAST_MODIFY_DATE_TIME");//": "2025-06-18 08:29:07"
            //查询历史门诊记录获取科室和医生
            try {
                WlyyOutpatientVO outpatientVO = dsyyPrescriptionService.selectOutpatientInfoByHisId(hisPid,conNo);
                dept = outpatientVO.getDept();
                deptName = outpatientVO.getDeptName();
//                List<DoctorMappingDO> doctorMappingDOS = doctorMappingDao.findByMappingCode(outpatientVO.getDoctor());
//                if(doctorMappingDOS.size()>0){
//                    doctorIdMz = doctorMappingDOS.get(0).getDoctor();
//                }
                doctorNameMz = outpatientVO.getDoctorName();
                mzTime = DateUtil.dateToStrLong(outpatientVO.getConDate());
            }catch (Exception e){
                e.printStackTrace();
                return "获取历史门诊记录失败";
            }
        }else {
            //住院
            String ATTENDINGPHYSICIAN = jaCy.getString("ATTENDINGPHYSICIAN");//黎喜梅 主治医师
            String DISCHARGEDISEASE = jaCy.getString("DISCHARGEDISEASE");//出院诊断
            String ADMISSIONDAY = jaCy.getString("ADMISSIONDAY");//5, 住院天数
//                String BIRTH = jaCy.getString("BIRTH");//1968-12-02 00:00:00", 出生日期
//                String ID = jaCy.getString("ID");//42661889-5-6000861496-2-9-0-20",
//                String LAST_MODIFY_DATE_TIME = jaCy.getString("LAST_MODIFY_DATE_TIME");//2025-05-13 21:16:12",
//                String BEDNO = jaCy.getString("BEDNO");//A12-46",
            String DISCHARGEDESC = jaCy.getString("DISCHARGEDESC");//出院时情况
            String RESIDENTPHYSICIAN = jaCy.getString("RESIDENTPHYSICIAN");//夏小艺 住院医师
            String ADMISSIONNO = jaCy.getString("ADMISSIONNO");//326405",住院号
//                String JHDL_CREATED_AT = jaCy.getString("JHDL_CREATED_AT");//2025-05-13T16:02:07.000+0000",
            String ADMISSIONDISEASE = jaCy.getString("ADMISSIONDISEASE");//入院诊断
            String NAME = jaCy.getString("NAME");//李兴英 居民姓名
            String DATE = jaCy.getString("DATE");//2025-05-10 08:11:38",填写日期
//                String JHDL_UPDATED_AT = jaCy.getString("JHDL_UPDATED_AT");//2025-05-13T16:02:07.000+0000",
            String VISIT_ID = jaCy.getString("VISIT_ID");//9 就诊次数
            String DEPTNAME = jaCy.getString("DEPTNAME");//肿瘤科",//科室名称
            String DISCHARGETIME = jaCy.getString("DISCHARGETIME");//2025-05-11 08:03:15 出院时间
            String TREATMENTCOURSE = jaCy.getString("TREATMENTCOURSE");//主要诊疗经过
            String DISCHARGEORDER = jaCy.getString("DISCHARGEORDER");//出院医嘱
//                String JHDL_ROWKEY = jaCy.getString("JHDL_ROWKEY");//4179340454200282426,
            String ADMISSIONDESC = jaCy.getString("ADMISSIONDESC");//入院情况
            String PATIENT_ID = jaCy.getString("PATIENT_ID");//6000861496 居民id
            String ATTENDNUMBER = jaCy.getString("ATTENDNUMBER");//326405 住院号
//                String JHDL_SRC_TAB = jaCy.getString("JHDL_SRC_TAB");//JHDL:01_HLW_CYXJ",
            String ADMISSIONTIME = jaCy.getString("ADMISSIONTIME");//2025-05-06 08:23:10 入院时间
            pmr.setAdmissionTime(DateUtil.strToDate(ADMISSIONTIME));
            pmr.setDischargeTime(DateUtil.strToDate(DISCHARGETIME));
            pmr.setAdmittingDiagnosisName(ADMISSIONDISEASE);
            pmr.setDischargeDiagnosisName(DISCHARGEDISEASE);
            pmr.setAdvice(DISCHARGEORDER);
            infoDO.setVisitNo(ADMISSIONNO);
        pmr.setDiseaseCode(diseaseId);//疾病code
        pmr.setDiseaseName(diseaseName);//疾病名称
            deptName = DEPTNAME;
            dept = findDeptByName(DEPTNAME);
            doctorNameZy = RESIDENTPHYSICIAN;
            pmr.setDept(dept);
            pmr.setDeptName(deptName);
            zyTime = DISCHARGETIME;
        }
        infoDO.setDept(dept);
        infoDO.setDeptName(deptName);
        //创建居民住院病历
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        PatientMedicalRecordsDO patientMedicalRecordsDO1 = rehabilitationInfoService.createMedicalRecords(planDoctorId, patient.getId(), patient.getName(), pmr, null);
        //三院专病配置
        RehabilitationPlanTemplateDO planTemplateDO = findPlanTemplate(dept,diagnosis,eventType);
        if(planTemplateDO==null){
            infoDO.setStatus(2);
            rehabilitationPatientInfoDao.save(infoDO);
            return "无匹配的康复计划";
        }
        infoDO.setDiseaseId(planTemplateDO.getDiseaseId());
        infoDO.setDiseaseName(planTemplateDO.getDiseaseName());
        infoDO.setTemplatePlanId(planTemplateDO.getId());
        infoDO.setTemplatePlanName(planTemplateDO.getTitle());
        if("1".equals(eventType)){
            doctorIdMz = findDoctorByName(doctorNameMz,planTemplateDO.getDepts());
            if(StringUtils.isBlank(doctorIdMz)){
                infoDO.setStatus(4);
                rehabilitationPatientInfoDao.save(infoDO);
                return "医生信息查询不到";
            }
        }else {
            doctorIdZy = findDoctorByName(doctorNameZy,planTemplateDO.getDepts());
            if(StringUtils.isBlank(doctorIdZy)){
                infoDO.setStatus(4);
                rehabilitationPatientInfoDao.save(infoDO);
                return "医生信息查询不到";
            }
        }
        if(planTemplateDO.getIsFamily()==1){
            boolean flag = pushIjk(planTemplateDO,null,infoDO);
            if(!flag){
                return "推送i健康失败";
            }
            return null;
        }
        // ↓创建康复计划。创建完成即为已下转
        PatientRehabilitationPlanDO planDO = new PatientRehabilitationPlanDO();
        if (patientMedicalRecordsDO1 == null) {
            infoUpdate(tmpList,2,modifyList,null);
            saveModifyList(modifyList);
            return "创建病历失败";
        } else {//
            // ↓创建康复计划。创建完成即为已下转
            PatientRehabilitationPlanDO planDO = new PatientRehabilitationPlanDO();
            planDO.setStatus(3);//待分配 执行医生和科室
            planDO.setPatient(patient.getId());
            planDO.setName(patient.getName());
            planDO.setTitle(patient.getName()+"的康复计划");
            planDO.setHealthStatusCode("2");
            planDO.setPlanType(1);
            planDO.setPayment(2);
            planDO.setAdviceContent("出院继续观察");
            planDO.setMedicalRecordsCode(patientMedicalRecordsDO1.getCode());//居民住院病历code
        String diseaseId = planTemplateDO.getDiseaseId();
        String diseaseName = planTemplateDO.getDiseaseName();
        String planTemplateId = planTemplateDO.getId();
        String planDoctorType = planTemplateDO.getPlanDoctorType();//计划负责人 1手动获取,2自动获取
        String planDoctorId = planTemplateDO.getPlanDoctor();//类型=1康复计划负责人,类型2  1门诊医生 2住院医生
        String distributionType = planTemplateDO.getDistributionType();//分配方式 1手动分配 2自动分配(分配康复计划项的执行医生)
        String distributionTo = planTemplateDO.getDistributionTo();//分配对象 1门诊医生 2住院医生
        BaseDoctorDO planDoctor = null;
        if("1".equals(planDoctorType)){
            planDoctor = doctorDao.findByIdAndDel(planDoctorId);
            planDO.setPlanDoctor(planDoctorId);
            planDO.setPlanDoctorName(planDoctor.getName());
            planDO.setPatientInfoCode(re.getCode());
            planDO.setCreateTime(new Date());
            planDO.setUpdateTime(new Date());
            planDO.setDisease(diseaseId);
            planDO.setDiseaseName(diseaseName);
//            planDO.setTotalExpense();
            StringBuilder results = new StringBuilder();
            //创建康复计划
            planDO = createRehabilitationPlanJson(planDO,planTemplateId,results,re);
            if (planDO == null) {//创建康复计划不成功,无法下转
                infoUpdate(tmpList,2,modifyList,null);
                saveModifyList(modifyList);
                return  "创建康复计划失败";
            } else {//创建康复计划成功
                String planId = planDO.getId();
                //居民专科标签。
                List<SignPatientLabelInfo> healthList = signPatientLabelInfoDao.findByPatientAndLabelTypeAndStatus(patient.getId(), "8", 1);
                if (healthList.size() > 0) {
                    //先删除已有健康情况标签
                    signPatientLabelInfoDao.deleteByPatientAndLabelTypeAndStatus(patient.getId(), "8", 1);
                }
                SignPatientLabelInfo signPatientLabelInfo = new SignPatientLabelInfo();
                signPatientLabelInfo.setPatient(patient.getId());
                signPatientLabelInfo.setPname(patient.getName());
                signPatientLabelInfo.setLabel("2");
                signPatientLabelInfo.setLabelName("出院康复");
                signPatientLabelInfo.setLabelType("8");
                signPatientLabelInfo.setStatus(1);
                signPatientLabelInfo.setCzrq(new Date());
                signPatientLabelInfoDao.save(signPatientLabelInfo);
                infoUpdate(tmpList,1,modifyList,planDoctor);
//                logger.info("康复计划自动下转————" +"下转结束:" + re.getIdcard() + "----下转成功,已转至医生:"+doctor.getName()+"《"+hos.getName()+"》的已下转列表,下转疾病:"+diseaseObj.getString("diseaseName"));
                //给服务医生群组发送下转消息
                if (StringUtils.isNoneBlank(planId)){
//                    asynService.sendMsg(planId,signFamily,patient,doctor,patientMedicalRecordsDO1,re);
                }
        }else {
            if("1".equals(planDoctorId)){
                //1门诊医生
                doctorId = doctorIdMz;
                doctorName = doctorNameMz;
            }else {
                //2住院医生
                doctorId = doctorIdZy;
                doctorName = doctorNameZy;
            }
            planDO.setPlanDoctor(doctorId);
            planDO.setPlanDoctorName(doctorName);
        }
        if("2".equals(eventType)){
            planDO.setMedicalRecordsCode(pmr.getCode());//居民住院病历code
        }
        infoDO.setDoctor(doctorId);
        infoDO.setDoctorName(doctorName);
        planDO.setStatus(1);
        planDO.setPatient(patient.getId());
        planDO.setName(patient.getName());
        planDO.setTitle(patient.getName()+"的康复计划");
        planDO.setHealthStatusCode("2");
        planDO.setPlanType(1);
        planDO.setPayment(2);
        planDO.setAdviceContent("出院继续观察");
        planDO.setPatientInfoCode(infoDO.getCode());
        planDO.setCreateTime(new Date());
        planDO.setUpdateTime(new Date());
        planDO.setDisease(diseaseId);
        planDO.setDiseaseName(diseaseName);
        //目前默认为冠心病
        //创建康复计划
        planDO = createRehabilitationPlanJson(planDO,planTemplateId,null,infoDO,distributionType,distributionTo,dept,deptName,doctorId,doctorName,mzTime,zyTime);
        if (planDO == null) {//创建康复计划不成功,无法下转
            infoDO.setStatus(2);
            rehabilitationPatientInfoDao.save(infoDO);
            return "创建康复计划请求失败";
        } else {//创建康复计划成功
            if("2".equals(distributionType)){
                infoDO.setStatus(7);
            }else {
                infoDO.setStatus(1);
            }
            saveModifyList(modifyList);
            rehabilitationPatientInfoDao.save(infoDO);
            pmr.setDiseaseCode(diseaseId);//疾病code
            pmr.setDiseaseName(diseaseName);//疾病名称
            //创建居民住院病历
            createMedicalRecords(doctorId,doctorName,pmr);
        }
        return null;
    }
@ -292,10 +416,11 @@ public class SynchronizePatientService  {
    //获取三院专病配置
    public RehabilitationPlanTemplateDO findPlanTemplate(String dept,String diagnosis,String turnDownRange){
        String sql = "SELECT t.*,d.is_family isFamily,d.id diseaseId,d.name diseaseName,d.family_relation familyRelation " +
        String sql = "SELECT t.*,d.is_family isFamily,d.id diseaseId,d.name diseaseName,d.family_relation familyRelation,d.dept depts " +
                ",d.distribution_type distributionType,d.distribution_to distributionTo FROM base_disease_hospital d,wlyy_rehabilitation_plan_template t " +
                " WHERE d.rehabilitation_template_id=t.id and d.`status`='1' and d.rehabilitation_down_type='0' and d.rehabilitation_type='1'" +
                " and d.turn_down_range in('"+turnDownRange+"','3') and d.dept like '%"+dept+"%' and d.diagnosis like '%"+diagnosis+"%' LIMIT 1";
                " and d.turn_down_range = '"+turnDownRange+"' and d.dept like '%"+dept+"%' LIMIT 1";
//                " and d.turn_down_range in('"+turnDownRange+"','3') and d.dept like '%"+dept+"%' and d.diagnosis like '%"+diagnosis+"%' LIMIT 1";
        List<RehabilitationPlanTemplateDO> diseaseList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(RehabilitationPlanTemplateDO.class));
        if(diseaseList.size()==0){
            return null;
@ -306,248 +431,7 @@ public class SynchronizePatientService  {
    //基卫补推送出院小结后,重新下转
    public StringBuilder reSynchronizePation(String type,String hospital,String createTime) throws Exception{
        StringBuilder results = new StringBuilder("居民下转\n");
        List<RehabilitationPatientInfoDO> rehabilitationPatientInfoDOs;
        Date nowDate = DateUtil.strToDate(createTime);
        Date preTime = DateUtil.getPreDays(nowDate,-30);
        if (StringUtils.isBlank(type)){//为空
            results.append("未分配居民下转type:"+type+"\n");
            rehabilitationPatientInfoDOs = rehabilitationPatientInfoDao.findUnDispation(preTime,hospital);
        }
        else{
            Integer typeInt = Integer.parseInt(type);
            results.append("指定状态居民下转type:"+type+"\n");
            rehabilitationPatientInfoDOs = rehabilitationPatientInfoDao.findUnDispationByStatus(typeInt,preTime,hospital);
        }
        logger.info("康复计划自动下转————需要下转的居民人数" + rehabilitationPatientInfoDOs.size());
        results.append("需要下转的居民人数" + rehabilitationPatientInfoDOs.size() + "\n");
        List<RehabilitationPatientInfoDO> modifyList = new ArrayList<>();
        for (RehabilitationPatientInfoDO re : rehabilitationPatientInfoDOs) {
            List<RehabilitationPatientInfoDO> tmpList = getPatientInfoList(re.getIdcard(),DateUtil.dateToStrShort(re.getCreateTime()));
            Date diagnoseTime = re.getDiagnoseTime();
            //诊断时间为空或超过一个月 也不做下转
            if (diagnoseTime==null){
                infoUpdate(tmpList,4,modifyList,null);
                continue;
            }
            if (DateUtil.getDays(nowDate,diagnoseTime)>30){
                infoUpdate(tmpList,4,modifyList,null);
                continue;
            }
            BasePatientDO patient = null;
            if(StringUtils.isBlank(re.getIdcard())){
                infoUpdate(tmpList,5,modifyList,null);
                saveModifyList(modifyList);
                results.append("下转数据错误,身份证号不存在\n");
                continue;
            }
            if(StringUtils.isBlank(re.getPatient())){
                List<BasePatientDO> patientList = patientDao.getPatientByIdcardOrSsc(re.getIdcard());//获取患者信息
                if (patientList.size() == 0) {
                    //未找到居民,从健康档案添加居民
                    patient = patientService.addPaitentByIdcard(re.getIdcard(),re.getName(),re.getSsc(),re.getMobile(),re.getSex());
                    if (patient == null) {
                        infoUpdate(tmpList,5,modifyList,null);
                        saveModifyList(modifyList);
                        results.append("居民信息不存在\n");
                        continue;
                    } else {
                        patientList = patientDao.getPatientByIdcardOrSsc(re.getIdcard());//重新获取该患者信息
                        patient = patientList.get(0);
                    }
                }
                infoUpdate4(tmpList,patient.getId(),modifyList);
            }else {
                patient = patientDao.findByIdAndDel(re.getPatient(),"1");
            }
            String dept = re.getDept();
            String diagnosis = re.getDiagnosis();
            //三院专病配置
            RehabilitationPlanTemplateDO planTemplateDO = findPlanTemplate(dept,diagnosis);
            if(planTemplateDO==null){
                results.append("未找到满足条件的专病配置\n");
                continue;
            }
            if(planTemplateDO.getIsFamily()==1){
                //判断签约的才推送i健康
                JSONObject isSign = businessService.isSign(re.getIdcard());
                if(isSign==null){
                    results.append("推送i健康失败\n");
                    continue;
                }
                if(isSign.getJSONObject("obj")!=null) {
                    //推送i健康数据
                    infoUpdate2(tmpList,planTemplateDO.getFamilyRelation(),modifyList);
                    saveModifyList(modifyList);
                    com.alibaba.fastjson.JSONObject jsonObject = businessService.pushPatientInfos(re);
                    if(jsonObject==null||jsonObject.getInteger("status")==-1){
                        results.append("推送i健康失败\n");
                        continue;
                    }
                    Long ijkId = jsonObject.getLong("data");
                    infoUpdate3(tmpList,3,ijkId,modifyList,null);
                    saveModifyList(modifyList);
                    results.append("推送i健康成功\n");
                    continue;
                }
            }
            String diseaseId = planTemplateDO.getDiseaseId();
            String diseaseName = planTemplateDO.getDiseaseName();
            String planTemplateId = planTemplateDO.getId();
            String planDoctorId = planTemplateDO.getPlanDoctor();//计划负责人
            BaseDoctorDO planDoctor = doctorDao.findByIdAndDel(planDoctorId);
            //同步病历 //如果同步病历失败,不做下转
            String result = "";
            if (demoFlag) {//测试线获取病历模板
                result = patientRecordService.getJosnFileResullt("event" + "2");
            } else {
//                try {
//                    JSONObject jsonEvent = new JSONObject();
//                    List<Map<String, String>> resultMap = patientRecordService.getAllEvent_new(patient.getId(), "2", "1", "1", "2010-10-10 00:00:00", hos.getCode());
//                    jsonEvent.put("data", JSON.parseArray(JSON.toJSONString(resultMap)));
//                    result = jsonEvent.toString();
//                }catch (Exception e){
//                    infoUpdate(tmpList,3,modifyList,null);
//                    results.append("同步患者病历:" + re.getIdcard() + "----无住院病历信息\n");
//                    logger.info("康复计划自动下转————" + "同步患者病历:" + re.getIdcard() + "----无住院病历信息");
//                    continue;
//                }
            }
            com.alibaba.fastjson.JSONObject rejson = com.alibaba.fastjson.JSONObject.parseObject(result);
            JSONArray temlist = rejson.getJSONArray("data");
            if (0 == temlist.size()) {
                results.append("同步患者病历:" + re.getIdcard() + "----无住院病历信息\n");
                logger.info("康复计划自动下转————" + "同步患者病历:" + re.getIdcard() + "----无住院病历信息");
                infoUpdate(tmpList,3,modifyList,null);
//                if(!isPatientExist){//患者不存在与医生原有的康复列表中,添加推送消息
//                    successSync = addSyncPatientInfo(successSync, doctor.getId(), doctor.getName(), teamId, adminTeam.getName(), hos.getCode(), hos.getName(), patient.getId(),0);
//                }
                continue;
            }
//            if (!needCreateRehabilitationPlan(hos.getCode())) {//仅厦心进行自动下转至已下转 //厦心不推送消息
//                if(!isPatientExist){//患者不存在与医生原有的康复列表中,添加推送消息
//                    successSync = addSyncPatientInfo(successSync, doctor.getId(), doctor.getName(), teamId, adminTeam.getName(), hos.getCode(), hos.getName(), patient.getId(),0);
//                }
//                continue;
//            }
            com.alibaba.fastjson.JSONObject tem = temlist.getJSONObject(0);
            /**
             * {
             "orgName": "厦门大学附属心血管病医院",
             "createTime": "2013-09-26 10:13:38",
             "patient": "386a35b8d17a47cbab6174ae7952b9b6",
             "orgCode": "182",
             "dataFrom": "1",
             "id": "9f35ff1f-f683-4f3c-a0a5-7ff8ef3df89e",
             "": "2",
             "dianosis": "高血压2级",
             "eventDate": "2013-09-26 10:13:38"
             }
             */
            PatientMedicalRecordsDO pmr = new PatientMedicalRecordsDO();
            pmr.setHospitalName(tem.getString("orgName"));
            pmr.setHospital(tem.getString("orgCode"));
            if (demoFlag) {//测试获取为病历模板 hospitalcode获取为自己的code
//                pmr.setHospital(hos.getCode());
            }
            pmr.setDischargeDiagnosis(re.getDiagnosis());
            pmr.setDischargeDiagnosisName(re.getDiagnosisName());
            pmr.setAdmittingDiagnosis(re.getDiagnosis());
            pmr.setJwpatient(tem.getString("patient"));
            pmr.setAdmittingDiagnosisName(re.getDiagnosisName());
            pmr.setEvent(tem.getString("id"));
            pmr.setDataFrom(tem.getString("dataFrom"));
            pmr.setAdvice("出院继续观察");
            if (tem.getString("dataFrom").equals("4"))//3中山 4智业
            {
//                if (StringUtils.isNoneBlank(diagnosisIn)){//入院诊断
//                pmr.setAdmittingDiagnosisName(diagnosisIn);
//            }
//            if (StringUtils.isNoneBlank(diagnosisOut)){//出院诊断
//                pmr.setDischargeDiagnosisName(diagnosisOut);
//            }
            }
            pmr.setDiseaseCode(diseaseId);//疾病code
            pmr.setDiseaseName(diseaseName);//疾病名称
            //创建居民住院病历
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            PatientMedicalRecordsDO patientMedicalRecordsDO1 = rehabilitationInfoService.createMedicalRecords(planDoctorId, patient.getId(), patient.getName(), pmr, null);
            if (patientMedicalRecordsDO1 == null) {
                results.append("创建病历请求:" + re.getIdcard() + "----创建病历失败\n");
                logger.info("康复计划自动下转————" + "创建病历请求:" + re.getIdcard() + "----创建病历失败");
                infoUpdate(tmpList,2,modifyList,null);
//                if(!isPatientExist){//患者不存在与医生原有的康复列表中,添加推送消息
//                    successSync = addSyncPatientInfo(successSync, doctor.getId(), doctor.getName(), teamId, adminTeam.getName(), hos.getCode(), hos.getName(), patient.getId(),0);
//                }
                continue;
            } else {//
                // ↓创建康复计划。创建完成即为已下转
                PatientRehabilitationPlanDO planDO = new PatientRehabilitationPlanDO();
                planDO.setStatus(3);//待分配 执行医生和科室
                planDO.setPatient(patient.getId());
                planDO.setName(patient.getName());
                planDO.setTitle(patient.getName()+"的康复计划");
                planDO.setHealthStatusCode("2");
                planDO.setPlanType(1);
                planDO.setPayment(2);
                planDO.setAdviceContent("出院继续观察");
                planDO.setMedicalRecordsCode(patientMedicalRecordsDO1.getCode());//居民住院病历code
                planDO.setPlanDoctor(planDoctorId);
                planDO.setPlanDoctorName(planDoctor.getName());
                planDO.setPatientInfoCode(re.getCode());
                planDO.setCreateTime(new Date());
                planDO.setUpdateTime(new Date());
                planDO.setDisease(diseaseId);
                planDO.setDiseaseName(diseaseName);
//            planDO.setTotalExpense();
                //目前默认为冠心病
                //创建康复计划
                planDO = createRehabilitationPlanJson(planDO,planTemplateId,results,re);
                if (planDO == null) {//创建康复计划不成功,无法下转
                    results.append("创建康复计划请求:" + re.getIdcard() + "----创建康复计划请求失败\n");
                    logger.info("康复计划自动下转————" + "创建康复计划请求:" + re.getIdcard() + "----创建康复计划请求失败");
                    infoUpdate(tmpList,2,modifyList,null);
//                    if(!isPatientExist){//患者不存在与医生原有的康复列表中,添加推送消息
//                        successSync = addSyncPatientInfo(successSync, doctor.getId(), doctor.getName(), teamId, adminTeam.getName(), hos.getCode(), hos.getName(), patient.getId(),0);
//                    }
                    continue;
                } else {//创建康复计划成功
                    String planId = planDO.getId();
                    Date date = new Date();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String relationId = " ";
                    //居民专科标签。
                    List<SignPatientLabelInfo> healthList = signPatientLabelInfoDao.findByPatientAndLabelTypeAndStatus(patient.getId(), "8", 1);
                    if (healthList.size() > 0) {
                        //先删除已有健康情况标签
                        signPatientLabelInfoDao.deleteByPatientAndLabelTypeAndStatus(patient.getId(), "8", 1);
                    }
                    SignPatientLabelInfo signPatientLabelInfo = new SignPatientLabelInfo();
                    signPatientLabelInfo.setPatient(patient.getId());
                    signPatientLabelInfo.setPname(patient.getName());
                    signPatientLabelInfo.setLabel("2");
                    signPatientLabelInfo.setLabelName("出院康复");
                    signPatientLabelInfo.setLabelType("8");
                    signPatientLabelInfo.setStatus(1);
                    signPatientLabelInfo.setCzrq(new Date());
                    signPatientLabelInfoDao.save(signPatientLabelInfo);
                    infoUpdate(tmpList,1,modifyList,null);
//                    successSync = addSyncPatientInfo(successSync, doctor.getId(), doctor.getName(), teamId, adminTeam.getName(), hos.getCode(), hos.getName(), patient.getId(),1);
                    results.append("下转结束:" + re.getIdcard() + "----下转成功\n");
                    logger.info("康复计划自动下转————" +"下转结束:" + re.getIdcard() + "----下转成功");
                    //给服务医生群组发送下转消息
//                    if (StringUtils.isNoneBlank(planId)){
//                        asynService.sendMsg(planId,signFamily,patient,doctor,patientMedicalRecordsDO1,re);
//                    }
                }
            }
        }
        rehabilitationPatientInfoDao.saveAll(modifyList);
        return results;
    }
@ -555,7 +439,8 @@ public class SynchronizePatientService  {
    public StringBuilder synchronizePation(String type) throws Exception {
        StringBuilder results = new StringBuilder("居民下转\n");
        Date nowDate = new Date();
        String preTimeStr = DateUtil.dateToStrShort(DateUtil.getPreDays(nowDate,-30));
//        String preTimeStr = DateUtil.dateToStrShort(DateUtil.getPreDays(nowDate,-30));
        String preTimeStr = DateUtil.getStringDateShort();
        String sql = "";
        if (StringUtils.isBlank(type)){//为空
            results.append("未分配居民下转type:"+type+"\n");
@ -567,12 +452,11 @@ public class SynchronizePatientService  {
        List<BasePatientDischargeRecord> patientDischargeRecords = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(BasePatientDischargeRecord.class));
        logger.info("康复计划自动下转————需要下转的居民人数" + patientDischargeRecords.size());
        results.append("需要下转的居民人数" + patientDischargeRecords.size() + "\n");
        List<BasePatientDischargeRecord> modifyList = new ArrayList<>();
        for (BasePatientDischargeRecord re : patientDischargeRecords) {
            String idcard = re.getIdcard();
            if(StringUtils.isBlank(idcard)){
                re.setStatus("2");
                basePatientDischargeRecordDao.equals(re);
                re.setStatus("-1");
                basePatientDischargeRecordDao.save(re);
                continue;
            }
            String content = re.getContent();
@ -583,8 +467,8 @@ public class SynchronizePatientService  {
                e.printStackTrace();
            }
            if(json==null){
                re.setStatus("2");
                basePatientDischargeRecordDao.equals(re);
                re.setStatus("-1");
                basePatientDischargeRecordDao.save(re);
                continue;
            }
//            List<BasePatientDischargeRecord> tmpList = getPatientInfoList(re.getIdcard(),DateUtil.dateToStrShort(re.getCreateTime()));
@ -597,268 +481,397 @@ public class SynchronizePatientService  {
//            if (DateUtil.getDays(nowDate,diagnoseTime)>30){
//                dischargeUpdate(tmpList,"4",modifyList);
//                continue;
//            }
//            //去除智业获取的厦心患者,智业获取到的一定有problemCode
//            if(StringUtils.isNoneBlank(re.getProblemCode())){
//                dischargeUpdate(tmpList,"2",modifyList);
//                continue;
//            }
            //"idcard":"510722201908261751","patientName":"龚嘉乐","cardNo":"510722201908261751" "conNo":"9","visitNo":"1727810009"}
            String name = json.getString("patientName");
            String cardNo = json.getString("cardNo");
            String conNo = json.getString("conNo");//就诊次数
            String visitNo = json.getString("visitNo");//就诊号
            //创建下转记录表
            RehabilitationPatientInfoDO infoDO = rehabilitationPatientInfoDao.findByVisitNo(idcard,conNo,visitNo);
            if(infoDO==null){
                infoDO = new RehabilitationPatientInfoDO();
                infoDO.setStatus(0);
                infoDO.setCode(getCode());
                infoDO.setCreateTime(new Date());
                infoDO.setName(name);
                infoDO.setIdcard(idcard);
                infoDO.setFromSource(2);
                infoDO.setConNo(conNo);
                infoDO.setVisitNo(visitNo);
                infoDO.setSignStatus(0);
                infoDO.setDischargeRecordId(re.getId());
                rehabilitationPatientInfoDao.save(infoDO);
                re.setStatus("1");
                basePatientDischargeRecordDao.save(re);
            }
            if(infoDO.getStatus()!=0){
                results.append("重复下推\n");
                re.setStatus("2");
                basePatientDischargeRecordDao.save(re);
                continue;
            }
            BasePatientDO patient = null;
            List<BasePatientDO> patientList = patientDao.getPatientByIdcard(re.getIdcard());//获取患者信息
            JSONArray cardList = dsyyPrescriptionService.findCardNo(idcard);
            if (patientList.size() == 0) {
                //未找到居民,从his视图添加居民
                patient = dsyyPrescriptionService.addPaitentByIdcard(re.getIdcard(),name);
                patient = dsyyPrescriptionService.addPaitentByIdcard(cardList,re.getIdcard(),name);
                if (patient == null) {
                    re.setStatus("3");
                    basePatientDischargeRecordDao.equals(re);
                    infoDO.setStatus(5);
                    rehabilitationPatientInfoDao.save(infoDO);
                    results.append("居民信息不存在\n");
                    continue;
                } else {
                    patientList = patientDao.getPatientByIdcardOrSsc(re.getIdcard());//重新获取该患者信息
                    patient = patientList.get(0);
                }
            }else {
                patient = patientList.get(0);
            }
            if(cardList==null){
                infoDO.setStatus(9);
                rehabilitationPatientInfoDao.save(infoDO);
                results.append("就诊卡信息不存在\n");
                continue;
            }
            JSONArray jaMzbl = new JSONArray();
            JSONArray jaCy = new JSONArray();
            infoDO.setSex(patient.getSex());
//            infoDO.setMobile(patient.getMobile());
            infoDO.setPatient(patient.getId());
            infoDO.setIdcard(patient.getIdcard());
            infoDO.setAge(IdCardUtil.getAgeByBirthdayOrIdcard(patient.getIdcard(), patient.getBirthday()));
            String ssc = null;
            String mobile = null;
            infoDO.setAddress(patient.getAddress());
            JSONObject jaMzbl = new JSONObject();
            JSONObject jaCy = new JSONObject();
            String hisPid = null;
            String eventType = "";//1门诊 2住院
            try {
                //门诊病历
                String mzbl = dsyyPrescriptionService.selectReportInfo("JHIDS-USD-HLWMZBL-014","",conNo,1,1);
                if(StringUtils.isNotBlank(mzbl)){
                    jaMzbl = JSONArray.parseArray(mzbl);
                }
                //出院小结
                String cyxj = dsyyPrescriptionService.selectReportInfo("JHIDS-USD-HLWCYXJ-013","",conNo,1,1);
                if(StringUtils.isNotBlank(cyxj)){
                    jaCy = JSONArray.parseArray(cyxj);
                for (int i=0;i<cardList.size();i++){
                    JSONObject tmp = cardList.getJSONObject(i);
                    String SICK_ID = tmp.getString("SICK_ID");
                    String CARD_NO = tmp.getString("CARD_NO");
                    String LXDH = tmp.getString("LXDH");
                    //门诊病历
                    if(StringUtils.isBlank(eventType)){
                        String mzbl = dsyyPrescriptionService.selectReportInfo("JHIDS-USD-HLWMZBL-014",SICK_ID,conNo,1,1);
                        if(StringUtils.isNotBlank(mzbl)&&!"[]".equals(mzbl)){
                            jaMzbl = JSONArray.parseArray(mzbl).getJSONObject(0);
                            eventType = "1";
                            hisPid = SICK_ID;
                            ssc = CARD_NO;
                            mobile = LXDH;
                        }
                    }
                    if(StringUtils.isBlank(eventType)){
                        //出院小结
                        String cyxj = dsyyPrescriptionService.selectReportInfo("JHIDS-USD-HLWCYXJ-013",SICK_ID,conNo,1,1);
                        if(StringUtils.isNotBlank(cyxj)&&!"[]".equals(cyxj)){
                            jaCy = JSONArray.parseArray(cyxj).getJSONObject(0);
                            eventType = "2";
                            hisPid = SICK_ID;
                            ssc = CARD_NO;
                            mobile = LXDH;
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            if(StringUtils.isBlank(eventType)){
                re.setStatus("4");
                basePatientDischargeRecordDao.equals(re);
                continue;
            }
            //同步病历 //如果同步病历失败,不做下转
            String result = "";
            if (demoFlag) {//测试线获取病历模板
                result = patientRecordService.getJosnFileResullt("event2");
            } else {
//                try {
//                    JSONObject jsonEvent = new JSONObject();
//                    List<Map<String, String>> resultMap = patientRecordService.getAllEvent_new(patient.getId(), "2", "1", "1", "2010-10-10 00:00:00", hos.getCode());
//                    jsonEvent.put("data", JSON.parseArray(JSON.toJSONString(resultMap)));
//                    result = jsonEvent.toString();
//                }catch (Exception e){
//                    infoUpdate(tmpList,3,modifyList,null);
//                    results.append("同步患者病历:" + re.getIdcard() + "----无住院病历信息\n");
//                    logger.info("康复计划自动下转————" + "同步患者病历:" + re.getIdcard() + "----无住院病历信息");
//                    continue;
//                }
            }
            com.alibaba.fastjson.JSONObject rejson = com.alibaba.fastjson.JSONObject.parseObject(result);
            JSONArray temlist = rejson.getJSONArray("data");
            if (0 == temlist.size()) {
                results.append("同步患者病历:" + re.getIdcard() + "----无住院病历信息\n");
                logger.info("康复计划自动下转————" + "同步患者病历:" + re.getIdcard() + "----无住院病历信息");
                infoDO.setStatus(3);
                rehabilitationPatientInfoDao.save(infoDO);
                results.append("患者无门诊病历或患者无出院小结\n");
                continue;
            }
            com.alibaba.fastjson.JSONObject tem = temlist.getJSONObject(0);
            //创建下转记录表
            RehabilitationPatientInfoDO infoDO = new RehabilitationPatientInfoDO();
            infoDO.setPatient(patient.getId());
            infoDO.setStatus(0);
            infoDO.setIdcard(patient.getIdcard());
            infoDO.setAge(IdCardUtil.getAgeByBirthdayOrIdcard(patient.getIdcard(), patient.getBirthday()));
            infoDO.setSsc(patient.getSsc());
            infoDO.setAddress(patient.getAddress());
            infoDO.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
            infoDO.setCreateTime(new Date());
            infoDO.setName(patient.getName());
            infoDO.setSex(patient.getSex());
            infoDO.setMobile(patient.getMobile());
            infoDO.setFromSource(2);
            infoDO.setSignStatus(0);
            infoDO.setDischargeRecordId(re.getId());
            rehabilitationPatientInfoDao.save(infoDO);
            infoDO.setSsc(ssc);
            infoDO.setMobile(mobile);
            infoDO.setHisPid(hisPid);
            infoDO.setEventType(eventType);
            String dept = "科室";
//            String dept = re.getDept();
//            String diagnosis = re.getDiagnosis();
            String deptName = null;
            String diagnosis = "诊断";
            String doctorId = null;
            String doctorName = null;
            String doctorIdMz = null;//门诊医生
            String doctorNameMz = null;
            String doctorIdZy = null;//住院医生
            String doctorNameZy = null;
            String mzTime = null;
            String zyTime = null;
            PatientMedicalRecordsDO pmr = new PatientMedicalRecordsDO();
            pmr.setPatient(patient.getId());
            pmr.setPatientName(patient.getName());
            pmr.setCode(getCode());
            pmr.setDataFrom("1");
            pmr.setCreateTime(new Date());
            pmr.setJwpatient(hisPid);
            pmr.setEventType(eventType);
            pmr.setConNo(conNo);
            if("1".equals(eventType)){
                //门诊
                String ASSISTEXAMINATION = jaMzbl.getString("ASSISTEXAMINATION");//辅助检查
                String JHDL_CREATED_AT = jaMzbl.getString("JHDL_CREATED_AT");//": "2025-06-18T16:32:52.000+0000",
                String MEDICALHISTORY = jaMzbl.getString("MEDICALHISTORY");//现病史
                String EMRPDF = jaMzbl.getString("EMRPDF");//电子病历详情pdf
                String PHYSICALEXAMINATION = jaMzbl.getString("PHYSICALEXAMINATION");//体格检查
                String JHDL_UPDATED_AT = jaMzbl.getString("JHDL_UPDATED_AT");//": "2025-06-18T16:32:52.000+0000",
                String VISIT_ID = jaMzbl.getString("VISIT_ID");//就诊次数
//                String JHDL_ROWKEY = jaMzbl.getString("JHDL_ROWKEY");//": 5620492334960637262,
                String PASTHISTORY = jaMzbl.getString("PASTHISTORY");//既往史
                String PATIENT_ID = jaMzbl.getString("PATIENT_ID");//居民id
//                String ID = jaMzbl.getString("ID");//": "42661889-5-6000861496-0-73-0-1",
                String COMPLAINT = jaMzbl.getString("COMPLAINT");//主诉
//                String JHDL_SRC_TAB = jaMzbl.getString("JHDL_SRC_TAB");//": "JHDL:01_HLW_MZBL",
//                String LAST_MODIFY_DATE_TIME = jaMzbl.getString("LAST_MODIFY_DATE_TIME");//": "2025-06-18 08:29:07"
                //查询历史门诊记录获取科室和医生
                try {
                    WlyyOutpatientVO outpatientVO = dsyyPrescriptionService.selectOutpatientInfoByHisId(hisPid,conNo);
                    dept = outpatientVO.getDept();
                    deptName = outpatientVO.getDeptName();
//                    List<DoctorMappingDO> doctorMappingDOS = doctorMappingDao.findByMappingCode(outpatientVO.getDoctor());
//                    if(doctorMappingDOS.size()>0){
//                        doctorIdMz = doctorMappingDOS.get(0).getDoctor();
//                    }
                    doctorNameMz = outpatientVO.getDoctorName();
                    mzTime = DateUtil.dateToStrLong(outpatientVO.getConDate());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                //住院
                String ATTENDINGPHYSICIAN = jaCy.getString("ATTENDINGPHYSICIAN");//黎喜梅 主治医师
                String DISCHARGEDISEASE = jaCy.getString("DISCHARGEDISEASE");//出院诊断
                String ADMISSIONDAY = jaCy.getString("ADMISSIONDAY");//5, 住院天数
//                String BIRTH = jaCy.getString("BIRTH");//1968-12-02 00:00:00", 出生日期
//                String ID = jaCy.getString("ID");//42661889-5-6000861496-2-9-0-20",
//                String LAST_MODIFY_DATE_TIME = jaCy.getString("LAST_MODIFY_DATE_TIME");//2025-05-13 21:16:12",
//                String BEDNO = jaCy.getString("BEDNO");//A12-46",
                String DISCHARGEDESC = jaCy.getString("DISCHARGEDESC");//出院时情况
                String RESIDENTPHYSICIAN = jaCy.getString("RESIDENTPHYSICIAN");//夏小艺 住院医师
                String ADMISSIONNO = jaCy.getString("ADMISSIONNO");//326405",住院号
//                String JHDL_CREATED_AT = jaCy.getString("JHDL_CREATED_AT");//2025-05-13T16:02:07.000+0000",
                String ADMISSIONDISEASE = jaCy.getString("ADMISSIONDISEASE");//入院诊断
                String NAME = jaCy.getString("NAME");//李兴英 居民姓名
                String DATE = jaCy.getString("DATE");//2025-05-10 08:11:38",填写日期
//                String JHDL_UPDATED_AT = jaCy.getString("JHDL_UPDATED_AT");//2025-05-13T16:02:07.000+0000",
                String VISIT_ID = jaCy.getString("VISIT_ID");//9 就诊次数
                String DEPTNAME = jaCy.getString("DEPTNAME");//肿瘤科",//科室名称
                String DISCHARGETIME = jaCy.getString("DISCHARGETIME");//2025-05-11 08:03:15 出院时间
                String TREATMENTCOURSE = jaCy.getString("TREATMENTCOURSE");//主要诊疗经过
                String DISCHARGEORDER = jaCy.getString("DISCHARGEORDER");//出院医嘱
//                String JHDL_ROWKEY = jaCy.getString("JHDL_ROWKEY");//4179340454200282426,
                String ADMISSIONDESC = jaCy.getString("ADMISSIONDESC");//入院情况
                String PATIENT_ID = jaCy.getString("PATIENT_ID");//6000861496 居民id
                String ATTENDNUMBER = jaCy.getString("ATTENDNUMBER");//326405 住院号
//                String JHDL_SRC_TAB = jaCy.getString("JHDL_SRC_TAB");//JHDL:01_HLW_CYXJ",
                String ADMISSIONTIME = jaCy.getString("ADMISSIONTIME");//2025-05-06 08:23:10 入院时间
                pmr.setAdmissionTime(DateUtil.strToDate(ADMISSIONTIME));
                pmr.setDischargeTime(DateUtil.strToDate(DISCHARGETIME));
                pmr.setAdmittingDiagnosisName(ADMISSIONDISEASE);
                pmr.setDischargeDiagnosisName(DISCHARGEDISEASE);
                pmr.setAdvice(DISCHARGEORDER);
                deptName = DEPTNAME;
                dept = findDeptByName(DEPTNAME);
                doctorNameZy = RESIDENTPHYSICIAN;
                pmr.setDept(dept);
                pmr.setDeptName(deptName);
                zyTime = DISCHARGETIME;
            }
            infoDO.setDeptName(deptName);
            infoDO.setDept(dept);
            //三院专病配置
            RehabilitationPlanTemplateDO planTemplateDO = findPlanTemplate(dept,diagnosis,eventType);
            if(planTemplateDO==null){
                re.setStatus("5");
                basePatientDischargeRecordDao.equals(re);
                results.append("未找到满足条件的专病配置\n");
                infoDO.setStatus(2);
                rehabilitationPatientInfoDao.save(infoDO);
                continue;
            }
            if(planTemplateDO.getIsFamily()==1){
                //判断签约的才推送i健康
                JSONObject isSign = businessService.isSign(re.getIdcard());
                if(isSign==null){
                    re.setStatus("6");
                    basePatientDischargeRecordDao.equals(re);
                    results.append("推送i健康失败\n");
            infoDO.setDiseaseId(planTemplateDO.getDiseaseId());
            infoDO.setDiseaseName(planTemplateDO.getDiseaseName());
            infoDO.setTemplatePlanId(planTemplateDO.getId());
            infoDO.setTemplatePlanName(planTemplateDO.getTitle());
            if("1".equals(eventType)){
                doctorIdMz = findDoctorByName(doctorNameMz,planTemplateDO.getDepts());
                if(StringUtils.isBlank(doctorIdMz)){
                    infoDO.setStatus(4);
                    rehabilitationPatientInfoDao.save(infoDO);
                    continue;
                }
                infoDO.setSignStatus(1);
                rehabilitationPatientInfoDao.save(infoDO);
                if(isSign.getJSONObject("obj")!=null) {
                    //推送i健康数据
                    com.alibaba.fastjson.JSONObject jsonObject = businessService.pushPatientInfos(infoDO);
                    if(jsonObject==null||jsonObject.getInteger("status")==-1){
                        re.setStatus("6");
                        basePatientDischargeRecordDao.equals(re);
                        results.append("推送i健康失败\n");
                        continue;
                    }
                    Long ijkId = jsonObject.getLong("data");
                    infoDO.setIjkId(ijkId);
            }else {
                doctorIdZy = findDoctorByName(doctorNameZy,planTemplateDO.getDepts());
                if(StringUtils.isBlank(doctorIdZy)){
                    infoDO.setStatus(4);
                    rehabilitationPatientInfoDao.save(infoDO);
                    re.setStatus("7");
                    basePatientDischargeRecordDao.equals(re);
                    results.append("推送i健康成功\n");
                    continue;
                }
            }
            if(planTemplateDO.getIsFamily()==1){
                pushIjk(planTemplateDO,re,infoDO);
                continue;
            }
            // ↓创建康复计划。创建完成即为已下转
            PatientRehabilitationPlanDO planDO = new PatientRehabilitationPlanDO();
            String diseaseId = planTemplateDO.getDiseaseId();
            String diseaseName = planTemplateDO.getDiseaseName();
            String planTemplateId = planTemplateDO.getId();
            String planDoctorType = planTemplateDO.getPlanDoctorType();//计划负责人 1手动获取,2自动获取
            String planDoctorId = planTemplateDO.getPlanDoctor();//类型=1康复计划负责人,类型2  1主管医生 2主治医生
            String planDoctorId = planTemplateDO.getPlanDoctor();//类型=1康复计划负责人,类型2  1门诊医生 2住院医生
            String distributionType = planTemplateDO.getDistributionType();//分配方式 1手动分配 2自动分配(分配康复计划项的执行医生)
            String distributionTo = planTemplateDO.getDistributionTo();//分配对象 1主管医生 2主治医生
            String distributionTo = planTemplateDO.getDistributionTo();//分配对象 1门诊医生 2住院医生
            BaseDoctorDO planDoctor = null;
            BaseDoctorDO zgDoctor = null;//主管医生
            BaseDoctorDO zzDoctor = null;//主治医生
            if("1".equals(planDoctorType)){
                planDoctor = doctorDao.findByIdAndDel(planDoctorId);
                planDO.setPlanDoctor(planDoctorId);
                planDO.setPlanDoctorName(planDoctor.getName());
            }else {
                if("1".equals(planDoctorId)){
                    //1主管医生
                    //1门诊医生
                    doctorId = doctorIdMz;
                    doctorName = doctorNameMz;
                }else {
                    //2主治医生
                    //2住院医生
                    doctorId = doctorIdZy;
                    doctorName = doctorNameZy;
                }
                planDO.setPlanDoctor(doctorId);
                planDO.setPlanDoctorName(doctorName);
            }
            infoDO.setDoctor(doctorId);
            infoDO.setDoctorName(doctorName);
            /**
             * {
             "orgName": "厦门大学附属心血管病医院",
             "createTime": "2013-09-26 10:13:38",
             "patient": "386a35b8d17a47cbab6174ae7952b9b6",
             "orgCode": "182",
             "dataFrom": "1",
             "id": "9f35ff1f-f683-4f3c-a0a5-7ff8ef3df89e",
             "": "2",
             "dianosis": "高血压2级",
             "eventDate": "2013-09-26 10:13:38"
             }
             */
            PatientMedicalRecordsDO pmr = new PatientMedicalRecordsDO();
            pmr.setHospitalName(tem.getString("orgName"));
            pmr.setHospital(tem.getString("orgCode"));
            if (demoFlag) {//测试获取为病历模板 hospitalcode获取为自己的code
//                pmr.setHospital(hos.getCode());
            }
//            pmr.setDischargeDiagnosis(re.getDiagnosis());
//            pmr.setDischargeDiagnosisName(re.getDiagnosisName());
//            pmr.setAdmittingDiagnosis(re.getDiagnosis());
            pmr.setJwpatient(tem.getString("patient"));
//            pmr.setAdmittingDiagnosisName(re.getDiagnosisName());
            pmr.setEvent(tem.getString("id"));
            pmr.setDataFrom(tem.getString("dataFrom"));
            pmr.setAdvice("出院继续观察");
            if (tem.getString("dataFrom").equals("4"))//3中山 4智业
            {
//                if (StringUtils.isNoneBlank(diagnosisIn)){//入院诊断
//                pmr.setAdmittingDiagnosisName(diagnosisIn);
//            }
//            if (StringUtils.isNoneBlank(diagnosisOut)){//出院诊断
//                pmr.setDischargeDiagnosisName(diagnosisOut);
//            }
            if("2".equals(eventType)){
                planDO.setMedicalRecordsCode(pmr.getCode());//居民住院病历code
            }
            pmr.setDiseaseCode(diseaseId);//疾病code
            pmr.setDiseaseName(diseaseName);//疾病名称
            //创建居民住院病历
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            PatientMedicalRecordsDO patientMedicalRecordsDO1 = rehabilitationInfoService.createMedicalRecords(planDoctorId, patient.getId(), patient.getName(), pmr, null);
            planDO.setStatus(1);
            planDO.setPatient(patient.getId());
            planDO.setName(patient.getName());
            planDO.setTitle(patient.getName()+"的康复计划");
            planDO.setHealthStatusCode("2");
            planDO.setPlanType(1);
            planDO.setPayment(2);
            planDO.setAdviceContent("出院继续观察");
            if (patientMedicalRecordsDO1 == null) {
                results.append("创建病历请求:" + re.getIdcard() + "----创建病历失败\n");
                logger.info("康复计划自动下转————" + "创建病历请求:" + re.getIdcard() + "----创建病历失败");
            planDO.setPatientInfoCode(infoDO.getCode());
            planDO.setCreateTime(new Date());
            planDO.setUpdateTime(new Date());
            planDO.setDisease(diseaseId);
            planDO.setDiseaseName(diseaseName);
            //目前默认为冠心病
            //创建康复计划
            planDO = createRehabilitationPlanJson(planDO,planTemplateId,results,infoDO,distributionType,distributionTo,dept,deptName,doctorId,doctorName,mzTime,zyTime);
            if (planDO == null) {//创建康复计划不成功,无法下转
                infoDO.setStatus(2);
                rehabilitationPatientInfoDao.save(infoDO);
                results.append("创建康复计划请求:" + re.getIdcard() + "----创建康复计划请求失败\n");
                logger.info("康复计划自动下转————" + "创建康复计划请求:" + re.getIdcard() + "----创建康复计划请求失败");
                continue;
            } else {//
                // ↓创建康复计划。创建完成即为已下转
                PatientRehabilitationPlanDO planDO = new PatientRehabilitationPlanDO();
                planDO.setStatus(3);//待分配 执行医生和科室
                planDO.setPatient(patient.getId());
                planDO.setName(patient.getName());
                planDO.setTitle(patient.getName()+"的康复计划");
                planDO.setHealthStatusCode("2");
                planDO.setPlanType(1);
                planDO.setPayment(2);
                planDO.setAdviceContent("出院继续观察");
                planDO.setMedicalRecordsCode(patientMedicalRecordsDO1.getCode());//居民住院病历code
                planDO.setPlanDoctor(planDoctorId);
                planDO.setPlanDoctorName(planDoctor.getName());
                planDO.setPatientInfoCode(infoDO.getCode());
                planDO.setCreateTime(new Date());
                planDO.setUpdateTime(new Date());
                planDO.setDisease(diseaseId);
                planDO.setDiseaseName(diseaseName);
                //目前默认为冠心病
                //创建康复计划
                planDO = createRehabilitationPlanJson(planDO,planTemplateId,results,infoDO,distributionType,distributionTo,zgDoctor,zzDoctor);
                if (planDO == null) {//创建康复计划不成功,无法下转
                    results.append("创建康复计划请求:" + re.getIdcard() + "----创建康复计划请求失败\n");
                    logger.info("康复计划自动下转————" + "创建康复计划请求:" + re.getIdcard() + "----创建康复计划请求失败");
                    continue;
                } else {//创建康复计划成功
                    String planId = planDO.getId();
                    ////创建患者疾病类型 wlyy_patient_disease_server
                    String relationId = "";
                    //居民专科标签。
                    List<SignPatientLabelInfo> healthList = signPatientLabelInfoDao.findByPatientAndLabelTypeAndStatus(patient.getId(), "8", 1);
                    if (healthList.size() > 0) {
                        //先删除已有健康情况标签
                        signPatientLabelInfoDao.deleteByPatientAndLabelTypeAndStatus(patient.getId(), "8", 1);
                    }
                    SignPatientLabelInfo signPatientLabelInfo = new SignPatientLabelInfo();
                    signPatientLabelInfo.setPatient(patient.getId());
                    signPatientLabelInfo.setPname(patient.getName());
                    signPatientLabelInfo.setLabel("2");
                    signPatientLabelInfo.setLabelName("出院康复");
                    signPatientLabelInfo.setLabelType("8");
                    signPatientLabelInfo.setStatus(1);
                    signPatientLabelInfo.setCzrq(new Date());
                    signPatientLabelInfoDao.save(signPatientLabelInfo);
            } else {//创建康复计划成功
                if("2".equals(distributionType)){
                    infoDO.setStatus(7);
                }else {
                    infoDO.setStatus(1);
                    rehabilitationPatientInfoDao.save(infoDO);
                    re.setStatus("1");
                    basePatientDischargeRecordDao.equals(re);
                    results.append("下转结束:" + re.getIdcard() + "----下转成功");
                    logger.info("康复计划自动下转————" +"下转结束:" + re.getIdcard() + "----下转成功");
                }
                rehabilitationPatientInfoDao.save(infoDO);
                pmr.setDiseaseCode(diseaseId);//疾病code
                pmr.setDiseaseName(diseaseName);//疾病名称
                //创建居民住院病历
                createMedicalRecords(doctorId,doctorName,pmr);
                results.append("下转结束:" + re.getIdcard() + "----下转成功");
                logger.info("康复计划自动下转————" +"下转结束:" + re.getIdcard() + "----下转成功");
            }
        }
        return results;
    }
    //推送ijk
    public boolean pushIjk(RehabilitationPlanTemplateDO planTemplateDO,BasePatientDischargeRecord re,RehabilitationPatientInfoDO infoDO){
        try {
            //判断签约的才推送i健康
            JSONObject isSign = businessService.isSign(infoDO.getIdcard());
            if(isSign==null){
                infoDO.setStatus(10);
                rehabilitationPatientInfoDao.save(infoDO);
                return false;
            }
            infoDO.setProblemCode(planTemplateDO.getFamilyRelation());
            infoDO.setSignStatus(1);
            rehabilitationPatientInfoDao.save(infoDO);
            if(isSign.getJSONObject("obj")!=null) {
                //推送i健康数据
                com.alibaba.fastjson.JSONObject jsonObject = businessService.pushPatientInfos(infoDO);
                if(jsonObject==null||jsonObject.getInteger("status")==-1){
                    infoDO.setStatus(10);
                    rehabilitationPatientInfoDao.save(infoDO);
                    return false;
                }
                Long ijkId = jsonObject.getLong("data");
                infoDO.setIjkId(ijkId);
                infoDO.setStatus(11);
                rehabilitationPatientInfoDao.save(infoDO);
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 新增住院病历
     * @param doctorCode
     * @param patientMedicalRecordsDO
     * @return
     */
    public PatientMedicalRecordsDO createMedicalRecords(String doctorCode,String doctorName, PatientMedicalRecordsDO patientMedicalRecordsDO) {
        patientMedicalRecordsDO.setHospitalName("厦门市第三医院");
        patientMedicalRecordsDO.setHospital("350211A1004");
        patientMedicalRecordsDO.setCreateUser(doctorCode);
        patientMedicalRecordsDO.setCreateUserName(doctorName);
        patientMedicalRecordsDO.setCreateTime(new Date());
        patientMedicalRecordsDao.save(patientMedicalRecordsDO);
        return patientMedicalRecordsDO;
    }
    public String getCode(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    //查找科室编码
    public String findDeptByName(String deptName){
        String sql = "SELECT code from dict_hospital_dept where name = '"+deptName+"'";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(list.size()>0){
            return list.get(0).get("code")+"";
        }
        return null;
    }
    //查找医生编码
    public String findDoctorByName(String doctorName,String deptCode){
        if(StringUtils.isBlank(deptCode)){
            return null;
        }
        String sql = "SELECT d.id from base_doctor_hospital h,base_doctor d " +
                " WHERE h.dept_code in ('"+deptCode.replace(",","','")+"') and h.del='1' and h.doctor_code=d.id" +
                " and d.del='1' and d.`name`='"+doctorName+"'";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(list.size()>0){
            return list.get(0).get("id")+"";
        }
        return null;
    }
    /**
     * 创建康复计划json
     */
@ -896,11 +909,14 @@ public class SynchronizePatientService  {
     * 创建康复计划json
     */
    public PatientRehabilitationPlanDO createRehabilitationPlanJson(PatientRehabilitationPlanDO planDO, String planTemplateId,StringBuilder results
            , RehabilitationPatientInfoDO re,String distributionType,String distributionTo,BaseDoctorDO zgDoctor,BaseDoctorDO zzDoctor) throws Exception{
            , RehabilitationPatientInfoDO re,String distributionType,String distributionTo,String dept,String deptName
            ,String doctorId,String doctorName,String mzTime,String zyTime) throws Exception{
        String sql = "select * from wlyy_rehabilitation_template_detail where template_id = '" + planTemplateId + "'";
        List<RehabilitationTemplateDetailDO> templateDetail = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(RehabilitationTemplateDetailDO.class));
        if (templateDetail.size() == 0) {
            results.append("系统默认的康复模板请求:" + re.getIdcard() + "----系统默认的康复模板为空,请手动进行下转\n");
            if(results!=null){
                results.append("系统默认的康复模板请求:" + re.getIdcard() + "----系统默认的康复模板为空,请手动进行下转\n");
            }
            return null;
        }
        planDO = patientRehabilitationPlanDao.save(planDO);
@ -915,20 +931,13 @@ public class SynchronizePatientService  {
            detail.setUpdateTime(new Date());
            detail.setPlanId(planDO.getId());
            detail.setFrequencyCode(frequency_code);
            detail.setServerCount(detailDO.getServerCount());
            detail.setTimeType(Integer.parseInt(detailDO.getPlanStartTimeType()));
            detail.setDept(dept);
            detail.setDeptName(deptName);
            if("2".equals(distributionType)){
                if("1".equals(distributionTo)){
                    //1主管医生
//                    detail.setDept();
//                    detail.setDeptName();
                    detail.setDoctor(zgDoctor.getId());
                    detail.setDoctorName(zgDoctor.getName());
                }else {
                    //2主治医生
//                    detail.setDept();
//                    detail.setDeptName();
                    detail.setDoctor(zzDoctor.getId());
                    detail.setDoctorName(zzDoctor.getName());
                }
                detail.setDoctor(doctorId);
                detail.setDoctorName(doctorName);
            }
            detailDOList.add(detail);
        }
@ -947,9 +956,12 @@ public class SynchronizePatientService  {
                detailDO.setDept(newDetail.getDept());
                detailDO.setDeptName(newDetail.getDeptName());
                //生成执行计划列表
                planDOList = rehabilitationManageService.addServicePlan(serviceItemMap, planDO, detailDO, planDOList);
                planDOList = rehabilitationManageService.addServicePlan(serviceItemMap, planDO, detailDO, planDOList,mzTime,zyTime);
            }
        }
        if (planDOList.size() > 0) {
            serviceItemPlanDao.saveAll(planDOList);
        }
        rehabilitationManageService.addPlanLog(planDO.getId(),planDO.getPlanDoctor(),planDO.getPlanDoctorName());