瀏覽代碼

Merge branch '2.0' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into 2.0

wangzhinan 1 年之前
父節點
當前提交
f8649f544e
共有 51 個文件被更改,包括 3332 次插入7231 次删除
  1. 3 2
      business/base-service/src/main/java/com/yihu/jw/article/service/BaseMenuManageService.java
  2. 16 4
      business/base-service/src/main/java/com/yihu/jw/dict/service/HospitalDeptService.java
  3. 15 11
      business/base-service/src/main/java/com/yihu/jw/hospital/integrate/service/BaseHospitalUserActivityService.java
  4. 6 5
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/PrescriptionService.java
  5. 322 14
      business/es-service/src/main/java/com/yihu/jw/es/service/StatisticsEsService.java
  6. 1 1
      business/es-service/src/main/java/com/yihu/jw/es/util/ElasticsearchUtil.java
  7. 33 22
      business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java
  8. 1 1
      business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java
  9. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/base/im/ConsultTeamDo.java
  10. 67 27
      common/common-entity/src/main/java/com/yihu/jw/entity/base/servicePackage/ServiceItemPlanDO.java
  11. 17 13
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceOrderDO.java
  12. 4 4
      common/common-entity/src/main/java/com/yihu/jw/entity/followup/Followup.java
  13. 10 2
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/GuidanceMessageLogDO.java
  14. 74 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationDetailDO.java
  15. 2 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/hospital/statistics/ScreenQvo.java
  16. 3 3
      gateway/ag-basic/src/main/java/com/yihu/jw/gateway/filter/BasicZuulFilter.java
  17. 1 2
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/followup/DoctorFollowupDrugsController.java
  18. 12 8
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/servicePackage/ServicePackageSubItemEndpoint.java
  19. 3 1
      svr/svr-base/src/main/java/com/yihu/jw/base/service/followup/FollowupTemplateService.java
  20. 4 2
      svr/svr-base/src/main/java/com/yihu/jw/base/service/servicePackage/ServicePackageSubItemService.java
  21. 2 0
      svr/svr-internet-hospital-entrance/src/main/resources/application.yml
  22. 3 1
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/base/BaseInfoEndpoint.java
  23. 3 57
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java
  24. 12 2
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/integrate/BaseHospitalUserActivityController.java
  25. 3 1
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/patient/PatientNoLoginEndPoint.java
  26. 123 11
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/statistics/EsStatisticsEndpoint.java
  27. 55 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/booking/controller/BaseBookingServiceEndpoint.java
  28. 20 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/booking/dao/BaseBookingServiceDao.java
  29. 37 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/booking/service/BaseBookingServiceService.java
  30. 843 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/common/BaseController.java
  31. 12 12
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/common/CommonItemController.java
  32. 1 1028
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/controller/ConsultController.java
  33. 3 1118
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/controller/DoctorConsultController.java
  34. 15 3040
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultTeamService.java
  35. 14 12
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoorOrderController.java
  36. 8 6
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/ServiceItemPlanDao.java
  37. 13 67
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/DoorOrderService.java
  38. 24 132
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorServiceOrderService.java
  39. 725 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/controller/DoctorFollowUpController.java
  40. 78 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/controller/DoctorFollowupDrugsController.java
  41. 93 142
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/service/FollowUpService.java
  42. 98 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/service/FollowupDrugsService.java
  43. 2 1154
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/jw/service/JwSmjkService.java
  44. 27 6
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/DoctorRehabilitaionInfoController.java
  45. 42 44
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/PatientRehabilitationManageController.java
  46. 88 25
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/RehabilitationManageController.java
  47. 15 21
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/RehabilitationPlanController.java
  48. 2 2
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationDetailDao.java
  49. 51 32
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationInfoService.java
  50. 305 184
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationManageService.java
  51. 20 11
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationPlanService.java

+ 3 - 2
business/base-service/src/main/java/com/yihu/jw/article/service/BaseMenuManageService.java

@ -19,14 +19,12 @@ import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -1077,6 +1075,9 @@ public class BaseMenuManageService {
     * @return
     */
    public KnowledgeArticleDoctorDO insert(KnowledgeArticleDoctorDO articleDoctorDO){
        if(StringUtils.isBlank(articleDoctorDO.getBaseArticleDoctorId())){
            articleDoctorDO.setBaseArticleDoctorId(null);
        }
        articleDoctorDO.setCreateTime(new Date());
        articleDoctorDO.setUpdateTime(new Date());
        return knowledgeArticleDoctorDao.save(articleDoctorDO);

+ 16 - 4
business/base-service/src/main/java/com/yihu/jw/dict/service/HospitalDeptService.java

@ -7,6 +7,8 @@ import com.yihu.jw.entity.base.dict.DictHospitalDeptDO;
import com.yihu.jw.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
@ -16,13 +18,23 @@ import java.util.List;
public class HospitalDeptService extends BaseJpaService<BaseCityDO, BaseCityDao> {
    @Autowired
    private DictHospitalDeptDao dictHospitalDeptDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    // 基于机构编码,获取该机构下所有的科室列表
    public List<DictHospitalDeptDO> getHosDeptByCode(String orgCode,String consultDeptFlag) {
    public List<DictHospitalDeptDO> getHosDeptByCode(String orgCode,String consultDeptFlag,String name) {
        String sql = "select * from dict_hospital_dept where 1=1";
        if(StringUtils.isNotBlank(orgCode)){
            sql+=" and org_code = '"+orgCode+"' ";
        }
        if(StringUtils.isNotBlank(consultDeptFlag)){
            return dictHospitalDeptDao.findByOrgCodeAndConsultDeptFlag(orgCode,consultDeptFlag);
        }else{
            return dictHospitalDeptDao.findByOrgCode(orgCode);
            sql += " and consult_dept_flag = '"+consultDeptFlag+"' ";
        }
        if(StringUtils.isNotBlank(name)){
            sql += " and name like '%"+name+"%' ";
        }
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(DictHospitalDeptDO.class));
    }
}

+ 15 - 11
business/base-service/src/main/java/com/yihu/jw/hospital/integrate/service/BaseHospitalUserActivityService.java

@ -87,18 +87,22 @@ public class BaseHospitalUserActivityService extends BaseJpaService<BaseHospital
            String type = map.get("type").toString();
            if (type.equalsIgnoreCase("1")){
                BaseDoctorDO doctorDO = doctorDao.findByIdAndDel(user);
                map.put("name",doctorDO.getName());
                map.put("sex",doctorDO.getSex());
                map.put("age", DateUtil.getAgeForIdcard(doctorDO.getIdcard()));
                map.put("mobile",doctorDO.getMobile());
                map.put("idcard",doctorDO.getIdcard());
                if(doctorDO!=null){
                    map.put("name",doctorDO.getName());
                    map.put("sex",doctorDO.getSex());
                    map.put("age", DateUtil.getAgeForIdcard(doctorDO.getIdcard()));
                    map.put("mobile",doctorDO.getMobile());
                    map.put("idcard",doctorDO.getIdcard());
                }
            }else if (type.equalsIgnoreCase("2")){
                BasePatientDO patientDO = patientDao.findById(user).get();
                map.put("name",patientDO.getName());
                map.put("sex",patientDO.getSex());
                map.put("age", DateUtil.getAgeForIdcard(patientDO.getIdcard()));
                map.put("mobile",patientDO.getMobile());
                map.put("idcard",patientDO.getIdcard());
                BasePatientDO patientDO = patientDao.findById(user).orElse(null);
                if(patientDO!=null){
                    map.put("name",patientDO.getName());
                    map.put("sex",patientDO.getSex());
                    map.put("age", DateUtil.getAgeForIdcard(patientDO.getIdcard()));
                    map.put("mobile",patientDO.getMobile());
                    map.put("idcard",patientDO.getIdcard());
                }
            }
            String integrateSql ="SELECT IFNULL(SUM(integrate),0) as total FROM base_hospital_user_integrate where user='"+user+"' and relation_code='"+map.get("relationCode")+"' ";
            List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(integrateSql);

+ 6 - 5
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/PrescriptionService.java

@ -7702,6 +7702,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        rs.put("mobile", basePatientDO.getMobile());
        rs.put("photo", basePatientDO.getPhoto());
        rs.put("address", basePatientDO.getAddress());
        rs.put("latLon",basePatientDO.getLatLon());
        rs.put("cardType",basePatientDO.getCardType());
        rs.put("healthStatus","");
        rs.put("diseaseType","");
@ -14844,7 +14845,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    public List<Map<String, Object>> selectPriceTotal(String startTime,String endTime){
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> params = new HashedMap();
        String sql =" SELECT ORDER_CATEGORY as \"orderCategory\",\"SUM\"(PAY_PRICE)/100 as \"payPrice\" FROM BASE_BUSINESS_ORDER_PAY WHERE ORDER_CATEGORY IN(1,2,3,4)  and STATUS=1 ";
        String sql =" SELECT ORDER_CATEGORY as \"orderCategory\",SUM(PAY_PRICE)/100 as \"payPrice\" FROM BASE_BUSINESS_ORDER_PAY WHERE ORDER_CATEGORY IN(1,2,3,4)  and STATUS=1 ";
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
            sql+=" and create_time <= to_date('" + endTime + "', 'yyyy-mm-dd hh24:mi:ss') ";
        } else {
@ -14894,10 +14895,10 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            String j2="";
            String j3 ="";
            String j4="";
            String price1 = "";
            String price2 = "";
            String price3 = "";
            String price4 = "";
            String price1 = "0";
            String price2 = "0";
            String price3 = "0";
            String price4 = "0";
            for (Map<String, Object> m : ls) {
                if (m.get("orderCategory").toString().equalsIgnoreCase("1")){
                    j1 = m.get("orderCategory").toString();

+ 322 - 14
business/es-service/src/main/java/com/yihu/jw/es/service/StatisticsEsService.java

@ -46,7 +46,9 @@ import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.*;
import java.util.stream.Collectors;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * Created by wangzhinan on 2019/12/3.
@ -6172,9 +6174,9 @@ public class StatisticsEsService {
        //开方 【处方量】
        int kf_total = countListTotal(cf_model01);
        int kf_period = countListTotal(cf_model02);
        ;//上个周期
        //上个周期
        int kf_periodYear = countListTotal(cf_model03);
        ;//去年同周期
        //去年同周期
        result.put("kf_total", kf_total);//开方量
        result.put("kf_kfl", getRange(kf_total, patientVolume, 0));//【处方率】= 处方量 ÷ 接诊量 ×100%
        result.put("kf_hb", getRange((kf_total - kf_period), kf_period, 0));//环比
@ -6980,10 +6982,10 @@ public class StatisticsEsService {
        JSONObject result = new JSONObject();
        String sql = " SELECT dict_code \"functionCode\",dict_value \"functionName\",img_url \"img\" FROM wlyy_hospital_sys_dict WHERE dict_name='FUNCTION_SETTING' ORDER BY sort  ";
        List<Map<String, Object>> functionList = jdbcTemplate.queryForList(sql);
         List<String[]> list = new ArrayList<>();
        List<String[]> list = new ArrayList<>();
        for (Map<String, Object> map : functionList) {
              String[] strings = {String.valueOf(map.get("functionCode")), String.valueOf(map.get("functionName")), String.valueOf(map.get("img"))};
              list.add(strings);
            String[] strings = {String.valueOf(map.get("functionCode")), String.valueOf(map.get("functionName")), String.valueOf(map.get("img"))};
            list.add(strings);
        }
        result.put("list", list);
        return result;
@ -6994,12 +6996,12 @@ public class StatisticsEsService {
        String functionSql = " SELECT dict_code \"functionCode\",dict_value \"functionName\",py_code \"img\" FROM wlyy_hospital_sys_dict WHERE dict_name='FUNCTION_SETTING' ORDER BY sort  ";
        List<Map<String, Object>> functionList = jdbcTemplate.queryForList(functionSql);
        //医生信息
        String sql = " SELECT function_setting \"functionCode\" FROM base.base_doctor WHERE id='"+doctorCode+"'";
        String sql = " SELECT function_setting \"functionCode\" FROM base.base_doctor WHERE id='" + doctorCode + "'";
        List<Map<String, Object>> doctorList = jdbcTemplate.queryForList(sql);
        if (doctorList.isEmpty()){
        if (doctorList.isEmpty()) {
            return null;
        }else {
            String functionCodeList =(String) doctorList.get(0).get("functionCode");
        } else {
            String functionCodeList = (String) doctorList.get(0).get("functionCode");
//            List<String> list = Arrays.asList(functionCodeList.split(","));
//            List<Map<String, Object>> collect = functionList.stream()
//                    .filter(map -> map.keySet().containsAll(list))
@ -7007,21 +7009,21 @@ public class StatisticsEsService {
            List<String[]> list = new ArrayList<>();
            for (String code : functionCodeList.split(",")) {
                for (Map<String, Object> map : functionList) {
                    if (code.equals(map.get("functionCode"))){
                    if (code.equals(map.get("functionCode"))) {
                        String[] strings = {String.valueOf(map.get("functionCode")), String.valueOf(map.get("functionName")), String.valueOf(map.get("img"))};
                        list.add(strings);
                    }
                }
            }
            JSONObject result = new JSONObject();
            result.put("list",list);
            result.put("list", list);
            return result;
        }
    }
    public int updateDoctorSetting(String doctorCode,String functionCodeList) {
        String sql=" UPDATE base.base_doctor SET function_setting='"+functionCodeList+"'  WHERE id='"+doctorCode+"'" ;
    public int updateDoctorSetting(String doctorCode, String functionCodeList) {
        String sql = " UPDATE base.base_doctor SET function_setting='" + functionCodeList + "'  WHERE id='" + doctorCode + "'";
        int update = jdbcTemplate.update(sql);
        return update;
@ -7043,4 +7045,310 @@ public class StatisticsEsService {
    }
    public static ExecutorService execute = Executors.newFixedThreadPool(20);
    /**
     * 总人数:200人
     * <p>
     * 总次数:500次
     * 今日新增 +10
     * 本月新增 +10
     */
    public HashMap<String, Object> getConsultationCount(ScreenQvo qvo) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        //获取第一天、最后一天
        String[] dateList = getFirstAndEndDay(qvo.getEndDate());
        //今日新增量
        String todaySql = "SELECT count(*) as count from wlyy_consult_outpatient_info o where 1=1 AND o.create_time >='" + qvo.getEndDate() + "' and o.create_time <='" + qvo.getEndDate() + " 23:59:59' ";
        //查询本月量
        String monthSql = "SELECT count(*) as count from wlyy_consult_outpatient_info o where 1=1 AND o.create_time >='" + dateList[0] + "' and o.create_time <='" + dateList[1] + " 23:59:59' ";
        //查询人数
        String patientCountSql = "SELECT count(DISTINCT p.patient) 'count' FROM  wlyy_outpatient p  WHERE `p`.`pay_status` in (1,2) AND p.`create_time`>='" + qvo.getStartDate() + "' AND p.`create_time`<='" + qvo.getEndDate() + " 23:59:59' ";
        CompletableFuture<Void> future01 = CompletableFuture.runAsync(() -> {
            try {
                //全部问诊量
                SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(qvo.getEndDate(), qvo.getEndDate(), qvo.getArea(), qvo.getLevel(), qvo.getIndex(), SaveModel.timeLevel_DDL);
                if (saveModel != null) {
                    map.put("allConsultCount", saveModel.getResult2().longValue());
                } else {
                    map.put("allConsultCount", 0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, execute);
        CompletableFuture<Void> future02 = CompletableFuture.runAsync(() -> {
            //今日问诊量
            Integer count = jdbcTemplate.queryForObject(todaySql, Integer.class);
            map.put("todayConsultCount", count);
        }, execute);
        CompletableFuture<Void> future03 = CompletableFuture.runAsync(() -> {
            //本月
            Integer count = jdbcTemplate.queryForObject(monthSql, Integer.class);
            map.put("monthConsultCount", count);
        }, execute);
        CompletableFuture<Void> future04 = CompletableFuture.runAsync(() -> {
            //问诊人数
            Integer count = jdbcTemplate.queryForObject(patientCountSql, Integer.class);
            map.put("consultPaitentCount", count);
        }, execute);
        System.out.println("111");
        CompletableFuture<Void> allOf = CompletableFuture.allOf(future01, future02, future03, future04);
        allOf.get();
        System.out.println("222");
        return map;
    }
    /**
     * 获取男女就诊次数
     * 1男2女3其他
     */
    public HashMap<String, Object> getConsultGroupBySex(ScreenQvo qvo) {
        HashMap<String, Object> resultMap = new HashMap<>();
        String sql = "SELECT b.sex,count(a.id) 'count' \n" +
                " FROM  wlyy_outpatient a INNER JOIN base_patient b ON a.patient=b.id \n" +
                " WHERE 1=1 " +
                "  AND a.`pay_status` in (1,2) " +
                "  AND a.`create_time`>='" + qvo.getStartDate() + "' AND a.`create_time`<='" + qvo.getEndDate() + "' \n" +
                " GROUP BY b.sex";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        int otherCount = 0;
        for (Map<String, Object> map : list) {
            if (!Objects.isNull(map.get("sex")) && "1".equals(map.get("sex").toString())) {
                resultMap.put("1", map.get("count"));
            } else if (!Objects.isNull(map.get("sex")) && "2".equals(map.get("sex").toString())) {
                resultMap.put("2", map.get("count"));
            } else {
                otherCount += Integer.parseInt(map.get("count").toString());
            }
        }
        resultMap.put("3", otherCount);
        return resultMap;
    }
    /**
     * 获取第一天和最后一天
     */
    public String[] getFirstAndEndDay(String dateStr) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(dateStr);
        // 获取 Calendar 实例并设置到指定的 Date
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 设置 Calendar 到月初
        cal.set(Calendar.DAY_OF_MONTH, 1);
        String startOfMonth = sdf.format(cal.getTime());
        System.out.println("本月第一天: " + startOfMonth);
        // 获取本月最大天数并设置到 Calendar
        int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        cal.set(Calendar.DAY_OF_MONTH, maxDay);
        String endOfMonth = sdf.format(cal.getTime());
        System.out.println("本月最后一天: " + endOfMonth);
        // 返回包含本月第一天和最后一天的字符串数组
        String[] dates = {startOfMonth, endOfMonth};
        return dates;
    }
    public HashMap<String, Object> getConsultGroupByAge(ScreenQvo qvo) {
        String sql = "SELECT\n" +
                "	q.*,\n" +
                "	(\n" +
                "	SELECT\n" +
                "		count(1)\n" +
                "	FROM\n" +
                "		base_patient a\n" +
                "		INNER JOIN wlyy_outpatient b ON a.id = b.patient\n" +
                "		WHERE 1=1 AND a.birthday IS NOT NULL\n" +
                "		AND TIMESTAMPDIFF(YEAR, a.birthday, b.create_time) >=q.start_age\n" +
                "		AND TIMESTAMPDIFF(YEAR, a.birthday, b.create_time) <=q.end_age\n" +
                "		AND b.`pay_status` in (1,2)\n" +
                "		AND b.`create_time`>='" + qvo.getStartDate() + "' AND b.create_time<='" + qvo.getEndDate() + " 23:59:59'\n" +
                "	)'count'\n" +
                "FROM\n" +
                "	age_table q ORDER BY q.sort ";
        HashMap<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        int allCount = 0;
        for (Map<String, Object> map : list) {
            allCount += Integer.parseInt(map.get("count").toString());
        }
        resultMap.put("ageList", list);
        resultMap.put("allCount", allCount);
        return resultMap;
    }
    /**
     * 接诊量 job=12,14,16
     * 处方量 job=2
     * 【接诊率】= 接诊量 ÷ 问诊量 ×100%
     * 服务评价
     */
    public HashMap<String, Object> getConsultDetailCount(ScreenQvo qvo) throws Exception {
        HashMap<String, Object> resultMap = new HashMap<>();
        // 服务评分
        String scoreSql = "SELECT ROUND(AVG(score),2) 'score' FROM base_evaluate_score ";
        CompletableFuture<Void> future01 = CompletableFuture.runAsync(() -> {
            //开方量
            try {
                SaveModel model = elasticsearchUtil.findOneDateQuotaLevel0(qvo.getEndDate(), qvo.getEndDate(), qvo.getArea(), qvo.getLevel(), "2", SaveModel.timeLevel_DDL);
                if (model != null) {
                    resultMap.put("kfl", model.getResult2().longValue());//赋值开发量
                } else {
                    resultMap.put("kfl", 0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, execute);
        CompletableFuture<List<SaveModel>> future02 = CompletableFuture.supplyAsync(() -> {
            //接诊量
            List<SaveModel> model = null;
            try {
                model = elasticsearchUtil.findListDateQuotaLevel2(qvo.getStartDate(), qvo.getEndDate(), qvo.getArea(), qvo.getLevel(), "12,14,16", SaveModel.timeLevel_ZL, null, "9,16,12,1,17", "1");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return model;
        }, execute);
        CompletableFuture<SaveModel> future03 = CompletableFuture.supplyAsync(() -> {
            SaveModel model = null;
            try {
                //接诊量
                model = elasticsearchUtil.findOneDateQuotaLevel0(qvo.getEndDate(), qvo.getEndDate(), qvo.getArea(), qvo.getLevel(), "5", SaveModel.timeLevel_DDL);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return model;
        }, execute);
        CompletableFuture<Void> future04 = CompletableFuture.runAsync(() -> {
            String score = jdbcTemplate.queryForObject(scoreSql, String.class);
            resultMap.put("score", score);//赋值评分
        }, execute);
        CompletableFuture.allOf(future01, future02, future03, future04).get();
        List<SaveModel> jzModelList = future02.get();
        SaveModel model = future03.get();
        int patientVolume = countListTotal(jzModelList);
        int allConsultCount = 0;
        if (model != null) {
            allConsultCount = model.getResult2().intValue();
        }
        resultMap.put("jzCount", patientVolume);//赋值接诊量
        resultMap.put("wzAllCount", allConsultCount);//赋值问诊量
        //接诊率= 接诊量 ÷ 问诊量 ×100%
        resultMap.put("jzl", getRange(patientVolume, allConsultCount, 0));//赋值接诊率
        return resultMap;
    }
    /**
     * 【总收入】= 诊查费(21) + 处方费(3)
     * 查询诊查费、药品费、平均门诊费用 、总收入
     * 今日新增、本月新增
     */
    public HashMap<String, Object> getFreeDetailCount(ScreenQvo qvo) throws Exception {
        HashMap<String, Object> resultMap = new HashMap<>();
        String[] dateList = getFirstAndEndDay(qvo.getEndDate());
        //今天的
        String sql = "SELECT SUM(q.total)'todayFree' FROM(\n" +
                "	SELECT\n" +
                "	 IF(SUM(p.drug_fee) IS NULL,0,SUM(p.drug_fee))	 AS total \n" +
                "	FROM\n" +
                "		wlyy_prescription p\n" +
                "		INNER JOIN wlyy_outpatient o ON p.outpatient_id = o.id \n" +
                "	WHERE\n" +
                "		1 = 1 \n" +
                "		AND p.STATUS >= 30\n" +
                "		AND p.create_time  >='" + qvo.getEndDate() + "'  AND p.create_time <='" + qvo.getEndDate() + " 23:59:59' \n" +
                "	UNION ALL\n" +
                "	SELECT\n" +
                "		COALESCE(ROUND(SUM(bop.pay_price),2), 0) AS total\n" +
                "	FROM\n" +
                "		wlyy_outpatient o\n" +
                "		LEFT JOIN base_business_order_pay bop ON o.id = bop.relation_code \n" +
                "	WHERE\n" +
                "		o.pay_status = 1 \n" +
                "		AND o.`status` IN ( 1, 2, 3 )\n" +
                "		AND bop.pay_price IS NOT NULL AND bop.pay_price>0\n" +
                "		AND o.create_time  >='" + qvo.getEndDate() + "'  AND o.create_time <='" + qvo.getEndDate() + " 23:59:59' \n" +
                ") q ";
        CompletableFuture<SaveModel> future01 = CompletableFuture.supplyAsync(() -> {
            SaveModel model = null;
            try {
                //处方费
                model = elasticsearchUtil.findOneDateQuotaLevel0(qvo.getEndDate(), qvo.getEndDate(), qvo.getArea(), qvo.getLevel(), "3", SaveModel.timeLevel_DDL);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return model;
        }, execute);
        CompletableFuture<SaveModel> future02 = CompletableFuture.supplyAsync(() -> {
            SaveModel model = null;
            try {
                //检查费
                model = elasticsearchUtil.findOneDateQuotaLevel0(qvo.getEndDate(), qvo.getEndDate(), qvo.getArea(), qvo.getLevel(), "21", SaveModel.timeLevel_DDL);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return model;
        }, execute);
        CompletableFuture<SaveModel> future03 = CompletableFuture.supplyAsync(() -> {
            SaveModel model = null;
            try {
                //本月新增[处方费+检查费]
                model = elasticsearchUtil.findOneDateQuotaLevel0(dateList[0], dateList[1], qvo.getArea(), qvo.getLevel(), "3,21", SaveModel.timeLevel_ZL);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return model;
        }, execute);
        CompletableFuture<String> future04 = CompletableFuture.supplyAsync(() -> {
            String todayFree = jdbcTemplate.queryForObject(sql, String.class);
            return todayFree;
        }, execute);
        CompletableFuture.allOf(future01, future02, future03, future04).get();
        SaveModel model01 = future01.get();
        SaveModel model02 = future02.get();
        SaveModel monthModel = future03.get();
        String todayFree = future04.get();
        long checkFree = 0;
        long prescriptionFee = 0;
        long allCount;
        if (model01 != null) {
            prescriptionFee = model01.getResult2().longValue();
        }
        if (model02 != null) {
            checkFree = model02.getResult2().longValue();
        }
        allCount = prescriptionFee + checkFree;
        resultMap.put("checkFree", checkFree);//处方费
        resultMap.put("prescriptionFee", prescriptionFee);//检查费
        resultMap.put("allCount", allCount);//总费用
        if (allCount == 0) {
            resultMap.put("avgFree", 0);
        } else {
            resultMap.put("avgFree", allCount / 2.0);//平均费用
        }
        if (monthModel != null) {
            resultMap.put("monthFree", monthModel.getResult2().longValue());//本月新增
        } else {
            resultMap.put("monthFree", 0);
        }
        resultMap.put("todayFree", todayFree);//今日新增
        return resultMap;
    }
}

+ 1 - 1
business/es-service/src/main/java/com/yihu/jw/es/util/ElasticsearchUtil.java

@ -848,7 +848,7 @@ public class ElasticsearchUtil {
            }
        }
        sql.append(groupBy);
        //logger.info("sql:"+sql);
        logger.info("sql:"+sql);
        return excuteEs7(sql.toString(), SaveModel.class, "", "");
    }

+ 33 - 22
business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java

@ -139,21 +139,6 @@ public class ImService {
    @Value("${FileTempPath.upload_temp_path}")
    private String upload_temp_path;
    @Value("${FileTempPath.image_path}")
    private String image_path;
    @Value("${FileTempPath.voice_path}")
    private String voice_path;
    @Value("${FileTempPath.chat_file_path}")
    private String chat_file_path;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    @Value("${demo.flag}")
    private boolean demoFlag;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
@ -362,6 +347,24 @@ public class ImService {
        return consultCode;
    }
    public String getUnfinishedConsult(String patient, String doctor,int type) {
        String totalSql = "SELECT a.consult as \"consultCode\" " +
                "FROM wlyy_consult_team a,wlyy_consult_team_doctor b " +
                "WHERE a.consult=b.consult " +
                "AND a.patient= '" + patient + "' " +
                "AND b.to_doctor='" + doctor + "' " +
                "AND a.del='1' " +
                "AND a.type=" +type+
                "AND a.status=0";
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql);
        String consultCode = null;
        if (rstotal != null && rstotal.size() > 0) {
            consultCode = rstotal.get(0).get("consultCode").toString();
        }
        logger.info("未结束判断语句" + totalSql + "======consultCode" + consultCode);
        return consultCode;
    }
    /**
     * 查询居民与某个医生未结束的专家咨询
     *
@ -992,12 +995,20 @@ public class ImService {
            }
        }
        if (!flag) {
            if (!StringUtils.isEmpty(getUnfinishedConsult(patient, doctor))) {//判断是否有未结束的咨询移到同步方法中
//			re.put("status", -3);
//			return re;
                throw new RuntimeException("居民还有未结束的专家咨询!");
            if(ct.getType()==28){
                if (!StringUtils.isEmpty(getUnfinishedConsult(patient, doctor,ct.getType()))) {
                    throw new RuntimeException("居民还有未结束的康复咨询!");
                }
            }else {
                if (!StringUtils.isEmpty(getUnfinishedConsult(patient, doctor))) {//判断是否有未结束的咨询移到同步方法中
                    throw new RuntimeException("居民还有未结束的专家咨询!");
                }
            }
        }
        String title = "专家咨询";
        if(ct.getType()==28){
            title = "康复咨询";
        }
        JSONObject users = new JSONObject();
@ -1025,7 +1036,7 @@ public class ImService {
        // 医生未读数量为1
        ct.setDoctorRead(1);
        // 添加咨询记录
        ConsultDo consult = addConsult(ct.getPatient(), "专家咨询", ct.getSymptoms(), ct.getImages(), ct.getType(), source);
        ConsultDo consult = addConsult(ct.getPatient(), title, ct.getSymptoms(), ct.getImages(), ct.getType(), source);
//		// 设置关联指导
//		consult.setGuidance(ct.getGuidance());
        // 设置咨询标识
@ -1036,7 +1047,7 @@ public class ImService {
        ct.setDoctorName(baseDoctorDO.getName());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", tempPatient.getName() + "申请专家咨询");
        jsonObject.put("title", tempPatient.getName() + "申请"+title);
        jsonObject.put("content", ct.getSymptoms());
        jsonObject.put("age", DateUtil.getAgeForIdcard(tempPatient.getIdcard()));
        jsonObject.put("sex", tempPatient.getSex());
@ -1044,7 +1055,7 @@ public class ImService {
        //推送给IM去创建议题,取得成员消息
        JSONObject messages = imUtil.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), jsonObject.toJSONString(), consult.getImages(), doctor);
        users.put(patient, 0);//+ " "+(tempPatient.getSex()==1?"(男 ":"(女 ") + IdCardUtil.getAgeForIdcard(tempPatient.getIdcard())+")"
        users.put(patient, 0);
        String session_type = imUtil.SESSION_TYPE_MUC;
        if (17 == ct.getType()) {
            session_type = imUtil.SESSION_TYPE_MUC_VIDEO;//专家咨询-视频

+ 1 - 1
business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java

@ -598,7 +598,7 @@ public class ImUtil {
     */
    public static JSONObject createSession(JSONObject participants, String sessionType, String sessionName, String sessionId) {
//		String imAddr = im_host + "api/v2/sessions";
        String imAddr = ImService.im_host + "/sessions";
        String imAddr = ImService.im_host + "api/v2/sessions";
        JSONObject params = new JSONObject();
        params.put("participants", participants.toString());
        params.put("session_name", sessionName);

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/base/im/ConsultTeamDo.java

@ -23,7 +23,7 @@ public class ConsultTeamDo extends UuidIdentityEntity {
	private Integer type;           //  1、15三师咨询,2、家庭医生咨询,
	// 6、患者名医咨询 7医生名医咨询 8续方咨询 9、16在线复诊咨询(居民直接咨询专家)
	// 10医生发起的求助 11思明区上门服务在线咨询
	// 13、互联网医院专家咨询, 20紧急救助咨询, 21上门辅导咨询, 22安防警报咨询
	// 13、互联网医院专家咨询 28、康复咨询, 20紧急救助咨询, 21上门辅导咨询, 22安防警报咨询
	// 23 新生儿在线咨询
	// 24 老人在线咨询
	// 25

+ 67 - 27
common/common-entity/src/main/java/com/yihu/jw/entity/base/servicePackage/ServiceItemPlanDO.java

@ -5,6 +5,7 @@ import com.yihu.jw.entity.UuidIdentityEntityWithCreateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
 * 服务项执行计划
@ -18,13 +19,18 @@ public class ServiceItemPlanDO extends UuidIdentityEntityWithCreateTime {
    private String status;//状态0未完成 1已完成
    private String planTime;//计划时间
    private String completeTime;//完成时间
    private String signId;//签约id
    private String servicePackId;//服务包id
    private String serviceItemId;//服务项id
    private String itemConfigId;//服务项配置id
    private String doctor;//医生id
    private String doctorName;//医生姓名
    private String planId;//康复计划id
    private String planDetailId;//康复计划明细id
    private String name;//服务项名称
    private String relationCode;//关联业务id
    private String relationType;//关联业务类型 doorService上门服务
    private String relationType;//关联业务类型 1电话/短信关怀 2康复咨询 3康复咨询 4上门服务 5康复指导 6康复随访 7康复复诊
    private String content;//服务完成笔记
    private String appendixs;//附件
    private String guidanceMessage;//指导留言
    private String followupStatus;//随访状态 0取消 1已完成 2未开始 3进行中 4待审核
    @Column(name = "patient")
    public String getPatient() {
@ -44,39 +50,37 @@ public class ServiceItemPlanDO extends UuidIdentityEntityWithCreateTime {
        this.status = status;
    }
    @Column(name = "sign_id")
    public String getSignId() {
        return signId;
    @Column(name = "doctor")
    public String getDoctor() {
        return doctor;
    }
    public void setSignId(String signId) {
        this.signId = signId;
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    @Column(name = "service_pack_id")
    public String getServicePackId() {
        return servicePackId;
    @Column(name = "doctor_name")
    public String getDoctorName() {
        return doctorName;
    }
    public void setServicePackId(String servicePackId) {
        this.servicePackId = servicePackId;
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    @Column(name = "service_item_id")
    public String getServiceItemId() {
        return serviceItemId;
    @Column(name = "plan_id")
    public String getPlanId() {
        return planId;
    }
    public void setServiceItemId(String serviceItemId) {
        this.serviceItemId = serviceItemId;
    public void setPlanId(String planId) {
        this.planId = planId;
    }
    @Column(name = "item_config_id")
    public String getItemConfigId() {
        return itemConfigId;
    @Column(name = "plan_detail_id")
    public String getPlanDetailId() {
        return planDetailId;
    }
    public void setItemConfigId(String itemConfigId) {
        this.itemConfigId = itemConfigId;
    public void setPlanDetailId(String planDetailId) {
        this.planDetailId = planDetailId;
    }
    @Column(name = "name")
    public String getName() {
@ -118,4 +122,40 @@ public class ServiceItemPlanDO extends UuidIdentityEntityWithCreateTime {
    public void setCompleteTime(String completeTime) {
        this.completeTime = completeTime;
    }
    @Transient
    public String getGuidanceMessage() {
        return guidanceMessage;
    }
    public void setGuidanceMessage(String guidanceMessage) {
        this.guidanceMessage = guidanceMessage;
    }
    @Column(name = "content")
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    @Column(name = "appendixs")
    public String getAppendixs() {
        return appendixs;
    }
    public void setAppendixs(String appendixs) {
        this.appendixs = appendixs;
    }
    @Transient
    public String getFollowupStatus() {
        return followupStatus;
    }
    public void setFollowupStatus(String followupStatus) {
        this.followupStatus = followupStatus;
    }
}

+ 17 - 13
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceOrderDO.java

@ -215,9 +215,10 @@ public class WlyyDoorServiceOrderDO extends UuidIdentityEntityWithOperator {
    }
    private String packageId;//服务包的id
    private String feeAfter;//服务后收费标识(1是0否)
    private String signId;//签约id
    private String planId;//服务包的id---改成计划id ==>planId
    private String planItemDetailId;//签约id ---改成详情id===>planItemDetailId
    private String feeAfter;//服务后收费标识(1是0否)--这个暂时没用
    /**
@ -1266,13 +1267,7 @@ public class WlyyDoorServiceOrderDO extends UuidIdentityEntityWithOperator {
        this.nursingStaffType = nursingStaffType;
    }
    public String getPackageId() {
        return packageId;
    }
    public void setPackageId(String packageId) {
        this.packageId = packageId;
    }
    public String getFeeAfter() {
        return feeAfter;
@ -1282,11 +1277,20 @@ public class WlyyDoorServiceOrderDO extends UuidIdentityEntityWithOperator {
        this.feeAfter = feeAfter;
    }
    public String getSignId() {
        return signId;
    public String getPlanId() {
        return planId;
    }
    public void setPlanId(String planId) {
        this.planId = planId;
    }
    public String getPlanItemDetailId() {
        return planItemDetailId;
    }
    public void setSignId(String signId) {
        this.signId = signId;
    public void setPlanItemDetailId(String planItemDetailId) {
        this.planItemDetailId = planItemDetailId;
    }
}

+ 4 - 4
common/common-entity/src/main/java/com/yihu/jw/entity/followup/Followup.java

@ -1,7 +1,7 @@
package com.yihu.jw.entity.followup;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IntegerIdentityEntity;
import com.yihu.jw.entity.LongIdentityEntity;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import javax.persistence.*;
@ -17,7 +17,7 @@ import java.util.Map;
@Entity
@Table(name = "wlyy_followup")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_followup")
public class Followup extends IntegerIdentityEntity {
public class Followup extends LongIdentityEntity {
	//随访编号【基卫】
	private String followupNo;
@ -86,8 +86,8 @@ public class Followup extends IntegerIdentityEntity {
	private List<Map<String,Object>> followupLabelPatient;
	//居民头像
	private String photo;
	private String followupTypeName;
	private String followupClassName;
	private String followupTypeName;//随访方式名称
	private String followupClassName;//随访类型名称
	//随访类型1、新增随访、2临时随访、3入户访视
	private Integer type;
	//随访角色【FAMILY_WORK_TYPE_DICT】【1. 专科医生 2. 全科医生 3. 健康管理师】

+ 10 - 2
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/GuidanceMessageLogDO.java

@ -1,10 +1,8 @@
package com.yihu.jw.entity.specialist.rehabilitation;
import com.yihu.jw.entity.UuidIdentityEntityWithOperatorAES;
import com.yihu.jw.entity.util.StringFStringEncryptConverter;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
@ -22,6 +20,7 @@ public class GuidanceMessageLogDO extends UuidIdentityEntityWithOperatorAES impl
    private String content;
    private String doctor;
    private String doctorName;
    private String imgs;//附件
    private Integer doctorType;
    private Integer adminTeamCode;
    private String adminTeamName;
@ -117,4 +116,13 @@ public class GuidanceMessageLogDO extends UuidIdentityEntityWithOperatorAES impl
    public void setContentType(Integer contentType) {
        this.contentType = contentType;
    }
    @Column(name = "imgs")
    public String getImgs() {
        return imgs;
    }
    public void setImgs(String imgs) {
        this.imgs = imgs;
    }
}

+ 74 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationDetailDO.java

@ -7,6 +7,7 @@ import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.io.Serializable;
import java.util.Date;
@ -50,6 +51,10 @@ public class RehabilitationDetailDO extends UuidIdentityEntity implements Serial
    private String frequencyCode;//频次
    @Column(name = "time_type")
    private Integer timeType;//时间类型
    @Column(name = "server_time_type")
    private String serverTimeType;//服务方法 1饭前、2饭后、3睡前
    @Column(name = "server_count")
    private String serverCount;//服务次数
    @Column(name = "remark")
    private String remark;//备注
    @Column(name = "relation_code")
@ -65,6 +70,13 @@ public class RehabilitationDetailDO extends UuidIdentityEntity implements Serial
    private String updateUser;
    private String updateUserName;
    //非数据库字段
    private String name;//服务项名称
    private Integer finishNum;//已完成数
    private Integer totalNum;//总数
    private String completeTime;//上次完成时间
    private String planTime;//计划时间
    @Column(name = "reservation_type")
    public Integer getReservationType() {
        return reservationType;
@ -219,6 +231,23 @@ public class RehabilitationDetailDO extends UuidIdentityEntity implements Serial
        this.timeType = timeType;
    }
    @Column(name = "server_count")
    public String getServerCount() {
        return serverCount;
    }
    public void setServerCount(String serverCount) {
        this.serverCount = serverCount;
    }
    @Column(name = "server_time_type")
    public String getServerTimeType() {
        return serverTimeType;
    }
    public void setServerTimeType(String serverTimeType) {
        this.serverTimeType = serverTimeType;
    }
    @Column(name = "remark")
    public String getRemark() {
        return remark;
@ -297,4 +326,49 @@ public class RehabilitationDetailDO extends UuidIdentityEntity implements Serial
    public void setFollowupDetailType(Integer followupDetailType) {
        this.followupDetailType = followupDetailType;
    }
    @Transient
    public Integer getFinishNum() {
        return finishNum;
    }
    public void setFinishNum(Integer finishNum) {
        this.finishNum = finishNum;
    }
    @Transient
    public Integer getTotalNum() {
        return totalNum;
    }
    public void setTotalNum(Integer totalNum) {
        this.totalNum = totalNum;
    }
    @Transient
    public String getCompleteTime() {
        return completeTime;
    }
    public void setCompleteTime(String completeTime) {
        this.completeTime = completeTime;
    }
    @Transient
    public String getPlanTime() {
        return planTime;
    }
    public void setPlanTime(String planTime) {
        this.planTime = planTime;
    }
    @Transient
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

+ 2 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/hospital/statistics/ScreenQvo.java

@ -11,6 +11,8 @@ public class ScreenQvo {
//   interval  1日 2周 3月
//   lowLevel  下一级区域等级
   private String startDate;//开始时间
   private String endDate;//结束时间

+ 3 - 3
gateway/ag-basic/src/main/java/com/yihu/jw/gateway/filter/BasicZuulFilter.java

@ -317,9 +317,9 @@ public class BasicZuulFilter extends ZuulFilter {
    private String extractToken(HttpServletRequest request) {
        String accessToken = request.getHeader(ACCESS_TOKEN_PARAMETER);
        if (null == accessToken) {
            accessToken = request.getParameter(ACCESS_TOKEN_PARAMETER);
        }
//        if (null == accessToken) {
//            accessToken = request.getParameter(ACCESS_TOKEN_PARAMETER);
//        }
        return accessToken;
    }

+ 1 - 2
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/followup/DoctorFollowupDrugsController.java

@ -8,7 +8,6 @@ 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.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@ -24,7 +23,7 @@ import java.util.Map;
 *
 */
@RestController
@RequestMapping(value = "/doctor/followup/drugs", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,method = {RequestMethod.GET,RequestMethod.POST})
@RequestMapping(value = "/doctor/followup/drugs")
@Api(description = "医生端-随访用药接口")
public class DoctorFollowupDrugsController extends BaseController {

+ 12 - 8
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/servicePackage/ServicePackageSubItemEndpoint.java

@ -46,14 +46,18 @@ public class ServicePackageSubItemEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = "getItemList")
    @ApiOperation(value = "查询所有服务项")
    public PageEnvelop<Map<String, Object>> getSubItemList(
            @ApiParam(name = "jsonStr", value = "Json数据", required = true) @RequestParam String jsonStr
    ) throws Exception {
        jsonStr = URLDecoder.decode(jsonStr, "UTF-8");
        ParamQvo qvo = JSON.parseObject(jsonStr, ParamQvo.class);
        Map<String, Object> map = subItemService.getSubItemList(qvo);
        List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("list");
        Integer count = (Integer) map.get("count");
        return success(list, count, qvo.getPage(), qvo.getPageSize());
            @ApiParam(name = "jsonStr", value = "Json数据", required = true) @RequestParam String jsonStr)  {
        try {
            jsonStr = URLDecoder.decode(jsonStr, "UTF-8");
            ParamQvo qvo = JSON.parseObject(jsonStr, ParamQvo.class);
            Map<String, Object> map = subItemService.getSubItemList(qvo);
            List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("list");
            Integer count = (Integer) map.get("count");
            return success(list, count, qvo.getPage(), qvo.getPageSize());
        }catch (Exception e){
            e.printStackTrace();
            return PageEnvelop.getError("查询失败");
        }
    }

+ 3 - 1
svr/svr-base/src/main/java/com/yihu/jw/base/service/followup/FollowupTemplateService.java

@ -24,7 +24,9 @@ public class FollowupTemplateService extends BaseJpaService<FollowupTemplate, Fo
    public HashMap<String, Object> findList(ParamQvo qvo) {
        String detailSql = "SELECT * ";
        String detailSql = "SELECT id,template_name,followup_statrt_time_type,followup_count,description,template_detail_json,`status` " +
                ",leased_code,leased_name,org_code,org_name,DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%s') create_time,create_user " +
                ",create_user_name,DATE_FORMAT(update_time,'%Y-%m-%d %H:%i:%s') update_time,update_user,update_user_name ";
        String countSql = "SELECT COUNT(1) ";
        String conditionSql = " FROM base_followup_template WHERE 1=1 ";
        String pageSql = "";

+ 4 - 2
svr/svr-base/src/main/java/com/yihu/jw/base/service/servicePackage/ServicePackageSubItemService.java

@ -26,8 +26,10 @@ public class ServicePackageSubItemService extends BaseJpaService<ServicePackageS
    public Map<String, Object> getSubItemList(ParamQvo qvo) {
        String detailSql = "select * ";
        String detailSql = "select id,dict_item_id,name,introduce,`status`,sort,leased_code,leased_name,org_code,org_name " +
                ",photo,DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%s') create_time,price ";
        String countSql = " select count(1) ";
        String orderBySql = " order by a.sort desc ";
        String pageSql = "";
        String sql = " FROM base_service_package_sub_item a   ";
        if (StringUtils.isNotBlank(qvo.getParentId())) {
@ -62,7 +64,7 @@ public class ServicePackageSubItemService extends BaseJpaService<ServicePackageS
        if (StringUtils.isNotBlank(qvo.getPageIf())) {
            pageSql += " limit " + (qvo.getPage() - 1) * qvo.getPageSize() + "," + qvo.getPageSize();
        }
        detailSql += sql + pageSql;
        detailSql += sql + orderBySql + pageSql;
        countSql += sql;
        Integer count = jdbcTemplate.queryForObject(countSql, Integer.class);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(detailSql);

+ 2 - 0
svr/svr-internet-hospital-entrance/src/main/resources/application.yml

@ -25,6 +25,8 @@ spring:
    multipart:
      max-file-size: 30MB
      max-request-size: 100MB
  main:
    allow-bean-definition-overriding: true
  redis:
    database: 0 # Database index used by the connection factory.
    password: # Login password of the redis server.

+ 3 - 1
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/base/BaseInfoEndpoint.java

@ -114,11 +114,13 @@ public class BaseInfoEndpoint extends EnvelopRestEndpoint {
    public Envelop getDeptByOrgCode(
            @ApiParam(name = "orgCode", value = "机构编码")
            @RequestParam(value = "orgCode", required = false) String orgCode,
            @ApiParam(name = "name", value = "科室名称")
            @RequestParam(value = "name", required = false) String name,
            @ApiParam(name = "consultDeptFlag", value = "是否是就诊科室,1为查询门诊,不传为全部")
            @RequestParam(value = "consultDeptFlag", required = false) String consultDeptFlag)  {
        try {
            List<DictHospitalDeptDO> res =  hospitalDeptService.getHosDeptByCode(orgCode,consultDeptFlag);
            List<DictHospitalDeptDO> res =  hospitalDeptService.getHosDeptByCode(orgCode,consultDeptFlag,name);
            if(res != null && res.size() > 0 ){
                return  success(res);
            }else{

文件差異過大導致無法顯示
+ 3 - 57
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java


+ 12 - 2
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/integrate/BaseHospitalUserActivityController.java

@ -35,7 +35,12 @@ public class BaseHospitalUserActivityController extends EnvelopRestEndpoint {
                                          @RequestParam(value = "size", required = true) Integer size,
                                      @ApiParam(name = "title", value = "活动标题", required = false)
                                          @RequestParam(value = "title", required = false) String title) {
        return success(userActivityService.selectUserActivityByCondition(title,page,size));
        try {
            return success(userActivityService.selectUserActivityByCondition(title,page,size));
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @GetMapping(value= BaseHospitalRequestMapping.BaseHospitalUserActivity.findUserActivityById)
@ -113,7 +118,12 @@ public class BaseHospitalUserActivityController extends EnvelopRestEndpoint {
                                @RequestParam(value = "businessCode", required = false) String businessCode,
                                @ApiParam(name = "activityId", value = "活动id", required = false)
                                @RequestParam(value = "activityId", required = false) String activityId) throws Exception {
        return success(userActivityService.selectUserIntegrateListByCondition(user,businessCode,activityId,page,size));
        try {
            return success(userActivityService.selectUserIntegrateListByCondition(user,businessCode,activityId,page,size));
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @GetMapping(value= BaseHospitalRequestMapping.BaseHospitalUserActivity.selectDeptRomByCondition)

+ 3 - 1
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/patient/PatientNoLoginEndPoint.java

@ -455,10 +455,12 @@ public class PatientNoLoginEndPoint extends EnvelopRestEndpoint {
    public Envelop getDeptByOrgCode(
            @ApiParam(name = "orgCode", value = "机构编码")
            @RequestParam(value = "orgCode", required = false) String orgCode,
            @ApiParam(name = "name", value = "科室名称")
            @RequestParam(value = "name", required = false) String name,
            @ApiParam(name = "consultDeptFlag", value = "是否是就诊科室,1为查询门诊,不传为全部")
            @RequestParam(value = "consultDeptFlag", required = false) String consultDeptFlag)  {
        try {
            List<DictHospitalDeptDO> res =  hospitalDeptService.getHosDeptByCode(orgCode,consultDeptFlag);
            List<DictHospitalDeptDO> res =  hospitalDeptService.getHosDeptByCode(orgCode,consultDeptFlag,name);
            if(res != null && res.size() > 0 ){
                return  success(res);
            }else{

+ 123 - 11
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/statistics/EsStatisticsEndpoint.java

@ -20,6 +20,7 @@ import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -1191,7 +1192,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
            result = statisticsEsService.getTotal3Data(qvo);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口(getTotal3Data):报错==>入参:" + JSON.toJSONString(qvo));
            System.out.println("接口[getTotal3Data]:报错==>入参:" + JSON.toJSONString(qvo));
        }
        return success(result);
    }
@ -1209,7 +1210,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
            result = statisticsEsService.getKindsConsultCount(qvo);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口(getKindsConsultCount):报错==>入参:" + JSON.toJSONString(qvo));
            System.out.println("接口[getKindsConsultCount]:报错==>入参:" + JSON.toJSONString(qvo));
        }
        return success(result);
    }
@ -1231,7 +1232,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
            result = statisticsEsService.getConsultAndPrescriptionList(qvo);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口(getConsultAndPrescriptionList):报错==>入参:" + JSON.toJSONString(qvo));
            System.out.println("接口[getConsultAndPrescriptionList]:报错==>入参:" + JSON.toJSONString(qvo));
        }
        return success(result);
    }
@ -1254,7 +1255,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
            result = statisticsEsService.getDrugAndExaminationFeeList(qvo);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口(getDrugAndExaminationFeeList):报错==>入参:" + JSON.toJSONString(qvo));
            System.out.println("接口[getDrugAndExaminationFeeList]:报错==>入参:" + JSON.toJSONString(qvo));
        }
        return success(result);
    }
@ -1274,7 +1275,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
            result = statisticsEsService.getDeptOrDoctorVolumeList(qvo);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口(getDeptOrDoctorVolumeList):报错==>入参:" + JSON.toJSONString(qvo));
            System.out.println("接口[getDeptOrDoctorVolumeList]:报错==>入参:" + JSON.toJSONString(qvo));
        }
        return success(result);
    }
@ -1296,7 +1297,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
            result = statisticsEsService.getAllHospitalDetails(qvo);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口(getAllHospitalDetails):报错==>入参:" + JSON.toJSONString(qvo));
            System.out.println("接口[getAllHospitalDetails]:报错==>入参:" + JSON.toJSONString(qvo));
        }
        return success(result);
    }
@ -1316,7 +1317,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
            statisticsEsService.getAllDeptAndDoctorDetails(qvo, os); //导出
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口(exportHospitalDetails):报错==>入参:" + JSON.toJSONString(qvo));
            System.out.println("接口[exportHospitalDetails]:报错==>入参:" + JSON.toJSONString(qvo));
        }
    }
@ -1333,7 +1334,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
            result = statisticsEsService.getDeptScheduling(qvo);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口(getDeptScheduling):报错==>入参:" + JSON.toJSONString(qvo));
            System.out.println("接口[getDeptScheduling]:报错==>入参:" + JSON.toJSONString(qvo));
        }
        return success(result);
    }
@ -1349,7 +1350,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
            result = statisticsEsService.getAllFunctionSetting();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口(getAllFunctionSetting):报错");
            System.out.println("接口[getAllFunctionSetting]:报错");
        }
        return success(result);
    }
@ -1367,7 +1368,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
            result = statisticsEsService.getDoctorSetting(doctorCode);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口(getDoctorSetting):报错==>入参:" + JSON.toJSONString(doctorCode));
            System.out.println("接口[getDoctorSetting]:报错==>入参:" + JSON.toJSONString(doctorCode));
        }
        return success(result);
    }
@ -1390,7 +1391,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口(updateDoctorSetting):报错==>入参:" + doctorCode + "----" + functionCodeList);
            System.out.println("接口[updateDoctorSetting]:报错==>入参:" + doctorCode + "----" + functionCodeList);
        }
        return null;
    }
@ -1414,4 +1415,115 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
            return error(-1, e.getMessage());
        }
    }
    // ==========================================
    /**
     *  timeLevel;// 1 日 2 周 3 月 4 年  1增量 2到达量
     *  areaLevel;// 1 省 2 市 3 区县 4 机构 5团队 6医生
     */
    // ==========================================
    //------------------------------大屏接口-----------------------------------------
    /**
     * 查询网络门诊概况
     * 总人数:200人
     * 总次数:500次
     * 今日新增 +10
     * 本月新增 +10
     * - strJson={"startDate":"2020-07-18","endDate":"2023-11-29","area":"350200","level":2,"index":5}
     */
    @GetMapping(value = "/getConsultationCount")
    @ApiOperation(value = "查询网络门诊概况")
    public Envelop getConsultationCount(@RequestParam(required = true) String strJson) {
        ScreenQvo qvo = JSON.parseObject(strJson, ScreenQvo.class);
        try {
            HashMap<String, Object> result = statisticsEsService.getConsultationCount(qvo);
            return success(result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口[getConsultationCount]:报错==>入参:" + JSON.toJSONString(qvo));
            return failed("系统繁忙");
        }
    }
    /**
     * 获取男女就诊次数
     * strJson={"startDate":"2020-07-18","endDate":"2023-11-29"}
     */
    @GetMapping(value = "/getConsultGroupBySex")
    @ApiOperation(value = " 获取男女就诊次数")
    public Envelop getConsultGroupBySex(@RequestParam(required = true) String strJson) {
        ScreenQvo qvo = JSON.parseObject(strJson, ScreenQvo.class);
        try {
            HashMap<String, Object> result = statisticsEsService.getConsultGroupBySex(qvo);
            return success(result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口[getConsultGroupBySex]:报错==>入参:" + JSON.toJSONString(qvo));
            return failed("系统繁忙");
        }
    }
    /**
     * 患者年龄分布
     * strJson={"startDate":"2020-07-18","endDate":"2023-11-29"}
     */
    @GetMapping(value = "/getConsultGroupByAge")
    @ApiOperation(value = " 患者年龄分布")
    public Envelop getConsultGroupByAge(@RequestParam(required = true) String strJson) {
        ScreenQvo qvo = JSON.parseObject(strJson, ScreenQvo.class);
        try {
            HashMap<String, Object> result = statisticsEsService.getConsultGroupByAge(qvo);
            return success(result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口[getConsultGroupByAge]:报错==>入参:" + JSON.toJSONString(qvo));
            return failed("系统繁忙");
        }
    }
    /**
     * 查询接诊量、处方量、接诊率、服务评价
     * strJson={"startDate":"2020-07-18","endDate":"2023-11-29","area":"350200","level":2}
     */
    @GetMapping(value = "/getConsultDetailCount")
    @ApiOperation(value = "查询接诊量、处方量、接诊率、服务评价")
    public Envelop getConsultDetailCount(@RequestParam(required = true) String strJson) {
        ScreenQvo qvo = JSON.parseObject(strJson, ScreenQvo.class);
        try {
            HashMap<String, Object> result = statisticsEsService.getConsultDetailCount(qvo);
            return success(result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口[getConsultDetailCount]:报错==>入参:" + JSON.toJSONString(qvo));
            return failed("系统繁忙");
        }
    }
    /**
     * 查询诊查费、药品费、平均门诊费用 、【总收入= 诊查费 + 处方费】
     * 今日新增、本月新增
     * strJson={"startDate":"2020-07-18","endDate":"2023-11-29","area":"350200","level":2}
     */
    @GetMapping(value = "/getFreeDetailCount")
    @ApiOperation(value = "查询接诊量、处方量、接诊率、服务评价")
    public Envelop getFreeDetailCount(@RequestParam(required = true) String strJson) {
        ScreenQvo qvo = JSON.parseObject(strJson, ScreenQvo.class);
        try {
            HashMap<String, Object> result = statisticsEsService.getFreeDetailCount(qvo);
            return success(result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口[getFreeDetailCount]:报错==>入参:" + JSON.toJSONString(qvo));
            return failed("系统繁忙");
        }
    }
}

+ 55 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/booking/controller/BaseBookingServiceEndpoint.java

@ -0,0 +1,55 @@
package com.yihu.jw.hospital.module.booking.controller;
import com.yihu.jw.hospital.module.booking.service.BaseBookingServiceService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/***
 * @ClassName: BaseBookingServiceEndpoint
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/8/12 10:31
 */
@RestController
@RequestMapping("bookingService" )
@Api(tags = "预订服务弹框", description = "预订服务弹框")
public class BaseBookingServiceEndpoint extends EnvelopRestEndpoint {
    @Autowired
    private BaseBookingServiceService serviceService;
    @ApiOperation("是否需要弹框")
    @GetMapping(value= "findByPatient")
    public Envelop findByPatient(@ApiParam(name = "patient", value = "patient", required = true)
                                     @RequestParam(value = "patient", required = true)String patient){
        try {
            return success("获取成功!",serviceService.findByPatient(patient));
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("获取失败!");
        }
    }
    @ApiOperation("保存,不在弹框")
    @GetMapping(value= "saveByPatient")
    public Envelop saveByPatient(@ApiParam(name = "patient", value = "patient", required = true)
                                     @RequestParam(value = "patient", required = true)String patient){
        try {
            serviceService.saveByPatient(patient);
            return success("保存成功!");
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("保存失败!");
        }
    }
}

+ 20 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/booking/dao/BaseBookingServiceDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.hospital.module.booking.dao;
import com.yihu.jw.entity.care.booking.BaseBookingServiceDo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
/***
 * @ClassName: BaseBookingServiceDao
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/8/12 10:23
 */
public interface BaseBookingServiceDao extends JpaRepository<BaseBookingServiceDo,String>,
        JpaSpecificationExecutor<BaseBookingServiceDo> {
    @Query("select a from BaseBookingServiceDo a where a.patient = ?1 and a.status = 1")
    BaseBookingServiceDo findByPatient(String patient);
}

+ 37 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/booking/service/BaseBookingServiceService.java

@ -0,0 +1,37 @@
package com.yihu.jw.hospital.module.booking.service;
import com.yihu.jw.entity.care.booking.BaseBookingServiceDo;
import com.yihu.jw.hospital.module.booking.dao.BaseBookingServiceDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/***
 * @ClassName: BaseBookingServiceService
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/8/12 10:24
 */
@Service
public class BaseBookingServiceService {
    @Autowired
    private BaseBookingServiceDao serviceDao;
    public void saveByPatient(String patient) throws Exception {
            BaseBookingServiceDo serviceDo = new BaseBookingServiceDo();
            serviceDo.setPatient(patient);
            serviceDo.setStatus(1);
            serviceDao.save(serviceDo);
    }
    public int findByPatient(String patient){
        BaseBookingServiceDo serviceDo = serviceDao.findByPatient(patient);
        if (serviceDo != null){
            return serviceDo.getStatus();
        }else {
            return 0;
        }
    }
}

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

@ -0,0 +1,843 @@
package com.yihu.jw.hospital.module.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.IdEntity;
import com.yihu.jw.entity.base.dict.BaseExceptionDictDO;
import com.yihu.jw.restmodel.exception.dao.BaseExceptionDictDao;
import com.yihu.jw.util.date.DateUtil;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ReflectionUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "返回的json里的status是200,成功"),
        @ApiResponse(code = 403, message = "返回的json里的status是403,该操作没有权限"),
        @ApiResponse(code = 997, message = "返回的json里的status是997,重新登陆"),
        @ApiResponse(code = 998, message = "返回的json里的status是998,登录超时,请重新登录"),
        @ApiResponse(code = 999, message = "返回的json里的status是999,帐号在别处登录,请重新登录")
})
public class BaseController {
    private static Logger logger = LoggerFactory.getLogger("error_logger");
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    private BaseExceptionDictDao baseExceptionDictDao;
    @Autowired
    protected ObjectMapper objectMapper;
    /**
     * 獲取髮送請求用戶的uid
     * @return
     */
    public String getUID() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("uid");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取被代理人的code
     * @return
     */
    public String getRepresentedUID() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("represented");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取平台端
     * @return
     */
    public Integer getPlatform() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getInt("platform");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取被代理人code,若没有则返回当前登录者
     * @return
     */
    public String getRepUID(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            if(json.isNull("represented")){
                return json.getString("uid");
            }
            return json.getString("represented");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 獲取髮送請求用戶的uid
     *
     * @return
     */
    public String getLastUid() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            String id = json.getString("lastUid");
            if(StringUtils.isNoneBlank(id)){
                return id;
            }else{
               return json.getString("uid");
            }
        } catch (Exception e) {
            return null;
        }
    }
    public String getAppVersion() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("appVersion");
        } catch (Exception e) {
            return null;
        }
    }
    public String getOpenid() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("openid");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取用户ID
     *
     * @return
     */
    public long getId() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getLong("id");
        } catch (Exception e) {
            return 0;
        }
    }
    public String getIMEI() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("imei");
        } catch (Exception e) {
            return null;
        }
    }
    public String getToken() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("token");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取当前用户的角色级别
     * @return
     */
    public String getCurrentRoleLevel(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getJSONObject("currentUserRole").get("level")+"";
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取当前用户的角色是否是管理员
     * @return
     */
    public String getCurrentRoleIsManange(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getJSONObject("currentUserRole").getString("isManage");
        } catch (Exception e) {
            return null;
        }
    }
    public void error(Exception e) {
        logger.error(DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss")+":"+getClass().getName() + ":", e.getMessage());
        e.printStackTrace();
    }
    public void error(Exception e,String method,String key,String param) {
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            String exception = sw.toString();
            if(StringUtils.isNotBlank(exception)){
                exception = exception.length()>30000? exception.substring(0,30000):exception;
            }
        }catch (Exception e1){
            e1.printStackTrace();
        }
    }
    public void warn(Exception e) {
        logger.warn(getClass().getName() + ":", e.getMessage());
        e.printStackTrace();
    }
    public void infoMessage(String message) {
        logger.info(message);
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String error(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    public String errorResult(Exception e) {
        try {
            e.printStackTrace();
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            BaseExceptionDictDO baseExceptionDictDO =baseExceptionDictDao.findByExceptionInfo(e.getClass().toString());
            if (baseExceptionDictDO!=null){
                map.put("status", Integer.parseInt(baseExceptionDictDO.getCode()));
                map.put("msg", baseExceptionDictDO.getRemindContent());
            }else {
                map.put("status", -10000);
                map.put("msg", "系统繁忙,请稍后再试");
            }
            return mapper.writeValueAsString(map);
        } catch (Exception e1) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 接口处理成功
     *
     * @param msg
     * @return
     */
    public String success(String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", 200);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    public String write(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, list);
            String s = mapper.writeValueAsString(map);
            return s;
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, List<?> list,String key2,Object value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, list);
            map.put(key2, value);
            String s = mapper.writeValueAsString(map);
            return s;
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONObject value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONArray value,String key2, JSONObject value2) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            json.put(key2, value2);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONArray value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param total 总数
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, int total, String key, JSONArray value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put("total", total);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, int total, String key, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            map.put("status", code);
            map.put("msg", msg);
            map.put("total", total);
            map.put(key, list);
            String s = mapper.writeValueAsString(map);
            return s;
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Object value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, Page<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            // 是否为第一页
            map.put("isFirst", list.isFirst());
            // 是否为最后一页
            map.put("isLast", list.isLast());
            // 总条数
            map.put("total", list.getTotalElements());
            // 总页数
            map.put("totalPages", list.getTotalPages());
            map.put(key, list.getContent());
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, Page<?> page, JSONArray array) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            // 是否为第一页
            json.put("isFirst", page == null ? false : page.isFirst());
            // 是否为最后一页
            json.put("isLast", page == null ? true : page.isLast());
            // 总条数
            json.put("total", page == null ? 0 : page.getTotalElements());
            // 总页数
            json.put("totalPages", page == null ? 0 : page.getTotalPages());
            json.put(key, array);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Map<?, ?> value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, String value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, IdEntity entity) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, entity);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, boolean isFirst, boolean isLast, long total, int totalPages, String key, Object values) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            // 是否为第一页
            json.put("isFirst", isFirst);
            // 是否为最后一页
            json.put("isLast", isLast);
            // 总条数
            json.put("total", total);
            // 总页数
            json.put("totalPages", totalPages);
            json.put(key, values);
            return json.toString();
        } catch (Exception e) {
            logger.error("BaseController:", e.getMessage());
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    public String trimEnd(String param, String trimChars) {
        if (param.endsWith(trimChars)) {
            param = param.substring(0, param.length() - trimChars.length());
        }
        return param;
    }
    public List<Map<String, Object>> copyBeans(Collection<? extends Object> beans, String... propertyNames) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Object bean : beans) {
            result.add(copyBeanProperties(bean, propertyNames));
        }
        return result;
    }
    /**
     * 复制特定属性。
     *
     * @param bean
     * @param propertyNames
     * @return
     */
    public Map<String, Object> copyBeanProperties(Object bean, String... propertyNames) {
        Map<String, Object> simplifiedBean = new HashMap<>();
        for (String propertyName : propertyNames) {
            Field field = ReflectionUtils.findField(bean.getClass(), propertyName);
            if (field != null) {
                field.setAccessible(true);
                Object value = ReflectionUtils.getField(field, bean);
                simplifiedBean.put(propertyName, value == null ? "" : value);
            } else {
                simplifiedBean.put(propertyName, "");
            }
        }
        return simplifiedBean;
    }
    /**
     * 数据保留两位小数,**.0 去掉小数点
     * @param obj
     * @return
     */
    public String getNumberFormat(Object obj){
        if(obj != null){
            Double d = Double.valueOf(obj.toString());
            NumberFormat df = NumberFormat.getInstance();
            df.setGroupingUsed(false);
            df.setMaximumFractionDigits(2);
            return df.format(d);
        }else {
            return "";
        }
    }
    public String write(int code, String errorMsg, int page, int rows, long total, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("successFlg", code == 0);
            map.put("errorMsg", errorMsg);
            // 是否为第一页
            map.put("errorCode", code);
            // 是否为最后一页
            map.put("currPage", page);
            // 分页大小
            map.put("pageSize", rows);
            // 总条数
            map.put("totalCount", total);
            // 总页数
            map.put("totalPage", Math.ceil((double)total/(rows)));
            // 结果集
            map.put("detailModelList", list);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    
    /**
     * 判断是否是观察者模式
     * @return
     */
    public boolean getObserverStatus () {
    
        String userAgent = request.getHeader("userAgent");
        if (StringUtils.isEmpty(userAgent)) {
            userAgent = request.getHeader("User-Agent");
        }
        logger.debug("userAgent:" + userAgent);
        JSONObject json = new JSONObject(userAgent);
        String observer = json.has("observer") ? json.getString("observer") : "";
        //如果是观察者直接返回true
        if (!org.springframework.util.StringUtils.isEmpty(observer) && observer.equals("1")) {
            return true;
        }else{
            return false;
        }
    }
    //获取ip地址
    public String getIpAddr() {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
    //获取手机型号
    public String getPhoneType(){
        String userAgent = request.getHeader("User-Agent");
        Pattern pattern = Pattern.compile(";\\s?(\\S*?\\s?\\S*?)\\s?(Build)?/");
        Matcher matcher = pattern.matcher(userAgent);
        String model = null;
        if (matcher.find()) {
            model = matcher.group(1).trim();
        }else{
            model = "未知型号";
        }
        return model;
    }
    /**
     * 无效用户消息返回
     *
     * @param e
     * @param defaultCode
     * @param defaultMsg
     * @return
     */
    public String invalidUserException(Exception e, int defaultCode, String defaultMsg) {
        try {
            // if (e instanceof UndeclaredThrowableException) {
            // UndeclaredThrowableException ute = (UndeclaredThrowableException) e;
            // InvalidUserException iue = (InvalidUserException) ute.getUndeclaredThrowable();
            // if (iue != null) {
            // return error(iue.getCode(), iue.getMsg());
            // }
            // }
            return errorResult(e);
        } catch (Exception e2) {
            return null;
        }
    }
}

+ 12 - 12
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/common/CommonItemController.java

@ -24,23 +24,23 @@ public class CommonItemController extends EnvelopRestEndpoint {
    @Autowired
    private DoorOrderService doorOrderService;
    /**
     * 这个接口没用了
     * 去调用服务子项查询接口
     */
    @ApiOperation("查询字典-通用字典接口")
    @GetMapping(value= "getServiceItem")
    public Envelop getServiceItem(@ApiParam(name = "name", value = "name", required = false)
                               @RequestParam(value = "name", required = false)String name,
                                  @ApiParam(name = "signId", value = "signId", required = true)
                               @RequestParam(value = "signId", required = true)String signId,
                                  @ApiParam(name = "type", value = "type", required = true)
                               @RequestParam(value = "type", required = true)String type,
                                  @ApiParam(name = "page", value = "page", required = true)
                               @RequestParam(value = "page", required = true) Integer page,
                                  @ApiParam(name = "size", value = "pageSize", required = true)
                               @RequestParam(value = "size", required = true)Integer size){
    public Envelop getServiceItem(
            @ApiParam(name = "name", value = "name", required = false) @RequestParam(value = "name", required = false)String name,
            @ApiParam(name = "type", value = "type", required = true) @RequestParam(value = "type", required = true)String type,
            @ApiParam(name = "page", value = "page", required = true) @RequestParam(value = "page", required = true) Integer page,
            @ApiParam(name = "size", value = "pageSize", required = true) @RequestParam(value = "size", required = true)Integer size
    ){
        try {
            return doorOrderService.getServiceItem(signId,name,type,page,size);
            return doorOrderService.getServiceItem(name,type,page,size);
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询是吧",-1);
            return Envelop.getError("查询失败",-1);
        }
    }
}

+ 1 - 1028
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/controller/ConsultController.java

@ -4,17 +4,11 @@ package com.yihu.jw.hospital.module.consult.controller;
import com.alibaba.fastjson.JSON;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.im.ConsultTeamLogDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.message.MessageNoticeSetting;
import com.yihu.jw.entity.util.SystemConfEntity;
import com.yihu.jw.hospital.module.consult.service.ConsultTeamService;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.HttpUtil;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.dao.ConsultTeamDao;
@ -24,19 +18,15 @@ import com.yihu.jw.message.service.MessageService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.common.CommonUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
@ -139,315 +129,6 @@ public class ConsultController extends EnvelopRestEndpoint {
//    private WlyyDynamicMessagesDao dynamicMessagesDao;
//    @ApiOperation("testRedis")
//    @RequestMapping(value = "testRedis",method = RequestMethod.POST)
//    public String testRedis(){
//        try{
//            String redis_key = "REDIS_KEY_REPLACER";
//            String Topics ="sessions:REDIS_KEY_REPLACER:topics";
//            String Topic= "topics:REDIS_KEY_REPLACER";
//            String Messages= "sessions:REDIS_KEY_REPLACER:messages";
//            String MessagesByTimestamp= "sessions:REDIS_KEY_REPLACER:messages_by_timestamp";
//            String sessionId = "0fab4dd67e074e16ac86db6b6c15233e_7e3da9605d064b4fa0aacca95cf683b3_2";
//
//            String setKey = Messages.replace(redis_key,sessionId);
//            System.out.println(setKey);
//            long l1= redisTemplate.boundZSetOps(setKey).zCard();
//            Set<String> range = redisTemplate.boundZSetOps(setKey).range(0, -1);
//            System.out.println(l1);
//            System.out.println(range.size());
//            return success("testRedis");
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return error(-1,"挂断失败");
//    }
//    @RequestMapping(value = "sendVideoCommunication")
//    @ApiOperation("居民发起视频通讯")
//    public String sendVideoCommunication(@ApiParam(name = "patient", value = "居民code")
//                                         @RequestParam(value = "patient", required = true) String patient,
//                                         @ApiParam(name = "consult", value = "咨询code")
//                                         @RequestParam(value = "consult", required = true) String consult,
//                                         @ApiParam(name = "doctor", value = "医生code")
//                                         @RequestParam(value = "doctor", required = true) String doctor,
//                                         @ApiParam(name = "sessionId", value = "会话id")
//                                         @RequestParam(value = "sessionId", required = true) String sessionId) {
//        try {
//            ConsultTeamDo consultTeam = consultTeamDao.findByConsult(consult);
//            if (consultTeam.getStatus() != 0) {
//                return error(-1, "该咨询已结束,无法发起视频通讯!");
//            }
//
///*            BaseDoctorDO d = doctorDao.findByCode(doctor);
//            if(d.getVideoStauts()!=null&&d.getVideoStauts()==1){
//                return error(-1, "医生在视频通讯中,无法发起视频通讯!");
//            }*/
//
//            BasePatientDO p = patientDao.findByCode(patient);
//
//            JSONObject message = new JSONObject();
//            JSONObject content = new JSONObject();
//            content.put("patient", patient);
//            content.put("patientName", p.getName());
//            content.put("consult", consult);
//            content.put("sessionId", sessionId);
//            content.put("patientName", p.getName());
//            content.put("photo", p.getPhoto());
//            message.put("id", getUID());
//            message.put("sender_id", p.getCode());
//            message.put("session_id", "system");
//            message.put("sender_name", p.getName());
//            message.put("content_type", 40);
//            message.put("timestamp", DateUtil.getStringDate());
//            message.put("content", content);
//
//            String response = imUtill.sendVideoCommunication(doctor, message.toString());
//            JSONObject jsonObject = new JSONObject(response);
//            if (1 == jsonObject.getInt("status")) {
//                return error(-1, "医生不在线无法发起视频通讯!");
//            }
////            d.setVideoStauts(1);
////            doctorDao.save(d);
//            return success("发起成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return error(-1, "发起失败!");
//    }
//    @ApiOperation("居民取消视频")
//    @RequestMapping(value = "cancelVideo", method = RequestMethod.POST)
//    public String cancelVideo(@ApiParam(name = "consult", value = "咨询code")
//                              @RequestParam(value = "consult", required = true) String consult,
//                              @ApiParam(name = "doctor", value = "医生code")
//                              @RequestParam(value = "doctor", required = true) String doctor,
//                              @ApiParam(name = "sessionId", value = "会话id")
//                              @RequestParam(value = "sessionId", required = true) String sessionId) {
//        try {
//            BaseDoctorDO d = doctorDao.findByCode(doctor);
//            d.setVideoStauts(0);
//            doctorDao.save(d);
//            BasePatientDO p = patientDao.findByCode(getUID());
//
//            JSONObject message = new JSONObject();
//            JSONObject content = new JSONObject();
//            content.put("patient", p.getCode());
//            content.put("patientName", p.getName());
//            content.put("consult", consult);
//            content.put("sessionId", sessionId);
//            content.put("patientName", p.getName());
//            content.put("photo", p.getPhoto());
//            message.put("id", getUID());
//            message.put("sender_id", p.getCode());
//            message.put("session_id", "system");
//            message.put("sender_name", p.getName());
//            message.put("content_type", 45);
//            message.put("timestamp", DateUtil.getStringDate());
//            message.put("content", content);
//
//            String response = imUtill.sendVideoCommunication(doctor, message.toString());
//
//            imUtill.sendTopicIM(p.getCode(), p.getName(), consult, "45", "居民取消视频通讯", null);
//            return success("取消成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return error(-1, "取消失败");
//    }
//    @ApiOperation("居民挂断视频")
//    @RequestMapping(value = "handUpVideo", method = RequestMethod.POST)
//    public String handUpVideo(@ApiParam(name = "consult", value = "咨询code")
//                              @RequestParam(value = "consult", required = true) String consult,
//                              @ApiParam(name = "doctor", value = "医生code")
//                              @RequestParam(value = "doctor", required = true) String doctor,
//                              @ApiParam(name = "time", value = "视频接通时长")
//                              @RequestParam(value = "time", required = true) String time) {
//        try {
//            BaseDoctorDO d = doctorDao.findById(doctor).orElse(null);
//            d.setVideoStauts(0);
//            doctorDao.save(d);
//            BasePatientDO p = patientDao.findById(getUID()).orElse(null);
//            imUtill.sendTopicIM(p.getId(), p.getName(), consult, "44", time, null);
//            return success("挂断成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return error(-1, "挂断失败");
//    }
    /**
     * 患者咨询记录查询
     *
     * @param title    咨询标题
     * @param id
     * @param pagesize 分页大小
     * @return
     */
//    @RequestMapping(value = "records")
//    @ApiOperation("患者咨询记录查询")
//    public String consultRecords(
//            @RequestParam(required = false) String title,
//            long id,
//            int pagesize) {
//        try {
//            JSONArray array = new JSONArray();
//            Page<Object> data = consultTeamService.findConsultRecordByPatient(getRepUID(), id, pagesize, title);
//            if (data != null) {
//                for (Object consult : data.getContent()) {
//                    if (consult == null) {
//                        continue;
//                    }
//                    Object[] result = (Object[]) consult;
//                    JSONObject json = new JSONObject();
//                    json.put("id", result[0]);
//                    // 设置咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈
//                    json.put("type", result[1]);
//                    // 设置咨询标识
//                    json.put("code", result[2]);
//                    // 设置显示标题
//                    json.put("title", result[3]);
//                    // 设置主诉
//                    json.put("symptoms", result[4]);
//                    // 咨询状态
//                    json.put("status", result[6]);
//                    // 设置咨询日期
//                    json.put("czrq", DateUtil.dateToStrLong((Date) result[5]));
//                    // 咨询状态
//                    json.put("doctorCode", result[7]);
//
//                    json.put("teamCode", result[8]);
//
//                    json.put("evaluate", result[9]);
//
//                    //签约code
//                    json.put("signCode", result[10]);
//
//                    array.put(json);
//                }
//            }
//            return write(200, "查询成功!", "list", array);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
    /**
     * 获取医生的排班时间
     *
     * @param doctor
     * @param week
     * @return
     */
//    @RequestMapping(value = "/doctor_worktime/week")
//    @ApiOperation("获取医生的排班时间")
//    public String getDoctorWeekWorkTime(String doctor, String week) {
//        try {
//            JSONObject result = doctorWorkTimeService.findDoctorWeekWorkTime(doctor, week);
//
//            return write(200, "查询成功!", "data", result);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
    /**
     * 获取医生某天的排班时间
     *
     * @param doctor
     * @return
     */
//    @RequestMapping(value = "/doctor_worktime")
//    @ApiOperation("获取医生某天的排班时间")
//    public String getDoctorWorkTime(String doctor) {
//        try {
//            JSONObject result = doctorWorkTimeService.findDoctorWorkTime(doctor);
//
//            return write(200, "查询成功!", "data", result);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
    /**
     * 医生是否在工作
     *
     * @param doctor
     * @return
     */
//    @RequestMapping(value = "is_doctor_working")
//    @ApiOperation("医生是否在工作")
//    public String isDoctorAtWorking(String doctor) {
//        try {
//            JSONObject result = doctorWorkTimeService.isDoctorWorking(doctor);
//            return write(200, result.getString("msg"), "data", result.getString("status"));
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    /**
     * 患者端在发起家庭医生咨询时检查全科医生和健管师是否在工作
     *
     * @param doctor
     * @param healthDoctor
     * @return
     */
//    @RequestMapping(value = "isDoctorWorkWhenconsult", method = RequestMethod.POST)
//    @ApiOperation("全科医生和健管师是否在工作")
//    public String isDoctorWorkWhenconsult(String doctor, String healthDoctor) {
//        try {
//            JSONObject result = doctorWorkTimeService.isDoctorWorkingWhenConsult(doctor, healthDoctor);
//            return write(200, result.getString("msg"), "data", result.getString("status"));
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    /**
     * 名医是否在工作
     *
     * @param doctor
     * @return
     */
//    @RequestMapping(value = "is_famous_doctor_working")
//    @ApiOperation("名医是否在工作")
//    public String isFamousDoctorAtWorking(String doctor) {
//        try {
//            JSONObject result = doctorWorkTimeService.isFamousDoctorWorking(doctor);
//            return write(200, result.getString("msg"), "data", result.getString("status"));
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    /**
     * 名医咨询剩余次数查询
     *
     * @param doctor
     * @return
     */
//    @ApiOperation("名医咨询剩余次数查询")
//    @RequestMapping(value = "/consult_times_remain")
//    public String famousDoctorTimesRemain(String doctor) {
//        try {
//            int result = doctorWorkTimeService.getDoctorConsultTimesRemain(doctor);
//            return write(200, "查询成功", "data", result);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    /**
     * 获取未完成咨询
     *
@ -655,294 +336,6 @@ public class ConsultController extends EnvelopRestEndpoint {
//        }
//    }
//    @RequestMapping(value = "intoTopic", method = RequestMethod.POST)
//    @ApiOperation("进入咨询")
//    public String intoTopic(@RequestParam(required = true) String consult) {
//        try {
//            int result = consultTeamService.intoTopic(consult, getRepUID(), getUID());
//            if (result == -1) {
//                return error(-1, "该咨询不是进行中");
//            }
//            JSONObject json = new JSONObject();
//            json.put("consult", consult);
//            json.put("content", "进入咨询");
//            BusinessLogs.info(BusinessLogs.BusinessType.consult, getUID(), getRepUID(), json);
//            return success("进入成功");
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "请求失败");
//        }
//    }
    /**
     * 名医咨询添加接口
     *
     * @param when       发病时间
     * @param symptoms   主要症状
     * @param images     图片URL地址,多图以逗号分隔
     * @param voice      语音URL地址
     * @param doctorCode 名医的code
     * @return
     */
//    @RequestMapping(value = "famousAdd")
//    @ApiOperation("名医咨询添加接口")
//    public String famousAdd(
//            @RequestParam(required = false) String when,
//            String symptoms,
//            @RequestParam(required = false) String doctorCode,
//            @RequestParam(required = false) String images,
//            @RequestParam(required = false) String voice) {
//        try {
//            //判断医生是否是在工作时间
//            JSONObject jo = doctorWorkTimeService.isFamousDoctorWorking(doctorCode);
//            if (!jo.get("status").equals("1")) {
//                return error(-1, jo.get("msg").toString());
//            }
//            //判断医生是否剩下咨询次数
//            int result = doctorWorkTimeService.getDoctorConsultTimesRemain(doctorCode);
//            if (result == 0) {
//                return error(-1, "没有次数");
//            }
//            if (StringUtils.isEmpty(images)) {
//                images = fetchWxImages();
//            }
//            // 将临时图片拷贝到正式存储路径下
//            if (StringUtils.isNotEmpty(images)) {
//                images = CommonUtil.copyTempImage(images);
//            }
//            if (StringUtils.isEmpty(voice)) {
//                voice = fetchWxVoices();
//            }
//            if (StringUtils.isNotEmpty(voice)) {
//                voice = CommonUtil.copyTempVoice(voice);
//            }
//            //判断是否已经存在还没有关闭的咨询
//            if (consultTeamService.isExistConsult(getRepUID(), doctorCode)) {
//                return error(-1, "还有咨询未结束,不允许再次提交咨询!");
//            }
//            ConsultTeam consult = new ConsultTeam();
//            // 设置咨询类型:1三师咨询,2家庭医生咨询 6.名医咨询
//            consult.setType(6);
//            // 设置发病时间
//            consult.setWhen(when);
//            // 设置主要症状
//            consult.setSymptoms(symptoms);
//            // 设置咨询图片URL
//            consult.setImages(images);
//            // 设置咨询语音URL
//            consult.setVoice(voice);
//            consult.setDoctor(doctorCode);//设置专科医生
//            // 保存到数据库
//            JSONObject object = consultTeamService.famousConsult(consult, getRepUID(), "1", getUID());
//            JSONObject resultConsult = new JSONObject(consult);
//            resultConsult.put("session_id", object.getString("session_id"));
//            //名医咨询次数减一
//            doctorWorkTimeService.setDoctorCurrentConsultTimesRemain(doctorCode);
//            // 推送消息给医生
//            pushMsgTask.put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.D_CT_03.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.您有新的名医咨询.name(), consult.getConsult());
//            BusinessLogs.info(BusinessLogs.BusinessType.consult, getRepUID(), getUID(), new JSONObject(consult));
//            return write(200, "提交成功", "data", resultConsult);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception ex) {
//            error(ex);
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
    /**
     * 名医列表
     *
     * @return
     */
//    @RequestMapping(value = "famousDoctorList")
//    @ApiOperation("名医列表")
//    public String famousDoctorList(
//            @RequestParam(required = false) String name) {
//        try {
//            JSONArray array = new JSONArray();
//            List<Doctor> list = doctorService.famousDoctorList(name);
//            if (list != null) {
//                for (BaseDoctorDO doctor : list) {
//                    if (doctor == null) {
//                        continue;
//                    }
//
//                    // 判断名医是否在工作
//                    JSONObject isWorking = doctorWorkTimeService.isDoctorWorking(doctor.getCode());
//
//                    if (isWorking == null || !isWorking.getString("status").equals("1")) {
//                        continue;
//                    }
//
//                    int num = doctorWorkTimeService.getDoctorConsultTimesRemain(doctor.getCode());
//
//                    if (num < 1) {
//                        continue;
//                    }
//
//                    JSONObject json = new JSONObject();
//                    json.put("id", doctor.getId());
//                    // 医生标识
//                    json.put("code", doctor.getCode());
//                    // 医生性别
//                    json.put("sex", doctor.getSex());
//                    // 医生姓名
//                    json.put("name", doctor.getName());
//                    // 所在医院名称
//                    json.put("hospital", doctor.getHospital());
//                    // 所在医院名称
//                    json.put("hospital_name", doctor.getHospitalName());
//                    // 科室名称
//                    json.put("dept_name", (doctor.getDeptName() == null ||
//                            StringUtils.isEmpty(doctor.getDeptName().toString())) ? " " : doctor.getDeptName());
//                    // 职称名称
//                    json.put("job_name", (doctor.getJobName() == null ||
//                            StringUtils.isEmpty(doctor.getJobName().toString())) ? " " : doctor.getJobName());
//                    // 头像
//                    json.put("photo", doctor.getPhoto());
//                    // 简介
//                    json.put("introduce", doctor.getIntroduce());
//                    // 专长
//                    json.put("expertise", doctor.getExpertise());
//                    // 剩余咨询次数
//                    json.put("num", num);
//                    array.put(json);
//                }
//            }
//            return write(200, "获取医院医生列表成功!", "list", array);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "获取医院医生列表失败!");
//        }
//    }
//    @RequestMapping(value = "status")
//    public String status(String consult) {
//        try {
//            ConsultTeam ct = consultTeamService.findByCode(consult);
//            if (ct == null) {
//                return error(-1, "获取状态失败!");
//            } else {
//                return write(200, "获取状态成功!", "data", ct.getStatus());
//            }
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "获取状态失败!");
//        }
//    }
//    @RequestMapping(value = "evaluateStatus")
////    public String statuss(String consult) {
////        try {
////            ConsultTeam ct = consultTeamService.findByCode(consult);
////            if (ct == null) {
////                return error(-1, "获取状态失败!");
////            } else {
////                return write(200, "获取状态成功!", "data", ct.getEvaluate());
////            }
////        } catch (Exception e) {
////            error(e);
////            return invalidUserException(e, -1, "获取状态失败!");
////        }
////    }
    /**
     * 查询患者三师咨询咨询列表
     *
     * @param status   咨询状态(0未结束,1已结束,-1 已取消)
     * @param pagesize 页数
     * @return 查询结果
     */
//    @RequestMapping(value = "list")
//    @ApiOperation("查询患者三师咨询咨询列表")
//    public String list(int status, long id, int pagesize) {
//        try {
//            Page<ConsultTeam> consults = consultTeamService.findByPatient(getRepUID(), status, id, pagesize);
//            JSONArray jsonArray = new JSONArray();
//            if (consults != null) {
//                for (ConsultTeam consult : consults) {
//                    if (consult == null) {
//                        continue;
//                    }
//                    JSONObject json = new JSONObject();
//                    json.put("id", consult.getId());
//                    // 设置咨询标志
//                    json.put("code", consult.getConsult());
//                    // 设置咨询类型:0公共咨询,1指定医生,2三师咨询
//                    json.put("type", consult.getType());
//                    // 设置标题
//                    json.put("title", consult.getSymptoms());
//                    // 设置发病时间
//                    json.put("when", consult.getWhen());
//                    // 设置患者未读数量
//                    json.put("patientRead", consult.getPatientRead());
//                    // 设置状态
//                    json.put("status", consult.getStatus());
//                    // 设置患者评价标识
//                    json.put("comment", consult.getComment());
//                    // 设置关联指导
//                    json.put("guidance", consult.getGuidance());
//                    // 设置咨询或回复时间
//                    json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
//                    jsonArray.put(json);
//                }
//            }
//            return write(200, "查询成功", "list", jsonArray);
//        } catch (Exception ex) {
//            error(ex);
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
    /**
     * 患者取消三师咨询
     *
     * @param consult
     * @return
     */
//    @RequestMapping(value = "cancel")
//    @ApiOperation("患者取消三师咨询")
//    public String cancel(String consult) {
//        try {
//            int row = consultTeamService.cancel(consult);
//            if (row > 0) {
//                return success("咨询已取消!");
//            } else {
//                return error(-1, "咨询不能取消!");
//            }
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "操作失败!");
//        }
//    }
    /**
     * 修改状态为1的咨询记录为结束
     *
     * @param code 咨询标识
     * @return
     */
//    @RequestMapping(value = "finish")
//    @ApiOperation("修改状态为1的咨询记录为结束")
//    public String finish(@RequestParam(required = true) String code) {
//        try {
//            int row = consultTeamService.finishConsult(code, getRepUID(), 1);
//            if (row > 0) {
//                return success("操作成功!");
//            } else if (row == -2) {
//                return error(-1, "续方未审核,不能结束续方咨询!");
//            } else {
//                return error(-1, "操作失败!");
//            }
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "操作失败!");
//        }
//    }
//    @RequestMapping(value = "imAppend")
//    @ApiOperation("im会话回复通用接口")
@ -1104,42 +497,6 @@ public class ConsultController extends EnvelopRestEndpoint {
                            if (doctorCode.equals(patient.getId())) {
                                continue;
                            }
                            //健管
                            Boolean flag = messageService.getMessageNoticeSettingByMessageType(doctorCode, "1", MessageNoticeSetting.MessageTypeEnum.imSwitch.getValue());
                            //全科
//                            Boolean flag2 = !messageService.getMessageNoticeSettingByMessageType(doctorCode, "1", MessageNoticeSetting.MessageTypeEnum.familyTopicSwitch.getValue());
//                            if (flag) {
//                                //            新增发送医生助手模板消息 v1.4.0 by wujunjie
//                                BaseDoctorDO doctor = doctorDao.findById(doctorCode).orElse(null);
//                                String doctorOpenID = doctor.getOpenid();
//                                if (StringUtils.isNotEmpty(doctorOpenID)) {
//                                    String title = "";
//                                    ConsultDo consultSingle = consultDao.findById(log.getConsult()).orElse(null);
//                                    if (consultSingle != null) {
//                                        Integer singleType = consultSingle.getType();
//                                        if (singleType != null && singleType == 8) {
//                                            title = consultSingle.getTitle();
//                                        } else if (singleType != null && singleType != 8) {
//                                            title = consultSingle.getSymptoms();
//                                        }
//                                        String repContent = parseContentType(type + "", content);
//                                        String first = "居民" + patient.getName() + "的咨询有新的回复。";
//                                        String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
//                                        List<NameValuePair> params = new ArrayList<>();
//                                        params.add(new BasicNameValuePair("type", "8"));
//                                        params.add(new BasicNameValuePair("openId", doctorOpenID));
//                                        params.add(new BasicNameValuePair("url", targetUrl));
//                                        params.add(new BasicNameValuePair("first", first));
//                                        params.add(new BasicNameValuePair("remark", "请进入手机APP查看"));
//                                        String keywords = title + "," + repContent + "," + doctor.getName();
//                                        params.add(new BasicNameValuePair("keywords", keywords));
//
//                                        httpClientUtil.post(url, params, "UTF-8");
//                                        System.out.println("发送对象:" + doctorCode);
//                                        System.out.println("发送对象名字:" + doctor.getName());
//                                    }
//                                }
//                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
@ -1154,36 +511,6 @@ public class ConsultController extends EnvelopRestEndpoint {
        }
    }
    /**
     * 获取医生评价列表
     *
     * @param consult  咨询标识
     * @param pagesize 每页显示数,默认为10
     * @return
     */
//    @GetMapping(value = "loglist2")
//    @ApiOperation("获取医生评价列表")
//    public String loglist2(@RequestParam String consult, @RequestParam int page, @RequestParam int pagesize) {
//        try {
//            ConsultTeamDo consultModel = consultTeamService.findByCode(consult);
//            if (consultModel == null) {
//                return error(-1, "咨询记录不存在!");
//            }
//            JSONObject messageObj = imUtill.getTopicMessage(consultModel.getConsult(), consultModel.getStartMsgId(), consultModel.getEndMsgId(), page, pagesize, getRepUID());
//
//            //过滤续签
//            consultTeamService.removeRenewPerson(messageObj, getRepUID());
//            //过滤非本次咨询专科医生
//            consultTeamService.removeSpecialist(messageObj, getRepUID(), consult);
//
//            return write(200, "查询成功", "list", messageObj);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
    /**
     * 网络咨询咨询日志查询
@ -1218,143 +545,7 @@ public class ConsultController extends EnvelopRestEndpoint {
        }
    }
    /**
     * 网络咨询咨询日志查询
     *
     * @param pagesize 每页显示数,默认为10
     * @return
     */
//    @RequestMapping(value = "logs")
//    @ApiOperation("网络咨询咨询日志查询")
//    public String logs(@RequestParam String sessionId, @RequestParam(required = false) String startMsgId, @RequestParam(required = false) String endMsgId, @RequestParam int page, @RequestParam int pagesize) {
//        try {
//            JSONArray messageArray = imUtill.getSessionMessage(sessionId, startMsgId, endMsgId, page, pagesize, getRepUID());
//            return write(200, "查询成功", "list", messageArray);
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//    @RequestMapping(value = "participants")
//    public String participants(@RequestParam String sessionId) {
//        try {
//            JSONArray participants = imUtill.getSessionsParticipants(sessionId);
//
//            //过滤续签
//            consultTeamService.removeRenewPerson(participants, getRepUID());
//
//            return write(200, "查询成功", "list", participants);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
    /**
     * 查找单个咨询记录
     *
     * @param consult 咨询标识
     * @param logId   记录标识
     * @return
     */
//    @RequestMapping(value = "oneLog")
//    @ApiOperation("查找单个咨询记录")
//    public String oneLog(@RequestParam String consult, @RequestParam Long logId, @RequestParam int msgType) {
//        try {
//            ConsultTeamDo consultModel = consultTeamService.findByCode(consult);
//            if (consultModel == null) {
//                return error(-1, "咨询记录不存在!");
//            }
//
//            String url = SystemConf.getInstance().getSystemProperties().getProperty("im_list_get")
//                    + "api/v1/chats/message";
//            String reG = httpUtil.sendGet(url, "id=" + logId + "&type=" + msgType);
//            JSONObject obj = null;
//            if (!org.springframework.util.StringUtils.isEmpty(reG)) {
//                obj = new JSONObject(new String(reG.getBytes(), "utf-8"));
//            } else {
//                return error(-1, "查询失败");
//            }
//
//            if (obj == null) {
//                return error(-1, "查询失败");
//            }
//
//            JSONObject json = new JSONObject();
//
//            json.put("id", obj.getInt("id"));
//            if (!obj.getString("from").equals(getRepUID())) {
//                BaseDoctorDO doc = doctorService.findDoctorByCode(obj.getString("from"));
//                // 设置回复医生姓名
//                json.put("doctorName", doc.getName());
//                json.put("photo", doc.getPhoto());
//            } else {
//                BasePatientDO p = patientDao.findByCode(obj.getString("from"));
//                // 设置回复医生姓名
//                json.put("doctorName", p.getName());
//                json.put("photo", p.getPhoto());
//            }
//
//            // 设置回复内容
//            json.put("content", obj.getString("content"));
//            // 设置咨询或回复时间
//            json.put("time", DateUtil.dateToStr(new Date(obj.getLong("timestamp")), DateUtil.YYYY_MM_DD_HH_MM_SS));
//            // 设置记录类型:1文字,2图片,3语音
//            json.put("msgType", obj.getInt("contentType"));
//            // 设置类型:0患者问,1医生回复,2患者追问,3患者评价
//            if (!obj.getString("from").equals(getRepUID())) {
//                json.put("type", 1);
//            } else {
//                json.put("type", obj.getInt("contentType") == 6 ? 0 : 2);
//            }
//
//            // 返回结果
//            return write(200, "查询成功", "consult", json);
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
    /**
     * 三师咨询评论
     * consult 咨询标识
     * content 评价内容
     * star    星级
     * 操作结果
     */
//    @RequestMapping(value = "comment")
//    @ApiOperation("三师咨询评论")
//    public String comment(String consult, String content, int star) {
//        try {
//            // 保存评价
//            JSONArray array = doctorCommentService.consultComment(getRepUID(), consult, content, star, 2);
//            // 添加到统计队列
//            if (array != null) {
//                //新增判断 续方咨询暂不统计
//                ConsultTeam consultTeam = consultTeamDao.findByConsult(consult);
//                if (consultTeam.getType() != 8) {
//                    DoctorStatisticsTask.getInstance(doctorStatisticsService).put(array);
//                }
//            }
//            // 添加评价记录
//            ConsultTeamLogDo log = new ConsultTeamLogDo();
//            log.setConsult(consult);
//            log.setContent(content);
//            log.setChatType(1);
//            log.setDel("1");
//            log.setType(3);
//            log = consultTeamService.reply(log, getRepUID(), null, log.getType());
//            return success("感谢您的评价!");
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "评价失败!");
//        }
//
//    }
    @RequestMapping(value = "getTopic")
    public Envelop getTopic(String consult) {
        try {
@ -1378,209 +569,6 @@ public class ConsultController extends EnvelopRestEndpoint {
    /*===========================================续方咨询==============================================================*/
//    @RequestMapping(value = "isPrescriptionConsult", method = RequestMethod.GET)
//    @ApiOperation("是否可以续方咨询")
//    public String isPrescriptConsult(@ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = true) String patient) {
//        try {
//            JSONObject json = consultTeamService.isPrescriptConsult(patient);
//            if (json.has("msg")) {
//                return error(-1, json.getString("msg"));
//            }
//            return write(200, "查询成功!", "data", json);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
//    @RequestMapping(value = "addPrescriptionConsult", method = RequestMethod.POST)
//    @ApiOperation("添加续方咨询")
//    public String addPrescriptionConsult(@ApiParam(name = "jwCode", value = "基位处方code", defaultValue = "10")
//                                         @RequestParam(value = "jwCode", required = true) String jwCode,
//                                         @ApiParam(name = "doctor", value = "咨询医生(开方医生、审核医生)", defaultValue = "86225d1365e711e69f7c005056850d66")
//                                         @RequestParam(value = "doctor", required = true) String doctor,
//                                         @ApiParam(name = "type", value = "咨询类型(1、高血压-续方咨询;2、糖尿病-续方咨询,3、高糖-续方咨询 4、其他疾病咨询)", defaultValue = "1")
//                                         @RequestParam(value = "type", required = true) Integer type,
//                                         @ApiParam(name = "adminTeamId", value = "签约行政团队id", defaultValue = "224")
//                                         @RequestParam(value = "adminTeamId", required = true) Long adminTeamId,
//                                         @ApiParam(name = "reason", value = "续方说明", defaultValue = "续方申请")
//                                         @RequestParam(value = "reason", required = false) String reason,
//                                         @ApiParam(name = "signTag", value = "0为家签续方,1未非家签约", defaultValue = "0")
//                                         @RequestParam(value = "signTag", required = false) Integer signTag,
//                                         @ApiParam(name = "hospital", value = "机构CODE")
//                                         @RequestParam(value = "hospital", required = false) String hospital,
//                                         @ApiParam(name = "systolic", value = "收缩压")
//                                         @RequestParam(value = "systolic", required = false) String systolic,
//                                         @ApiParam(name = "diastolic", value = "舒张压")
//                                         @RequestParam(value = "diastolic", required = false) String diastolic,
//                                         @ApiParam(name = "bloodSugar", value = "血糖")
//                                         @RequestParam(value = "bloodSugar", required = false) String bloodSugar,
//                                         @ApiParam(name = "bloodSugarType", value = "血糖类型")
//                                         @RequestParam(value = "bloodSugarType", required = false) String bloodSugarType,
//                                         @ApiParam(name = "hospitalName", value = "机构名称")
//                                         @RequestParam(value = "hospitalName", required = false) String hospitalName,
//                                         @ApiParam(name = "ratType", value = "费别类型 zy_common_dict表IV_RATE_TYPE_DICT")
//                                         @RequestParam(value = "ratType", required = false) String ratType,
//                                         @RequestParam(required = true) @ApiParam(value = "配送方式:1 自取 2快递配送 3健管师配送 4网格员派送", name = "dispensaryType") int dispensaryType,
//                                         @RequestParam(required = true) @ApiParam(value = "配送地址json", name = "addressJson", defaultValue = "{\"townName\":\"海沧区\",\"code\":\"3502050100\",\"address\":" +
//                                                 "\"冰岛\",\"cityName\":\"厦门市\",\"townCode\":\"350205\",\"provinceCode\":\"350000\",\"cityCode\":\"350200\",\"name\":\"海沧区嵩屿街道社区卫生服务中心\"," +
//                                                 "\"provinceName\":\"福建省\",\"streeCode\":\"35020501\",\"streeName\":\"皇后大道东\",\"phone\":\"13253541190\"}") String addressJson) {
//        try {
//            ConsultTeam consult = new ConsultTeam();
//            consult.setType(8);//续方咨询
//            consult.setAdminTeamId(adminTeamId);
//
//            //增加体征数据上传发送IM消息标识:1血压 2血糖 3血压+血糖---huangwenjie 2017.11.06
//            consult.setHealthindexType(type);
//            // 保存到数据库
//            int res = 0;
//            synchronized (jwCode.intern()) {
//                res = consultTeamService.addPrescriptionConsult(jwCode, getRepUID(), getUID(), doctor, consult, reason, type,
//                        addressJson, dispensaryType, signTag, hospital, hospitalName, adminTeamId, systolic, diastolic, bloodSugar, bloodSugarType, ratType);
//            }
//            if (res == -1) {
//                return error(-1, "该处方存在未审核的续方,无法进行续方咨询!");
//            }
//            if (res == -2) {
//                return error(-1, "您还未签约,不能发起续方咨询!");
//            }
//            if (res == -3) {
//                return error(-1, "您当天有未完成的续方,不能发起续方咨询!");
//            }
//
//            if (messageService.getMessageNoticeSettingByMessageType(doctor, "1", MessageNoticeSetting.MessageTypeEnum.prescriptionSwitch.getValue())) {
//                // 推送消息给医生
//                pushMsgTask.put(doctor, MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_PRESCRIPTION.D_CT_05.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_PRESCRIPTION.续方咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_PRESCRIPTION.您有新的续方咨询.name(), consult.getConsult());
//                try {
//                    //续方消息应该发给居民签约的团队长,modify by hmf
//                    SignFamily signFamily = signFamilyDao.findByPatient(getRepUID());
//                    BaseDoctorDO doctor1 = doctorDao.findByAdminTeamId(signFamily.getAdminTeamId());
//                    //            新增发送医生助手模板消息 v1.4.0 by wujunjie
//                    BasePatientDO patient = patientDao.findByCode(getRepUID());
//                    String doctorOpenID = doctor1.getOpenid();
//                    if (StringUtils.isNotEmpty(doctorOpenID)) {
//                        String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
//                        List<NameValuePair> params = new ArrayList<>();
//                        params.add(new BasicNameValuePair("type", "9"));
//                        params.add(new BasicNameValuePair("openId", doctorOpenID));
//                        params.add(new BasicNameValuePair("url", targetUrl));
//                        params.add(new BasicNameValuePair("first", doctor1.getName() + "医生您好。您的签约居民" + patient.getName() + "申请线上续方,请尽快审核。"));
//                        params.add(new BasicNameValuePair("remark", "请进入手机APP查看"));
//                        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
//                        String keywords = "续方审核" + "," + doctor1.getHospitalName() + "," + doctor1.getName();
//                        params.add(new BasicNameValuePair("keywords", keywords));
//
//                        httpClientUtil.post(url, params, "UTF-8");
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//            BusinessLogs.info(BusinessLogs.BusinessType.consult, getRepUID(), getUID(), new JSONObject(consult));
//            return write(200, "提交成功", "data", consult);
//
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "添加失败");
//        }
//    }
//    @RequestMapping(value = "getPreConsultList", method = RequestMethod.GET)
//    @ApiOperation("获取续方咨询列表")
//    public String getPreConsultList(@ApiParam(name = "title", value = "咨询标题") @RequestParam(required = false) String title,
//                                    @ApiParam(name = "id", value = "第几页") @RequestParam(required = true) long id,
//                                    @ApiParam(name = "pagesize", value = "页面大小") @RequestParam(required = true) int pagesize) {
//        try {
//            JSONArray array = new JSONArray();
//            Page<Object> data = consultTeamService.findConsultRecordByType(getRepUID(), id, pagesize, 8, title);//8表示续方咨询
//            if (data != null) {
//                for (Object consult : data.getContent()) {
//                    if (consult == null) {
//                        continue;
//                    }
//                    Object[] result = (Object[]) consult;
//                    JSONObject json = new JSONObject();
//                    json.put("id", result[0]);
//                    // 设置咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈,8 续方咨询
//                    json.put("type", result[1]);
//                    // 设置咨询标识
//                    json.put("code", result[2]);
//                    // 设置显示标题
//                    json.put("title", result[3]);
//                    // 设置主诉
//                    json.put("symptoms", result[4]);
//                    // 咨询状态
//                    json.put("status", result[6]);
//                    // 设置咨询日期
//                    json.put("czrq", DateUtil.dateToStrLong((Date) result[5]));
//                    // 咨询状态
//                    json.put("doctorCode", result[7]);
//                    json.put("evaluate", result[8]);
//                    String relationCode = result[9] == null ? "" : result[9].toString();
//                    json.put("prescriptionCode", relationCode);//续方code
//                    json.put("prescriptionDt", prescriptionDiagnosisService.getPrescriptionDiagnosis(relationCode));//续方疾病类型
//                    json.put("prescriptionInfo", prescriptionDiagnosisService.getPrescriptionInfo(relationCode));//续方药品信息
//
//                    array.put(json);
//                }
//            }
//            return write(200, "查询成功!", "list", array);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
//    @RequestMapping(value = "prescriptionDetail", method = RequestMethod.GET)
//    @ApiOperation("获取续方信息")
//    public String prescriptionDetail(@ApiParam(name = "consult", value = "咨询code") @RequestParam(required = true) String consult) {
//        try {
//            JSONObject json = new JSONObject();
//
//            Consult consult1 = consultDao.findByCode(consult);
//
//            String prescriptionCode = consult1.getRelationCode();
//            Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
//            json.put("status", prescription.getStatus());//状态 (-1 审核不通过 , 0 审核中, 10 审核通过/待支付 ,21支付失败  20 配药中/支付成功, 21 等待领药 ,30 配送中 ,100配送成功/已完成)
//            json.put("prescriptionInfo", prescriptionDiagnosisService.getPrescriptionInfo(prescriptionCode));//续方药品信息
//            json.put("symptoms", consult1.getSymptoms());//咨询类型--- 1高血压,2糖尿病
//            json.put("jwCode", prescription.getJwCode());//基位处方code
//            json.put("code", prescription.getCode());//续方code
//            json.put("viewJiancha", prescription.getViewJiancha());//检查
//            json.put("viewTizhen", prescription.getViewTizhen());//体征
//            json.put("viewChufang", prescription.getViewChufang());//处方
//            json.put("viewXufang", prescription.getViewXufang());//续方
//            json.put("viewWenjuan", prescription.getViewWenjuan());//问卷
//            json.put("viewSuifang", prescription.getViewSuifang());//随访
//
//            return write(200, "查询成功!", "data", json);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
//    @RequestMapping(value = "remainConsultTimes", method = RequestMethod.GET)
//    @ApiOperation("获取剩余家庭咨询次数")
//    public String countRemainConsult() {
//        try {
//            String patient = getRepUID();
//            JSONObject result = consultTeamService.countRemainConsult(patient);
//            if (result.has("count") && result.has("amount")) {
//                return write(200, "查询成功!", "data", result);
//            } else if (result.has("count") && !result.has("amount")) {
//                return error(-1, "您的签约已到期,请重新申请");
//            } else {
//                return error(-1, "查询失败!");
//            }
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
    /**
     * 解析contentType
     * PlainText: 1,   // 信息
@ -1839,22 +827,7 @@ public class ConsultController extends EnvelopRestEndpoint {
//        }
//    }
    /**
     * 获取患者发起咨询时可选择的专科医生团队列表,
     *
     * @param patientCode 患者code
     * @return
     */
//    @RequestMapping(value = "getConsultDoctorForConsulting", method = RequestMethod.GET)
//    @ApiOperation("获取咨询医生团队列表列表")
//    public String getConsultDoctorForConsulting(@RequestParam("patientCode") String patientCode) {
//        try {
//            return write(200, "查询成功", "data", consultTeamService.getConsultDoctorForConsulting(patientCode));
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    /**
     *

+ 3 - 1118
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/controller/DoctorConsultController.java

@ -1,27 +1,13 @@
package com.yihu.jw.hospital.module.consult.controller;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.hospital.message.service.SystemMessageService;
import com.yihu.jw.hospital.module.consult.service.ConsultTeamService;
import com.yihu.jw.hospital.module.followup.service.FollowUpService;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.DoctorAssistantUtil;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.common.CommonUtil;
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.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@ -33,62 +19,13 @@ import org.springframework.web.bind.annotation.RestController;
 * @author George
 */
@RestController
@RequestMapping(value = "/doctor/consult", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RequestMapping(value = "/doctor/consult")
@Api(description = "三师咨询")
public class DoctorConsultController extends EnvelopRestEndpoint {
//    @Value("${doctorAssistant.api}")
    private String doctorAssistant;
//    @Value("${doctorAssistant.target_url}")
    private String targetUrl;
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private BasePatientService patientService;
    @Autowired
    private BaseDoctorInfoService doctorInfoService;
    @Autowired
    private com.yihu.jw.util.common.CommonUtil CommonUtil;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private FollowUpService followUpService;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private SystemMessageService messageService;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctorAssistantUtil doctorAssistantUtil;
    //    @Autowired
//    private DoctorHelpDao doctorHelpDao;
//    @Autowired
//    private HospitalInviteSpecialistDao inviteSpecialistDao;
//    @Autowired
//    private PrescriptionDiagnosisService prescriptionDiagnosisService;
//    @Autowired
//    private DoctorWorkTimeService doctorWorkTimeService;
//    @Autowired
//    private TalkGroupService talkGroupService;
//    @Autowired
//    private HttpClientUtil httpClientUtil;
    private ConsultTeamService consultTeamService;
    @RequestMapping(value = "queryByConsultCode", method = RequestMethod.GET)
@ -114,22 +51,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
        }
    }
    @ApiOperation("咨询是否结束")
    @RequestMapping(value = "/getConsultStatusByPrescription", method = RequestMethod.GET)
    public String getConsultStatusByPrescription(@ApiParam(name = "prescriptionCode", value = "续方code")
                                                 @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode) {
        try {
            ConsultTeamDo consultTeam = consultTeamService.getConsultStatus(prescriptionCode);
            if (consultTeam != null) {
                return write(200, "查询成功", "data", consultTeam.getStatus());
            } else {
                return error(-1, "咨询不存在");
            }
        } catch (Exception e) {
            return e.getMessage();
        }
    }
//
//    /**
@ -220,56 +141,7 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//            return error(-1, "发送失败");
//        }
//    }
//
//    @ApiOperation("医生拒绝视频")
//    @RequestMapping(value = "refuseVideo", method = RequestMethod.POST)
//    public String refuseVideo(@ApiParam(name = "consult", value = "咨询code")
//                              @RequestParam(value = "consult", required = true) String consult,
//                              @ApiParam(name = "doctor", value = "医生code")
//                              @RequestParam(value = "doctor", required = true) String doctor) {
//        try {
//            Doctor d = doctorDao.findByCode(doctor);
//            d.setVideoStauts(0);
//            doctorDao.save(d);
//            imUtill.sendTopicIM(doctor, d.getName(), consult, "43", "医生在忙,建议提现预约视频通讯", null);
//            return success("拒绝成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//
//    }
//
//    @ApiOperation("医生接通视频")
//    @RequestMapping(value = "connectVideo", method = RequestMethod.POST)
//    public String connectVideo() {
//        try {
//            Doctor doctor = doctorDao.findByCode(getUID());
//            doctor.setVideoStauts(1);
//            doctorDao.save(doctor);
//            return success("接通成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//
//    }
//
//    @ApiOperation("医生挂断视频")
//    @RequestMapping(value = "handUpVideo", method = RequestMethod.POST)
//    public String handUpVideo(@ApiParam(name = "consult", value = "咨询code")
//                              @RequestParam(value = "consult", required = true) String consult,
//                              @ApiParam(name = "time", value = "视频接通时长")
//                              @RequestParam(value = "time", required = true) String time) {
//        try {
//            Doctor doctor = doctorDao.findByCode(getUID());
//            doctor.setVideoStauts(0);
//            doctorDao.save(doctor);
//            imUtill.sendTopicIM(doctor.getCode(), doctor.getName(), consult, "41", time, null);
//            return success("挂断成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//
//    }
//
//    /**
//     * 三师咨询列表查询
@ -369,26 +241,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//    }
//
//
//    @RequestMapping(value = "list_by_team", method = RequestMethod.POST)
//    @ApiOperation(value = "居民咨询列表查询")
//    public String listByTeam(@RequestParam @ApiParam(value = "居民Code") String patient,
//                             @RequestParam @ApiParam(value = "团队Code") Long teamCode,
//                             @RequestParam @ApiParam(value = "第几页") int page,
//                             @RequestParam @ApiParam(value = "页大小") int pagesize) {
//        try {
//            if (StringUtils.isEmpty(patient)) {
//                return error(-1, "请输入需查询的居民");
//            }
//            if (teamCode == null || teamCode < 1) {
//                return error(-1, "请输入需查询的居民的团队");
//            }
//            page = page > 0 ? page - 1 : 0;
//            JSONArray jsonArray = consultTeamService.findByPatientAndTeam(patient, teamCode, page, pagesize);
//            return write(200, "查询成功", "data", jsonArray);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 获取三师家庭咨询
@ -466,645 +318,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//        }
//    }
//
//    @RequestMapping(value = "/hasTnvite", method = RequestMethod.POST)
//    public String hasTnvite(String groupCode) {
//        try {
//            JSONObject jo = new JSONObject();
//            List<WlyyTalkGroupMember> wlyyTalkGroupMembers = talkGroupService.findTalkGroupMembers(groupCode);
//            if (wlyyTalkGroupMembers.size() > 2) {
//                jo.put("hasTnvite", 1);//有邀请
//            } else {
//                jo.put("hasTnvite", 0);//没邀请
//            }
//            return write(200, "查询成功", "list", jo);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 名医列表
//     *
//     * @return
//     */
//    @ApiOperation("名医列表")
//    @RequestMapping(value = "famousDoctorList", method = RequestMethod.POST)
//    public String famousDoctorList(
//            @RequestParam(required = false) String name) {
//        try {
//            JSONArray array = new JSONArray();
//            List<Doctor> list = doctorService.getDoctorFamousDoctorList(name);
//            if (list != null) {
//                for (Doctor doctor : list) {
//                    if (doctor == null) {
//                        continue;
//                    }
//                    // 过滤掉自己
//                    if (doctor.getCode().equals(getUID())) {
//                        continue;
//                    }
//
//                    // 判断名医是否在工作
//                    JSONObject isWorking = doctorWorkTimeService.isDoctorWorking(doctor.getCode());
//
//                    if (isWorking == null || !isWorking.getString("status").equals("1")) {
//                        continue;
//                    }
//
//                    JSONObject json = new JSONObject();
//                    json.put("id", doctor.getId());
//                    // 医生标识
//                    json.put("code", doctor.getCode());
//                    // 医生性别
//                    json.put("sex", doctor.getSex());
//                    // 医生姓名
//                    json.put("name", doctor.getName());
//                    // 类别
//                    json.put("level", doctor.getLevel());
//                    // 所在医院名称
//                    json.put("hospital", doctor.getHospital());
//                    // 所在医院名称
//                    json.put("hospital_name", doctor.getHospitalName());
//                    // 科室名称
//                    json.put("dept_name", (doctor.getDeptName() == null ||
//                            StringUtils.isEmpty(doctor.getDeptName().toString())) ? " " : doctor.getDeptName());
//                    // 职称名称
//                    json.put("job_name", (doctor.getJobName() == null ||
//                            StringUtils.isEmpty(doctor.getJobName().toString())) ? " " : doctor.getJobName());
//                    // 头像
//                    json.put("photo", doctor.getPhoto());
//                    // 简介
//                    json.put("introduce", doctor.getIntroduce());
//                    // 专长
//                    json.put("expertise", doctor.getExpertise());
//                    array.put(json);
//                }
//            }
//            return write(200, "获取医院医生列表成功!", "list", array);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 获取咨询全科医生签约量
//     *
//     * @param consults
//     * @return
//     */
//    @ApiOperation("获取咨询全科医生签约量")
//    @RequestMapping(value = "/consult_sign", method = RequestMethod.POST)
//    public String consultSign(String consults) {
//        try {
//            List<Map<String, Object>> list = consultTeamService.getConsultSign(consults.split(","));
//            return write(200, "查询成功", "data", new JSONArray(list));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 结束三师咨询接口
//     *
//     * @param consult 三师咨询标识
//     * @return
//     */
//    @ApiOperation("结束三师咨询接口")
//    @RequestMapping(value = "finish", method = RequestMethod.POST)
//
//    public String finish(String consult) {
//        try {
//            int flag = consultTeamService.finish(consult, getUID(), 2);
//            if (flag > 0) {
//                return success("咨询已关闭");
//            } else if (flag == -2) {
//                return error(-1, "续方未审核,不能结束续方咨询!");
//            } else {
//                return error(-1, "关闭失败!");
//            }
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "关闭失败!");
//        }
//    }
//
//
//    /**
//     * 医生咨询咨询日志查询
//     *
//     * @param consult  咨询标识
//     * @param patient  患者标识
//     * @param pagesize 每页显示数,默认为10
//     * @return
//     */
//    @ApiOperation("医生咨询咨询日志查询")
//    @RequestMapping(value = "record", method = RequestMethod.POST)
//    public String record(String consult, String patient, long id, int pagesize) {
//        try {
//            Patient patientTemp = null;
//            if (id <= 0) {
//                // 只有第一页才会查询患者信息
//                patientTemp = patientService.findByCode(patient);
//                // 更新医生未读数量为0
//                consultTeamService.clearDoctorRead(consult);
//            }
//            // 查询日志列表
//            JSONArray jsonArray = new JSONArray();
//            Page<ConsultTeamDoLog> list = consultTeamService.findLogByConsult(consult, id, pagesize);
//            if (list != null) {
//                for (ConsultTeamDoLog log : list) {
//                    if (consult == null) {
//                        continue;
//                    }
//                    JSONObject json = new JSONObject();
//                    json.put("id", log.getId());
//                    // 设置回复内容
//                    json.put("content", log.getContent());
//                    // 设置回复医生姓名
//                    json.put("doctorName", log.getDoctorName());
//                    // 设置回复人头像
//                    json.put("photo", log.getPhoto());
//                    // 设置日志类型
//                    json.put("type", log.getType());
//                    // 设置记录类型
//                    json.put("chatType", log.getChatType());
//                    // 设置咨询或回复时间
//                    json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
//                    jsonArray.put(json);
//                }
//            }
//            // 设置返回结果
//            JSONObject values = new JSONObject();
//            if (patientTemp != null) {
//                JSONObject patientJson = new JSONObject();
//                // 设置患者标识
//                patientJson.put("patient", patientTemp.getCode());
//                // 设置姓名
//                patientJson.put("name", patientTemp.getName());
//                // 设置头像
//                patientJson.put("photo", patientTemp.getPhoto());
//                values.put("patient", patientJson);
//            }
//            values.put("list", jsonArray);
//            // 返回结果
//            return write(200, "查询成功", "data", values);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 医生回复网络咨询
//     *
//     * @param patient 患者标识
//     * @param consult 咨询标识
//     * @param content 回复内容
//     * @param type    回复类型,1文字,2图片,3语音
//     * @return
//     */
//    @ApiOperation("医生回复网络咨询")
//    @RequestMapping(value = "reply", method = RequestMethod.POST)
//    public String reply(String patient, String consult, String content, int type) {
//        try {
//            // 查询医生基本信息
//            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
//            if (doctor == null) {
//                return error(-1, "回复失败!");
//            } else {
//                ConsultTeamDoLog log = new ConsultTeamDoLog();
//                // 设置咨询标识
//                log.setConsult(consult);
//                // 拷贝图片
//                if (StringUtils.isNotEmpty(content)) {
//                    if (type == 3) {
//                        // 语音
//                        content = CommonUtil.copyTempVoice(content);
//                    } else if (type == 2) {
//                        // 图片
//                        content = CommonUtil.copyTempImage(content);
//                    }
//                }
//                // 设置回复内容
//                log.setContent(content);
//                log.setDel("1");
//                // 设置回复医生标识
//                log.setDoctor(doctor.getCode());
//                // 设置医生姓名
//                log.setDoctorName(doctor.getName());
//                // 设置医生头像
//                log.setPhoto(doctor.getPhoto());
//                // 设置咨询类型为医生回复
//                log.setType(1);
//                // 设置记录类型
//                log.setChatType(type);
//                // 保存医生回复内容
//                log = consultTeamService.reply(log, patient, getUID(), log.getType());
//                if (log == null) {
//                    return error(-1, "回复失败!");
//                } else {
//                    // 推送消息给患者
//                    // 推送消息给微信端
//                    ConsultTeamDo ct = consultTeamService.findByCode(consult);
//                    Patient p = patientService.findByCode(patient);
//                    if (ct != null && p != null && StringUtils.isNotEmpty(p.getOpenid())) {
//                        JSONObject json = new JSONObject();
//                        json.put("first", p.getName() + ",您好!\n您的健康咨询有新的回复");
//                        json.put("toUser", p.getCode());
//                        String symp = ct.getSymptoms();
//                        json.put("consultcontent", StringUtils.isNotEmpty(symp) && symp.length() > 50 ? (symp.substring(0, 50) + "...") : content);
//                        String replycontent = content.length() > 50 ? content.substring(0, 50) + "..." : content;
//                        if (type == 2) {
//                            replycontent = "[图片]";
//                        } else if (type == 3) {
//                            replycontent = "[语音]";
//                        }
//                        json.put("consult", consult);
//                        json.put("replycontent", replycontent);
//                        json.put("doctorName", doctor.getName());
//                        json.put("remark", "医生已为您提供问诊方案");
//                        // PushMsgTask.getInstance().putWxMsg(getAccessToken(), 3, p.getOpenid(), p.getName(), json);
//                    }
//                    if (type == 2) {
//                        return write(200, "回复成功!", "data", content);
//                    }
//                    return success("回复成功!");
//                }
//            }
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "回复失败!");
//        }
//    }
//
//    /**
//     * 查询医生的总咨询次数和今日咨询次数
//     *
//     * @param doctorCode
//     * @return
//     */
//    @ApiOperation("查询医生的总咨询次数和今日咨询次数")
//    @RequestMapping(value = "getConsultCount", method = RequestMethod.POST)
//    public String getAllCount(@RequestParam(required = true) String doctorCode) {
//        try {
//            JSONObject json = new JSONObject();
//            Map<String, Long> counts = consultTeamService.getAllCount(doctorCode);
//
//            json.put("all", counts.get("all"));
//            json.put("today", counts.get("today"));
//            return json.toString();
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 查询患者的服务数目
//     *
//     * @return
//     */
//    @ApiOperation("查询患者的服务数目")
//    @RequestMapping(value = "getPatientServicNum", method = RequestMethod.POST)
//    public String getPatientServicNum(String patientCode) {
//        try {
//            JSONObject json = new JSONObject();
//            //统计咨询数目
//            Integer allSize1 = consultTeamService.findByDoctorSize(patientCode, getUID());
//            //查询健康指导
//            Integer allSize2 = patientHealthGuidanceService.findGuidanceByPatient(patientCode, getUID());
//            json.put("consult", allSize1);
//            json.put("guide", allSize2);
//            //json.put("today", counts.get("today"));
//            return json.toString();
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 根据医生code和和患者code判断是否有存在进行中的咨询
//     *
//     * @param patientCode 多个患者 逗号分隔
//     * @param doctor
//     * @return 只返回存在咨询的患者的code
//     */
//    @ApiOperation("根据医生code和和患者code判断是否有存在进行中的咨询")
//    @RequestMapping(value = "getConsultByPatientAndDoctor", method = RequestMethod.POST)
//    public String getConsultByPatientAndDoctor(String patientCode, String doctor) {
//        try {
//            JSONArray json = new JSONArray();
//            String[] patients = patientCode.split(",");
//            //查询医生未结束居民列表
//            List<String> list = consultTeamService.getConsultListByPatientAndDoctor(doctor);
//            for (int i = 0; i < patients.length; i++) {
//                if (list.contains(patients[i])) {
//                    json.put(patients[i]);
//                }
//            }
//            return json.toString();
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 名医咨询添加接口
//     *
//     * @param when       发病时间
//     * @param symptoms   主要症状
//     * @param images     图片URL地址,多图以逗号分隔
//     * @param voice      语音URL地址
//     * @param doctorCode 名医的code
//     * @return
//     */
//    @ApiOperation("名医咨询添加接口")
//    @RequestMapping(value = "famousAdd", method = RequestMethod.POST)
//
//    public String famousAdd(
//            @RequestParam(required = false) String when,
//            String symptoms,
//            @RequestParam(required = false) String doctorCode,
//            @RequestParam(required = false) String images,
//            @RequestParam(required = false) String voice) {
//        try {
//            //判断医生是否是在工作时间
//            JSONObject jo = doctorWorkTimeService.isFamousDoctorWorking(doctorCode);
//            if (!jo.get("status").equals("1")) {
//                return error(-1, jo.get("msg").toString());
//            }
//            if (StringUtils.isEmpty(images)) {
//                images = fetchWxImages();
//                // 将临时图片拷贝到正式存储路径下
//                if (StringUtils.isNotEmpty(images)) {
//                    images = CommonUtil.copyTempImage(images);
//                }
//            }
//
//            if (StringUtils.isNotEmpty(voice)) {
//                voice = fetchWxVoices();
//            }
//            if (StringUtils.isNotEmpty(voice)) {
//                voice = CommonUtil.copyTempVoice(voice);
//            }
//
//            ConsultTeamDo consult = new ConsultTeamDo();
//            // 设置咨询类型:1三师咨询,2家庭医生咨询 6.患者发起名医咨询 7医生发起的名医咨询
//            consult.setType(7);
//            // 设置发病时间
//            consult.setWhen(when);
//            // 设置主要症状
//            consult.setSymptoms(symptoms);
//            // 设置咨询图片URL
//            consult.setImages(images);
//            // 设置咨询语音URL
//            consult.setVoice(voice);
//            consult.setDoctor(doctorCode);//设置专科医生
//            // 保存到数据库
//            JSONObject result = consultTeamService.famousConsult(consult, getUID(), "2", null);
//            // 推送消息给医生
//            pushMsgTask.put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.D_CT_04.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.您有新的名医咨询.name(), consult.getConsult());
//            if (StringUtils.isNotEmpty(images)) {
//                String[] arr = images.split(",");
//                for (String img : arr) {
//                    pushMsgTask.put(consult.getDoctor(), "2", MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.您有新的名医咨询.name(), img);
//                }
//            }
//            return write(200, "创建成功!", "data", result);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
//
//    /**
//     * 查询与某个医生是否存在未结束的咨询
//     *
//     * @param doctor 医生
//     * @return
//     */
//    @ApiOperation("查询与某个医生是否存在未结束的咨询")
//    @RequestMapping(value = "/is_consult_unfinished", method = RequestMethod.POST)
//    public String isExistsUnfinishedConsult(@RequestParam(required = false) String patient,
//                                            @RequestParam(required = false) String type,
//                                            @RequestParam(required = true) String doctor) {
//        try {
//            if ("1".equals(type)) {
//                //专科
//                List<ConsultHelp> helps = consultTeamService.findUnfinishedByPatientAndSpecialist(patient, doctor);
//                if (helps.size() > 0) {
//                    return write(200, "查询成功", "data", helps.get(0).getConsult());
//                } else {
//                    return write(200, "查询成功", "data", "");
//                }
//            }
//            List<ConsultTeamDo> consults = consultTeamService.getUnfinishedConsult(StringUtils.isEmpty(patient) ? getUID() : patient, doctor);
//
//            if (consults != null && consults.size() > 0) {
//                return write(200, "查询成功", "data", consults.get(0).getConsult());
//            } else {
//                return write(200, "查询成功", "data", "");
//            }
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//
//    /**
//     * 查询与某个医生是否存在未结束的咨询
//     *
//     * @param consult 咨询code
//     * @return
//     */
//    @ApiOperation("查询与某个医生是否存在未结束的咨询")
//    @RequestMapping(value = "/consultTeam", method = RequestMethod.POST)
//    public String consult(@RequestParam(required = false) String consult) {
//        try {
//            ConsultTeamDo consultTeam = consultTeamService.findByCode(consult);
//            return write(200, "查询成功", "data", consultTeam);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//
//    /**
//     * 三师咨询转接接口
//     *
//     * @param consult 图咨询标识
//     * @param doctor  转接对象标识 健康管理师转全科是 1个    全科转专科是多个  传多个doctor逗号分隔
//     * @param type    转接对象类型,1三师团队,2指定医生,3工作组团队
//     * @return
//     */
//    @ApiOperation("三师咨询转接接口")
//    @RequestMapping(value = "transfer", method = RequestMethod.POST)
//
//    public String transfer(
//            String consult,
//            String doctor,
//            @RequestParam(required = false) int type) {
//        try {
//            consultTeamService.transfers(getUID(), doctor, consult);
//            return success("转接成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 根据咨询code获取咨询的log
//     *
//     * @param consultCode
//     * @return
//     */
//    @ApiOperation("根据咨询code获取咨询的log")
//    @RequestMapping(value = "getConsultLog", method = RequestMethod.POST)
//    public String getConsultLog(
//            String consultCode) {
//        try {
//            List<ConsultTeamDoLog> consultTeamLogs = consultTeamService.getConsultLog(consultCode);
//            JSONArray ja = new JSONArray();
//            for (ConsultTeamDoLog log : consultTeamLogs) {
//                JSONObject json = new JSONObject();
//                json.put("id", log.getId());
//                // 设置回复内容
//                json.put("content", log.getContent());
//                // 设置回复医生姓名
//                json.put("doctorName", log.getDoctorName());
//                // 设置回复人头像
//                json.put("photo", log.getPhoto());
//                // 设置日志类型
//                json.put("type", log.getType());
//                // 设置记录类型
//                json.put("chatType", log.getChatType());
//                // 设置咨询或回复时间
//                json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
//                ja.put(json);
//            }
//            return write(200, "查询成功", "data", ja);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 医生求助添加接口
//     *
//     * @param when       发病时间
//     * @param symptoms   主要症状
//     * @param groupCode  从哪个讨论组发起的求助
//     * @param images     图片URL地址,多图以逗号分隔
//     * @param voice      语音URL地址
//     * @param doctorCode 名医的code
//     * @return
//     */
//    @ApiOperation("医生求助添加接口")
//    @RequestMapping(value = "forHelpAdd", method = RequestMethod.POST)
//
//    public String forHelpAdd(
//            @RequestParam(required = false) String when,
//            String symptoms,
//            @RequestParam(required = false) String oldConsultCode,
//            @RequestParam(required = false) String groupCode,
//            @RequestParam(required = false) String doctorCode,
//            @RequestParam(required = false) String images,
//            @RequestParam(required = false) String voice) {
//        try {
//            if (StringUtils.isEmpty(images)) {
//                images = fetchWxImages();
//                // 将临时图片拷贝到正式存储路径下
//                if (StringUtils.isNotEmpty(images)) {
//                    images = CommonUtil.copyTempImage(images);
//                }
//            }
//
//            if (StringUtils.isEmpty(voice)) {
//                voice = fetchWxVoices();
//            }
//            if (StringUtils.isNotEmpty(voice)) {
//                voice = CommonUtil.copyTempVoice(voice);
//            }
//
//            ConsultTeamDo consult = new ConsultTeamDo();
//            // 设置咨询类型:1三师咨询,2家庭医生咨询 6.患者发起名医咨询 7医生发起的名医咨询 10医生发起的求助
//            consult.setType(10);
//            // 设置来源(从哪个讨论组发起的求助)
//            consult.setTeam(groupCode);
//            // 设置发病时间
//            consult.setWhen(when);
//            // 设置主要症状
//            consult.setSymptoms(symptoms);
//            // 设置咨询图片URL
//            consult.setImages(images);
//            // 设置咨询语音URL
//            consult.setVoice(voice);
//
//            consult.setDoctor(doctorCode);//设置专科医生
//            // 保存到数据库
//            if (consultTeamService.isCommonTeam(doctorCode, getUID())) {
//                consultTeamService.sendForHelpMsg(consult, getUID(), oldConsultCode);
//            } else {
//                consultTeamService.addForHelpTeamConsult(consult, getUID(), oldConsultCode);
//            }
//            return success("提交成功");
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
//
//    @RequestMapping(value = "hasUnfinished", method = RequestMethod.POST)
//    public String hasUnfinished(String doctorCode) {
//        try {
//            String curDoc = getUID();
//            JSONObject json = new JSONObject();
//            if (consultTeamService.isCommonTeam(doctorCode, curDoc)) {
//                json.put("isCommonTeam", 1);
//                return write(200, "查询成功", "data", json);
//            }
//            List<ConsultTeamDo> ls = consultTeamService.hasUnfinished(doctorCode, curDoc);
//            if (ls != null && ls.size() > 0) {
//                ConsultTeamDo ct = ls.get(0);
//                json.put("consult", ct.getConsult());
//                //是否是医生求助医生
//                if (ct.getType() == 10) {
//                    //取出原有咨询求助返回原咨询的患者
//                    ConsultTeamDo consultTeam = consultTeamService.findByConsultCode(ct.getTeam());
//                    Patient patient = patientService.findByCode(consultTeam.getPatient());
//                    json.put("zxGroupCode", consultTeam.getPatient() + "_" + consultTeam.getTeam() + "_" + consultTeam.getType());
//                    json.put("from", ct.getPatient());
//                    json.put("patient_name", patient.getName());
//                }
//            }
//            return write(200, "查询成功", "data", json);
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 该咨询求助过的医生列表
//     *
//     * @param consult 关联的上一个咨询
//     * @return
//     */
//    @ApiOperation("该咨询求助过的医生列表")
//    @RequestMapping(value = "forHelpDocs", method = RequestMethod.POST)
//    public String forHelpDocs(String consult) {
//        try {
//            List<String> ls = consultTeamService.findByTeam(consult);
//            JSONObject json = new JSONObject();
//            if (ls != null) {
//                for (String o : ls) {
//                    json.put(o, 1);
//                }
//            }
//            return write(200, "查询成功", "data", json);
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
//
//    @RequestMapping(value = "getConsult")
//    public String getConsult(String consult) {
@ -1126,73 +339,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//        }
//    }
//
//    @RequestMapping(value = "seekHelp", method = RequestMethod.POST)
//
//    public String seekHelp(
//            @RequestParam(required = true) String symptoms,
//            @RequestParam(required = false) String oldConsultCode,
//            @RequestParam(required = false) String doctorCode,
//            @RequestParam(required = false) String images,
//            @RequestParam(required = true) Integer isSend) {
//        try {
//            if (StringUtils.isEmpty(images)) {
//                images = fetchWxImages();
//                // 将临时图片拷贝到正式存储路径下
//                if (StringUtils.isNotEmpty(images)) {
//                    images = CommonUtil.copyTempImage(images);
//                }
//            }
//            ConsultTeamDo consult = new ConsultTeamDo();
//            // 设置咨询类型:1三师咨询,2家庭医生咨询 6.患者发起名医咨询 7医生发起的名医咨询 10医生发起的求助
//            consult.setType(10);
//            // 设置主要症状
//            consult.setSymptoms(symptoms);
//            // 设置咨询图片URL
//            consult.setImages(images);
//
//            consult.setDoctor(doctorCode);//设置专科医生
//            // 保存到数据库
//            if (consultTeamService.isCommonTeam(doctorCode, getUID())) {
//                consultTeamService.addSeekHelpTeam(consult, getUID(), oldConsultCode, isSend);
//            } else {
//                consultTeamService.addSeekHelpOtherTeam(consult, getUID(), oldConsultCode, isSend);
//            }
//            return success("提交成功");
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
//
//
//    /**
//     * 结束咨询接口
//     *
//     * @param consult 咨询标识
//     * @return
//     */
//    @ApiOperation("结束咨询接口")
//    @RequestMapping(value = "finish_consult", method = {RequestMethod.GET, RequestMethod.POST})
//
//    public String finishConsult(@RequestParam(required = false) String consult) {
//        try {
//            int flag = consultTeamService.finishConsult(consult, getUID(), 2);
//            if (flag > 0) {
//                return success("咨询已关闭");
//            } else if (flag == -1) {
//                return error(-1, "该咨询已经关闭,不需重复关闭!");
//            } else if (flag == -2) {
//                return error(-1, "续方未审核,不能结束续方咨询!");
//            } else {
//                return error(-1, "关闭失败!");
//            }
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "关闭失败!");
//        }
//    }
//
//
//    /**
@ -1219,156 +365,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//        }
//    }
//
//    /*********************************************续方咨询**************************************************************/
//
//    @RequestMapping(value = "prescriptionDetail", method = RequestMethod.GET)
//    @ApiOperation("获取续方信息")
//    public String prescriptionDetail(@ApiParam(name = "consult", value = "咨询code", defaultValue = "1")
//                                     @RequestParam(value = "consult", required = true) String consult) {
//        try {
//            JSONObject json = new JSONObject();
//
//            Consult consult1 = consultDao.findByCode(consult);
//            String prescriptionCode = consult1.getRelationCode();
//            Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
//            json.put("status", prescription.getStatus());//状态 (-1 审核不通过 , 0 审核中, 10 审核通过/待支付 ,21支付失败  20 配药中/支付成功, 21 等待领药 ,30 配送中 ,100配送成功/已完成)
//            json.put("prescriptionDt", prescriptionDiagnosisService.getPrescriptionDiagnosis(prescriptionCode));//续方疾病类型
//            json.put("prescriptionInfo", prescriptionDiagnosisService.getPrescriptionInfo(prescriptionCode));//续方药品信息
//            json.put("followup", followUpService.getFollowupByPrescriptionCode(prescriptionCode));//续方关联的随访记录
//
//            //服务类型
//            List<SignFamilyServer> list = signFamilyServerDao.findBySignCodeAndType(consult1.getSignCode());
//            JSONArray jsonArray = new JSONArray();
//            if (list != null && list.size() > 0) {
//                for (SignFamilyServer server : list) {
//                    JSONObject jsonObject = new JSONObject();
//                    jsonObject.put("serverType", server.getServerType());
//                    jsonObject.put("serverTypeName", server.getServerTypeName());
//                    jsonArray.put(jsonObject);
//                }
//            }
//            json.put("signFamilyServer", jsonArray);
//            json.put("symptoms", consult1.getSymptoms());//咨询类型--- 1高血压,2糖尿病
//            json.put("jwCode", prescription.getJwCode());//基位处方code
//            json.put("code", prescription.getCode());//续方code
//            json.put("viewJiancha", prescription.getViewJiancha());//检查
//            json.put("viewTizhen", prescription.getViewTizhen());//体征
//            json.put("viewChufang", prescription.getViewChufang());//处方
//            json.put("viewXufang", prescription.getViewXufang());//续方
//            json.put("viewWenjuan", prescription.getViewWenjuan());//问卷
//            json.put("viewSuifang", prescription.getViewSuifang());//随访
//
//            return write(200, "查询成功!", "data", json);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "addPrescriptionBloodStatusConsult", method = RequestMethod.POST)
//
//    @ApiOperation("续方咨询-医生发送血糖血压快捷回复咨询")
//    public String addPrescriptionBloodStatusConsult(
//            @ApiParam(name = "prescriptionCode", value = "处方code", defaultValue = "")
//            @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode,
//            @ApiParam(name = "type", value = "类型(1血压,2血糖)", defaultValue = "")
//            @RequestParam(value = "type", required = true) String type,
//            @ApiParam(name = "followupid", value = "随访记录ID", defaultValue = "")
//            @RequestParam(value = "followupid", required = true) String followupid) {
//        try {
//            consultTeamService.addPrescriptionBloodStatusConsult(prescriptionCode, type, followupid);
//            return write(200, "添加成功!");
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "addPrescriptionFollowupContentConsult", method = RequestMethod.POST)
//
//    @ApiOperation("续方咨询-医生发送问卷快捷回复咨询")
//    public String addPrescriptionFollowupContentConsult(
//            @ApiParam(name = "prescriptionCode", value = "处方code", defaultValue = "")
//            @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode,
//            @ApiParam(name = "type", value = "类型(1症状,2体征及生活方式)", defaultValue = "")
//            @RequestParam(value = "type", required = true) String type,
//            @ApiParam(name = "followupid", value = "随访记录ID", defaultValue = "")
//            @RequestParam(value = "followupid", required = true) String followupid) {
//        try {
//            consultTeamService.addPrescriptionFollowupContentConsult(prescriptionCode, type, followupid);
//            return write(200, "添加成功!");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "getSessionId", method = RequestMethod.GET)
//    @ApiOperation("pcim-获取居民的sessionId")
//    public String getSessionId(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
//                               @RequestParam(value = "patient", required = true) String patient) {
//        try {
//            com.alibaba.fastjson.JSONObject re = consultTeamService.getSessionId(patient);
//            return write(200, "获取成功!", "data", re);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "sendBusinessCard", method = RequestMethod.POST)
//    @ApiOperation("发送居民的名片")
//
//    public String sendBusinessCard(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
//                                   @RequestParam(value = "patient", required = true) String patient,
//                                   @ApiParam(name = "sessionId", value = "会话id", defaultValue = "")
//                                   @RequestParam(value = "sessionId", required = true) String sessionId,
//                                   @ApiParam(name = "businessType", value = "businessType", defaultValue = "1")
//                                   @RequestParam(value = "businessType", required = true) String businessType) {
//        try {
//            String doctorCode = getUID();
//            Doctor doctor = doctorService.findDoctorByCode(doctorCode);
//
//            Patient p = patientService.findByCode(patient);
//            com.alibaba.fastjson.JSONObject content = new com.alibaba.fastjson.JSONObject();
//            content.put("name", p.getName());
//            content.put("patient", patient);
//            content.put("photo", p.getPhoto());
//            content.put("age", IdCardUtil.getAgeByIdcardOrBirthday(p.getIdcard(), p.getBirthday()));
//            content.put("sex", IdCardUtil.getSexForIdcard_new(p.getIdcard()));
//            SignFamily signFamily = signFamilyDao.findByPatient(patient);
//            if (signFamily != null) {
//                content.put("hospitalName", signFamily.getHospitalName());
//            }
//            imUtill.sendImMsg(doctorCode, doctor.getName(), sessionId, ImUtill.ContentType.personalCard.getValue(), content.toString(), businessType);
//            return success("发送成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "messageForward", method = RequestMethod.POST)
//    @ApiOperation("请求转发消息")
//    public String messageForward(@ApiParam(name = "senderId", value = "发送者id", defaultValue = "")
//                                 @RequestParam(value = "senderId", required = true) String senderId,
//                                 @ApiParam(name = "senderName", value = "发送者姓名", defaultValue = "")
//                                 @RequestParam(value = "senderName", required = true) String senderName,
//                                 @ApiParam(name = "sessionId", value = "会话id", defaultValue = "")
//                                 @RequestParam(value = "sessionId", required = true) String sessionId,
//                                 @ApiParam(name = "content", value = "会话内容", defaultValue = "")
//                                 @RequestParam(value = "content", required = true) String content,
//                                 @ApiParam(name = "title", value = "会话标题", defaultValue = "")
//                                 @RequestParam(value = "title", required = true) String title,
//                                 @ApiParam(name = "sessionType", value = "原会话的会话类型", defaultValue = "")
//                                 @RequestParam(value = "sessionType", required = true) String sessionType,
//                                 @ApiParam(name = "businessType", value = "businessType", defaultValue = "1")
//                                 @RequestParam(value = "businessType", required = true) String businessType) {
//        try {
//            String message = consultTeamService.getMessageById(sessionType, content, title);
//            imUtill.sendImMsg(senderId, senderName, sessionId, ImUtill.ContentType.messageForward.getValue(), message, businessType);
//            return success("发送成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "examinationDetail", method = RequestMethod.GET)
//    @ApiOperation("获取在线复诊信息")
@ -1410,53 +406,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//        }
//    }
//
//    @RequestMapping(value = "inviteDoctor", method = RequestMethod.POST)
//    @ApiOperation("邀请医生回复居民问题")
//
//    public String inviteDoctor(@ApiParam(name = "sessionid", value = "会话ID")
//                               @RequestParam(value = "sessionid", required = true) String sessionid,
//                               @ApiParam(name = "doctor", value = "被邀请人")
//                               @RequestParam(value = "doctor", required = true) String doctor,
//                               @ApiParam(name = "topic", value = "咨询id")
//                               @RequestParam(value = "topic", required = true) String topic) {
//        try {
//            String uid = getUID();
//            imUtill.updateParticipant(sessionid, doctor, null);
//            //设置邀请消息
//            Doctor from = doctorDao.findByCode(uid);
//            Doctor d = doctorDao.findByCode(doctor);
//            String content = "已邀请" + d.getName() + "医生为您服务,请耐心等待";
//            imUtill.sendTopicIM(from.getCode(), from.getName(), topic, "1", content, null);
//            //发送邀请医生提醒消息
////            if(StringUtils.isNotEmpty(d.getOpenid())){
////                String first = from.getName()+"医生邀请您,为";
////                doctorAssistantUtil.sendWXTemplate(1,d.getOpenid(),d.getCid(),"咨询邀请回复","","");
////            }
//            return write(200, "操作成功!");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "askSpecialist", method = RequestMethod.POST)
//    @ApiOperation("邀请专科-回复居民咨询")
//
//    public String askSpecialist(@ApiParam(name = "sessionid", value = "会话ID")
//                                @RequestParam(value = "sessionid", required = true) String sessionid,
//                                @ApiParam(name = "doctor", value = "被邀请人")
//                                @RequestParam(value = "doctor", required = true) String doctor,
//                                @ApiParam(name = "topic", value = "咨询id")
//                                @RequestParam(value = "topic", required = true) String topic) {
//        try {
//            consultTeamService.askSpecialist(topic, sessionid, getUID(), doctor);
//            return write(200, "操作成功!");
//        } catch (ServiceException se) {
//            return error(-1, se.getMessage());
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 家庭医生发起康复咨询
//     *
@ -1529,27 +478,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//            } else if (res == -3) {
//                return error(-1, "还有咨询未结束,不允许再次提交咨询!");
//            }
//            Boolean flag = messageService.getMessageNoticeSettingByMessageType(doctorCode, "1", MessageNoticeSetting.MessageTypeEnum.imSwitch.getValue());
//            if (flag) {
//                pushMsgTask.put(specialDoctorCode, MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.D_CT_01.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.指定咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.您有新的指定咨询.name(), consult.getConsult());
//                Doctor doctor = doctorDao.findByCode(specialDoctorCode);
//                if (doctor != null && StringUtils.isNotEmpty(doctor.getOpenid())) {
//                    String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
//                    List<NameValuePair> params = new ArrayList<>();
//                    params.add(new BasicNameValuePair("type", "4"));
//                    params.add(new BasicNameValuePair("openId", doctor.getOpenid()));
//                    params.add(new BasicNameValuePair("url", targetUrl));
//                    params.add(new BasicNameValuePair("first", doctor.getName() + "医生您好,有患者向您发起咨询"));
//                    params.add(new BasicNameValuePair("remark", "【" + consult.getSymptoms() + "】\r\n请进入手机APP查看"));
//                    String sex = consult.getSex() == 1 ? "男" : "女";
//                    String keywords = consult.getName() + "," + sex;
//                    params.add(new BasicNameValuePair("keywords", keywords));
//
//                    httpClientUtil.post(url, params, "UTF-8");
//                }
//            }
////                }
////            }
//
//            BusinessLogs.info(BusinessLogs.BusinessType.consult, getRepUID(), getUID(), new JSONObject(consult));
//            return write(200, "提交成功", "data", consult);
@ -1560,49 +488,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//        }
//    }
//
//    @RequestMapping(value = "getKangFuConsultList", method = RequestMethod.GET)
//    @ApiOperation("获取续方咨询列表")
//    public String getKangFuConsultList(@ApiParam(name = "title", value = "咨询标题") @RequestParam(required = false) String title,
//                                       @ApiParam(name = "patient", value = "居民CODE") @RequestParam(required = false) String patient,
//                                       @ApiParam(name = "id", value = "第几页") @RequestParam(required = true) long id,
//                                       @ApiParam(name = "pagesize", value = "页面大小") @RequestParam(required = true) int pagesize) {
//        try {
//            JSONArray array = new JSONArray();
//            Page<Object> data = consultTeamService.findConsultRecordByType(patient, id, pagesize, 18, title);//18表示康复咨询
//            Patient patientobj = patientService.findByCode(patient);
//            if (data != null) {
//                for (Object consult : data.getContent()) {
//                    if (consult == null) {
//                        continue;
//                    }
//                    Object[] result = (Object[]) consult;
//                    JSONObject json = new JSONObject();
//                    json.put("id", result[0]);
//                    // 设置咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈,8 续方咨询  18康复咨询
//                    json.put("type", result[1]);
//                    // 设置咨询标识
//                    json.put("code", result[2]);
//                    // 设置显示标题
//                    json.put("title", result[3]);
//                    json.put("patientName", patientobj.getName());
//                    json.put("patientPhoto", patientobj.getPhoto());
//                    // 设置主诉
//                    json.put("symptoms", result[4]);
//                    // 咨询状态
//                    json.put("status", result[6]);
//                    // 设置咨询日期
//                    json.put("czrq", DateUtil.dateToStrLong((Date) result[5]));
//                    // 咨询状态
//                    json.put("doctorCode", result[7]);
//                    json.put("evaluate", result[8]);
//                    array.put(json);
//                }
//            }
//            return write(200, "查询成功!", "list", array);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "/getDoctorConsultSessions", method = RequestMethod.GET)
//    @ApiOperation("获取医生咨询列表,带专家咨询")

+ 15 - 3040
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultTeamService.java

@ -1,8 +1,6 @@
package com.yihu.jw.hospital.module.consult.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.im.ConsultTeamLogDo;
@ -12,32 +10,26 @@ import com.yihu.jw.entity.wechat.WechatTemplateConfig;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorServiceOrderDao;
import com.yihu.jw.hospital.module.door.service.WlyyDoorServiceOrderService;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.im.dao.ConsultTeamDoctorDao;
import com.yihu.jw.im.dao.ConsultTeamLogDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.order.dao.ConsultTeamOrderDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Clock;
import java.text.DecimalFormat;
import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
@ -52,128 +44,35 @@ public class ConsultTeamService extends ConsultService {
    private final Logger logger = LoggerFactory.getLogger(ConsultTeamService.class);
    private final Clock clock = Clock.DEFAULT;
    @Autowired
    private ConsultTeamOrderDao consultTeamDao;
    // 咨询详细记录
    @Autowired
    private ConsultTeamLogDao consultTeamLogDao;
    @Autowired
    private ConsultTeamDoctorDao consultTeamDoctorDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private BasePatientDao patientDao;
//    @Autowired
//    private PrescriptionLogService prescriptionLogService;
//    @Autowired
//    private PrescriptionInfoDao prescriptionInfoDao;
//    @Autowired
//    private PrescriptionDiagnosisDao prescriptionDiagnosisDao;
//    @Autowired
//    private WeiXinAccessTokenUtils accessTokenUtils;
    @Autowired
    private BasePatientService patientService;
//    @Autowired
//    private MessageService messageService;
//
//    @Autowired
//    private PrescriptionExpressageDao expressageDao;
//    @Autowired
//    private HospitalDao hospitalDao;
    @Autowired
    private WlyyDoorServiceOrderDao wlyyDoorServiceOrderDao;
    @Autowired
    private WlyyDoorServiceOrderService wlyyDoorServiceOrderService;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private HttpClientUtil httpClientUtil;
    Map<Integer, String> relations = new HashMap<>();
    @Value("${im.im_list_get}")
    private String im_list_get;
    @Value("${im.data_base_name}")
    private String imdb;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private BaseDoctorInfoService doctorService;
//    @Autowired
//    private TalkGroupService talkGroupService;
//    @Autowired
//    private PatientDeviceDao patientDeviceDao;
//    @Autowired
//    private SignFamilyDao signFamilyDao;
//    @Autowired
//    private PatientHealthGuidanceService guidanceService;
//    @Autowired
//    private PatientFamilyMemberDao familyMemberDao;
//    @Autowired
//    private HealthEduArticleService healthEduArticleService;
//    @Autowired
//    private CsrfConstant csrfConstant;
//    @Autowired
//    private ConsultHelpDao consultHelpDao;
//    @Autowired
//    private DoctorHelpDao doctorHelpDao;
//    @Autowired
//    private DoctorAssistantUtil doctorAssistantUtil;
//    @Autowired
//    private PrescriptionExplainDao prescriptionExplainDao;
//    @Autowired
//    private ExaminationDao examinationDao;
//    @Autowired
//    private DoctorAdminTeamMemberDao doctorAdminTeamMemberDao;
//    @Autowired
//    private SpecialDiseaseMessagesDao specialDiseaseMessagesDao;
//    @Autowired
//    private PrescriptionFollowupContentService prescriptionFollowupContentService;
//    @Autowired
//    private SystemDictDao systemDictDao;
//    @Autowired
//    private FollowUpDao followupDao;
//    @Autowired
//    private PrescriptionReviewedDao prescriptionReviewedDao;
//    @Autowired
//    private JwPrescriptionService jwPrescriptionService;
//    @Autowired
//    private PrescriptionInfoService prescriptionInfoService;
//    @Autowired
//    private PresModeAdapter presModeAdapter;
//    @Autowired
//    private ZyDictService zyDictService;
//    @Autowired
//    private WeiXinOpenIdUtils weiXinOpenIdUtils;
//    @Autowired
//    private MessageDao messageDao;
    /**
     * 添加上门服务咨询
     */
@ -233,7 +132,6 @@ public class ConsultTeamService extends ConsultService {
         * 创建议题
         */
        JSONObject imResponseJson = imUtill.createTopics(sessionId, consult.getId(), content, participants, messages, ImUtil.SESSION_TYPE_ONDOOR_NURSING);
        System.out.println("创建议题成功了!!!!!!!!!!!!!!!!");
        if (imResponseJson == null || imResponseJson.getString("status").equals("-1")) {
            String failMsg = "发起服务咨询时:IM" + imResponseJson.getString("message");
            throw new Exception(failMsg);
@ -241,292 +139,14 @@ public class ConsultTeamService extends ConsultService {
        if (imResponseJson != null && imResponseJson.get("start_msg_id") != null) {
            consultTeam.setStartMsgId(imResponseJson.get("start_msg_id").toString());
        }
        System.out.println("准备保存consultTeam和consult");
        consultTeamDao.save(consultTeam);
        consultDao.save(consult);
        System.out.println("保存的consultTeam==>"+ JSON.toJSONString(consultTeam));
        System.out.println("保存的consult==>"+ JSON.toJSONString(consult));
        System.out.println("保存consultTeam和consult成功");
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, consultTeam);
        return result;
    }
//    @PostConstruct
//    public void init() {
//        relations.put(0, "其他");
//        relations.put(1, "父亲");
//        relations.put(2, "母亲");
//        relations.put(3, "老公");
//        relations.put(4, "老婆");
//        relations.put(5, "儿子");
//        relations.put(6, "女儿");
//        relations.put(7, "未知");
//        csrfConstant.init();
//    }
    /**
     * 查找邀请医生列表
     *
     * @param consultCode 咨询code
     * @param type        1家签医生 2社区邀约 3专病防治中心
     * @param hospital    医院code
     * @param deptName    科室名称
     * @param disease     专病类型
     * @param name        医生、机构、科室
     * @param sortBy      排序 不传默认综合
     *                    综合:专家标签>被邀请次数>回复率 > 平均响应时长>用户评价;
     *                    1被邀请次数:被邀请次数>回复率 > 平均响应时长>用户评价;
     *                    2回复率:回复率 > 被邀请次数>平均响应时长>用户评价;
     *                    3平均响应时长:平均响应时长>被邀请次数>回复率>用户评价 ;
     *                    4用户评价:用户评价>被邀请次数>回复率 > 平均响应时长;
     * @param size
     */
//    public PageEnvelop findHelpDoctorPage(String uid, String consultCode, String type, String hospital, String sortBy,
//                                          String deptName, String disease, String name, Integer page, Integer size) {
//        Consult consult = consultDao.findByCode(consultCode);
//        Doctor d = doctorDao.findByCode(uid);
//        boolean flag = true;
//        if (d != null) {
//            if (Constant.testHospital.equals(d.getHospital())) {
//                flag = false;
//            }
//        }
//        String patient = consult.getPatient();
//        String field = "";
//        if ("3".equals(type)) {
//            field = ",a.special_code specialCode,a.special_name specialName";
//        }
//        String sql = "SELECT DISTINCT d.code,d.name,d.photo,d.job_name jobName,d.dept_name deptName,d.hospital_name hospitalName " +
//                field + ",ifnull(h.reply_rate,'0%') replyRate " +
//                ",ifnull(h.average_response,0) averageResponse,ifnull(h.evaluate_score,80) evaluateScore " +
//                ",ifnull(h.invite_num,0) inviteNum,ifnull(h.invited_num,0) invitedNum " +
//                ",if(sf.id is null,0,1) 'signFlag',if(p.id is null,0,1) 'zbFlag' ";
//        String countSql = "select count(DISTINCT d.code) ";
//        String filter = "";
//        if ("3".equals(type)) {
//            filter = " from wlyy_admin_team a,wlyy_admin_team_member m,wlyy_doctor d " +
//                    " LEFT JOIN wlyy_doctor_help h on d.code = h.doctor " +
//                    " LEFT JOIN wlyy_sign_family sf on sf.patient='" + patient + "' and sf.`status`>=0 and sf.specialist=d.code " +
//                    " LEFT JOIN wlyy_patient_rehabilitation_plan p on p.patient = '" + patient + "' and p.create_user=d.code " +
//                    " WHERE a.accept_type = 0 and a.available =1 and a.special_code is not null " +
//                    " and a.id = m.team_id and m.available=1 and m.doctor_code=d.code and d.`status`=1 ";
//            if (StringUtils.isNotBlank(disease)) {
//                filter += " and a.special_code='" + disease + "' ";
//            }
//        } else {
//            filter = "from wlyy_hospital_invite_specialist s,wlyy_doctor d " +
//                    "LEFT JOIN wlyy_doctor_help h on d.code = h.doctor " +
//                    " LEFT JOIN wlyy_sign_family sf on sf.patient='" + patient + "' and sf.`status`>=0 and sf.specialist=d.code " +
//                    " LEFT JOIN wlyy_patient_rehabilitation_plan p on p.patient = '" + patient + "' and p.create_user=d.code " +
//                    " WHERE s.specialist=d.code and d.`status`=1 and s.type = '" + type + "' ";
//            if ("2".equals(type) && d != null) {
//                filter += " and s.hospital='" + d.getHospital() + "' ";
//            }
//        }
//        //排除医生自己
//        filter += " and d.code!='" + uid + "' ";
//        if (StringUtils.isNotBlank(hospital)) {
//            filter += " and d.hospital='" + hospital + "' ";
//        }
//        if (StringUtils.isNotBlank(deptName)) {
//            filter += " and d.dept_name='" + deptName + "' ";
//        }
//        if (StringUtils.isNotBlank(name)) {
//            filter += " and (d.name like '%" + name + "%' or d.dept_name like '%" + name + "%' or d.hospital_name like '%" + name + "%')";
//        }
//
//        if (flag) {
//            filter += " and d.hospital !='" + Constant.testHospital + "' ";
//        }
//        String orderBy = "";
//        if ("1".equals(sortBy)) {
//            //被邀请次数:被邀请次数>回复率 > 平均响应时长>用户评价;
//            orderBy = " order by invitedNum desc,replyRate desc,averageResponse desc,evaluateScore desc ";
//        } else if ("2".equals(sortBy)) {
//            //回复率:回复率 > 被邀请次数>平均响应时长>用户评价;
//            orderBy = " order by replyRate desc,invitedNum desc,averageResponse desc,evaluateScore desc ";
//        } else if ("3".equals(sortBy)) {
//            //平均响应时长:平均响应时长>被邀请次数>回复率>用户评价 ;
//            orderBy = " order by averageResponse desc,invitedNum desc,replyRate desc,evaluateScore desc ";
//        } else if ("4".equals(sortBy)) {
//            //用户评价:用户评价>被邀请次数>回复率 > 平均响应时长;
//            orderBy = " order by evaluateScore desc,invitedNum desc,replyRate desc,averageResponse desc ";
//        } else {
//            //综合:专家标签>被邀请次数>回复率 > 平均响应时长>用户评价;
//            orderBy = " order by signFlag desc,zbFlag desc,invitedNum desc,replyRate desc,averageResponse desc,evaluateScore desc ";
//        }
//
//        orderBy += " limit " + (page - 1) * size + "," + size;
//
//        long count = jdbcTemplate.queryForObject(countSql + filter, Long.class);
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql + filter + orderBy);
//        List<ConsultHelp> consultHelpList = consultHelpDao.findConsult(consultCode);
//        Map<String, String> speMap = consultHelpList.stream().collect(Collectors.toMap(ConsultHelp::getSpecialist, ConsultHelp::getSpecialist));
//        for (Map<String, Object> map : list) {
//            String code = map.get("code") + "";
//            int askFlag = 0;
//            if (speMap.containsKey(code)) {
//                askFlag = 1;
//            }
//            map.put("askFlag", askFlag);
//        }
//        return PageEnvelop.getSuccessListWithPage("获取成功", list, page, size, count);
//    }
    //专科医生获取家庭医生咨询邀请
//    public Envelop findConsultHelpPage(String specialist, String status, String patientName, Integer page, Integer size) {
//        String sql = "select c.*,p.photo,d.dept_name deptName,d.photo doctorPhoto ";
//        String countSql = " select count(c.id) ";
//        String filter = " from wlyy_consult_help c " +
//                " left join wlyy_patient p on c.patient=p.code " +
//                " left join wlyy_doctor d on c.doctor=d.code " +
//                " where c.specialist='" + specialist + "' ";
//        String orderBy = " order by c.id desc limit " + (page - 1) * size + "," + size;
//        if (StringUtils.isNotBlank(status)) {
//            filter += " and c.status = '" + status + "' ";
//        }
//        if (StringUtils.isNotBlank(patientName)) {
//            filter += " and (c.patient_name like '%" + patientName + "%' or d.name like '%" + patientName + "%')";
//        }
//        Long count = jdbcTemplate.queryForObject(countSql + filter, Long.class);
//        List<ConsultHelp> helpList = jdbcTemplate.query(sql + filter + orderBy, new BeanPropertyRowMapper<>(ConsultHelp.class));
//
//        return PageEnvelop.getSuccessListWithPage("获取成功", helpList, page, size, count);
//    }
    //结束咨询修改 邀请的状态
//    public void endConsultHelp(String consultCode) {
//        try {
//            List<ConsultHelp> helps = consultHelpDao.findConsultAndStatus(consultCode);
//            if (helps.size() > 0) {
//                List<ConsultHelp> helpList = new ArrayList<>();
//                for (ConsultHelp help : helps) {
//                    String status = help.getStatus();
//                    String specialist = help.getSpecialist();
//                    if ("0".equals(status)) {
//                        help.setStatus("3");
//                        helpList.add(help);
//                    } else if ("1".equals(status)) {
//                        help.setStatus("2");
//                        DoctorHelp doctorHelp = doctorHelpDao.findByDoctor(specialist);
//                        doctorHelp.setInvitedNum(doctorHelp.getInvitedNum() + 1L);
//                        if (doctorHelp.getInviteNum() == null || doctorHelp.getInviteNum() == 0) {
//                            doctorHelp.setInviteNum(1L);
//                        }
//                        doctorHelp.setReplyRate(getRange(doctorHelp.getInvitedNum(), doctorHelp.getInviteNum()));
//                        doctorHelpDao.save(doctorHelp);
//                        helpList.add(help);
//                    }
//                }
//                if (helpList.size() > 0) {
//                    consultHelpDao.save(helpList);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
    /**
     * 获取2个数的百分比
     *
     * @param first
     * @param second
     * @return
     */
    public String getRange(Long first, Long second) {
        if (second == 0 && first > 0) {
            return "100%";
        } else if (second == 0 && first == 0) {
            return "0%";
        }
        float size = (float) (first * 100) / second;
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数,不足的补0
        String filesize = df.format(size);
        return filesize + "%";
    }
    //邀请专科-回复居民咨询
    @Transactional
//    public synchronized void askSpecialist(String consultCode, String sessionId, String doctorCode, String specialistCode) {
//        List<ConsultHelp> helps = consultHelpDao.findByConsultAndSpecialist(consultCode, specialistCode);
//        if (helps.size() > 0) {
//            throw new ServiceException("请勿重复邀请");
//        }
//        //医生统计表
//        DoctorHelp doctorHelp = doctorHelpDao.findByDoctor(specialistCode);
//        if (doctorHelp == null) {
//            doctorHelp = new DoctorHelp();
//            doctorHelp.setDoctor(specialistCode);
//            doctorHelp.setAverageResponse(0L);
//            doctorHelp.setInviteNum(1L);
//            doctorHelp.setResponseTime(0L);
//            doctorHelp.setReplyRate("0%");
//            doctorHelp.setInvitedNum(0L);
//            doctorHelp.setCreateTime(new Date());
//            doctorHelp.setEvaluateScore(80D);
//            doctorHelp.setReplyNum(1L);
//        } else {
//            doctorHelp.setInviteNum(doctorHelp.getInviteNum() + 1L);
//        }
//        doctorHelpDao.save(doctorHelp);
//        List<ConsultHelp> consultHelpList = consultHelpDao.findConsult(consultCode);
//
//        Consult consult = consultDao.findByCode(consultCode);
//        Doctor doctor = doctorDao.findByCode(doctorCode);
//        Doctor specialist = doctorDao.findByCode(specialistCode);
//        Patient patient = patientDao.findByCode(consult.getPatient());
//        Hospital hospital = hospitalDao.findByCode(doctor.getHospital());
//        SignFamily signFamily = signFamilyDao.findByPatient(consult.getPatient());
//        ConsultHelp help = new ConsultHelp();
//        help.setStatus("0");
//        help.setType(consult.getType() + "");
//        help.setPatientName(patient.getName());
//        help.setCreateTime(new Date());
//        help.setConsult(consultCode);
//        help.setPatient(consult.getPatient());
//        help.setDoctor(doctorCode);
//        help.setDoctorName(doctor.getName());
//        help.setHospital(doctor.getHospital());
//        help.setHospitalName(doctor.getHospitalName());
//        help.setSpecialist(specialistCode);
//        help.setSpecialistDept(specialist.getDept());
//        help.setSpecialistName(specialist.getName());
//        help.setSpecialistHospital(specialist.getHospital());
//        help.setSpecialistHospitalName(specialist.getHospitalName());
//        help.setSpecialistDeptName(specialist.getDeptName());
//        help.setTown(hospital.getTown());
//        help.setSessionId(sessionId);
//        help.setAdminTeamId(signFamily.getAdminTeamId());
//        consultHelpDao.save(help);
//
//
//        imUtill.updateParticipant(sessionId, specialistCode, null);
//        //设置邀请消息
//        //居民端和家庭医生端 家庭医生【姓名】已邀请 专科医生【姓名】进入咨询
//        //专科医生端 家庭医生【姓名】邀请您加入了群聊,群聊参与人还有: {患者姓名}{其他群聊成员}
//        String content1 = "家庭医生[" + doctor.getName() + "]已邀请 专科医生[" + specialist.getName() + "]进入咨询";
//        String doctors = signFamily.getDoctorName();
//        if (StringUtils.isNotBlank(signFamily.getDoctorHealthName()) && !doctors.equals(signFamily.getDoctorHealthName())) {
//            doctors += "," + signFamily.getDoctorHealthName();
//        }
//        for (ConsultHelp consultHelp : consultHelpList) {
//            doctors += "," + consultHelp.getSpecialistName();
//        }
//        String content2 = "家庭医生[" + doctor.getName() + "]邀请您加入了群聊,群聊参与人还有:{" + patient.getName() + "}{" + doctors + "}";
//        imUtill.sendTopicIM(doctor.getCode(), doctor.getName(), consultCode, "46", content1, null);
//        imUtill.sendTopicIM(doctor.getCode(), doctor.getName(), consultCode, "47", content2, null);
//
//        //发送医生助手消息
//        String first = specialist.getName() + "医生您好,您收到来自" + doctor.getHospitalName() + "的" + doctor.getName() + "咨询求助,请访问厦门i健康APP查看。";
//        doctorAssistantUtil.sendWXTemplate(9, specialist.getOpenid(), specialist.getCid(), first, "请及时处理", "咨询求助", specialist.getHospitalName(), specialist.getName());
//
//        messageService.addSpecialistDynamicMessages(patient, specialist, doctor, "咨询求助", null, "3", null);
//    }
    /**
     * 医生主动发送im消息
     */
@ -548,1618 +168,18 @@ public class ConsultTeamService extends ConsultService {
            } else if ("3".equals(contentType)) {
                content = "一条语音消息";
            } else {
                content = "一条消息";
            }
            String url = temp.getUrl() + "&openid=" + p.getOpenid() + "&peerId=" + doctor + "&peerName=" + doctorName;
            json.put("consultcontent", temp.getKeyword1());
            json.put("replycontent", content);
            json.put("doctorName", doctorName);
            json.put("remark", "");
            json.put("url", url);
            pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 3, p.getOpenid(), p.getName(), json);
        }
    }
    /**
     * 处方判断
     */
//    public JSONObject isPrescriptConsult(String patient) {
//        JSONObject json = new JSONObject();
//        SignFamily signFamily = signFamilyDao.findByPatient(patient);
//        if (signFamily == null) {
//            json.put("msg", "您还未签约,不能发起续方咨询");
//            return json;
//        }
//
//        //续方说明
//        List<PrescriptionExplain> list = prescriptionExplainDao.findList();
//        JSONArray ja = new JSONArray();
//        for (PrescriptionExplain explain : list) {
//            ja.put(explain.getContent());
//        }
//
//        Doctor doctor = doctorDao.findByAdminTeamId(signFamily.getAdminTeamId());
//
//        Hospital hospital = hospitalDao.findByCode(signFamily.getHospital());
//
//        json.put("doctor", doctor.getCode());
//        json.put("doctorName", doctor.getName());
//        json.put("adminTeamId", signFamily.getAdminTeamId());
//        json.put("hospital", doctor.getHospital());
//        json.put("hospitalName", doctor.getHospitalName());
//        json.put("hospitalAddress", hospital.getAddress());
//        json.put("prescriptionExplain", ja);
//        return json;
//    }
    /**
     * 查询患者是否还有未结束的三师咨询
     */
//    public boolean exist(String patient, Integer type) throws Exception {
//        String memberCode = null;
//        if (type == 2 || type == 18) {
//            // 咨询家庭医生
//            SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
//            if (sf == null) {
//                throw new ServiceException("不存在家庭签约");
//            }
//            if (StringUtils.isEmpty(sf.getDoctorHealth())) {
//                memberCode = sf.getDoctor();
//            } else {
//                memberCode = sf.getDoctorHealth();
//            }
//
//        }
//
//        int count = consultTeamDao.countByPatient(patient, type, memberCode);
//        return count > 0;
//    }
    /**
     * 查詢醫生網絡諮詢列表
     *
     * @param type     咨询类型:1、咨询我的,2、公共的, 3、参与过的,4、已结束的 5 名医咨询 全部  6 名医咨询 进行中 7 名医咨询 已结束 8名医咨询 待处理 9咨询我的三师 + 家庭 + 名医
     * @param pagesize 每页显示数,默认为10
     */
//    public Page<ConsultTeamDo> findByDoctor(String uid, int type, long id, int pagesize, String patient, String title) {
//        if (id < 0) {
//            id = 0;
//        }
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//        switch (type) {
//            case 0:
//                // 全部
//                return findByDoctorType0(uid, id, patient, pagesize);
//            case 1:
//                // 咨询我的
//                return findByDoctorType1(uid, type, id, pagesize);
//            case 2:
//                // 我感兴趣的
//                return findByDoctorType2(uid, type, id, pagesize);
//            case 3:
//                // 我回复的
//                return findByDoctorType3(uid, id, pagesize);
//            case 4:
//                // 已完成的
//                return findByDoctorType4(uid, id, pagesize);
//            case 5:
//                // 5 名医咨询 全部
//                return findByDoctorType5(uid, id, pagesize, title);
//            case 6:
//                //6 名医咨询 进行中
//                return findByDoctorType6(uid, 0, id, pagesize, title);
//            case 7:
//                //7 名医咨询 已结束
//                return findByDoctorType6(uid, 1, id, pagesize, title);
//            case 8:
//                return findByDoctorType8(uid, id, pagesize, title);
//            case 9:
//                return findByDoctorType9(uid, id, pagesize);
//            case 10:
//                //我咨询的
//                return findByDoctorType10(uid, id, pagesize, title);
//            case 11:
//                //我咨询的 进行中
//                return findByDoctorType11(uid, 0, id, pagesize, title);
//            case 12:
//                //我咨询的 已结束中
//                return findByDoctorType11(uid, 1, id, pagesize, title);
//        }
//        return null;
//    }
//    private Page<ConsultTeamDo> findByDoctorType11(String uid, int status, long id, int pagesize, String title) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, id, title, pageRequest);
//            } else {
//                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, id, pageRequest);
//            } else {
//                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, pageRequest);
//            }
//        }
//    }
//    private Page<ConsultTeamDo> findByDoctorType10(String uid, long id, int pagesize, String title) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findMyFamousDoctorAllList(uid, id, title, pageRequest);
//            } else {
//                return consultTeamDao.findMyFamousDoctorAllList(uid, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findMyFamousDoctorAllList(uid, id, pageRequest);
//            } else {
//                return consultTeamDao.findMyFamousDoctorAllList(uid, pageRequest);
//            }
//        }
//    }
//    private Page<ConsultTeamDo> findByDoctorType8(String uid, long id, int pagesize, String title) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        sort.and(new Sort(Direction.DESC, "czrq"));
//        sort.and(new Sort(Direction.DESC, "doctorRead"));
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorUnReplyReadList(uid, id, title, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorUnReplyReadList(uid, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorUnReplyReadNoTitleList(uid, id, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorUnReplyReadNoTitleList(uid, pageRequest);
//            }
//        }
//    }
//    private Page<ConsultTeamDo> findByDoctorType5(String uid, long id, int pagesize, String title) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorAllList(uid, id, title, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorAllList(uid, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorAllList(uid, id, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorAllList(uid, pageRequest);
//            }
//        }
//    }
//    private Page<ConsultTeamDo> findByDoctorType6(String uid, int type, long id, int pagesize, String title) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorDoingList(uid, id, title, type, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorDoingList(uid, title, type, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorDoingList(uid, id, type, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorDoingList(uid, type, pageRequest);
//            }
//        }
//    }
    /**
     * 根据状态获取三师家庭咨询
     *
     * @param status 0未处理或未回复 1已回复 2已结束
     */
//    public Page<ConsultTeamDo> findConsultByDoctor(String doctor, int status, long id, int pagesize) {
//        if (id < 0) {
//            id = 0;
//        }
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//
//        if (status == 0) {
//            return findConsultByDoctorWcl(doctor, id, pagesize);
//        } else if (status == 1) {
//            return findConsultByDoctorIng(doctor, id, pagesize);
//        } else {
//            return findByDoctorType4(doctor, id, pagesize);
//        }
//    }
    /**
     * 获取三师家庭未处理咨询
     */
//    private Page<ConsultTeamDo> findConsultByDoctorWcl(String uid, long id, int pagesize) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        sort.and(new Sort(Direction.DESC, "czrq"));
//        sort.and(new Sort(Direction.DESC, "doctorRead"));
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//
//        if (id > 0) {
//            return consultTeamDao.findDoctorUnReplyReadNoTitleList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorUnReplyReadNoTitleList(uid, pageRequest);
//        }
//    }
    /**
     * 获取三师家庭已回复咨询
     */
//    private Page<ConsultTeamDo> findConsultByDoctorIng(String uid, long id, int pagesize) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//
//        if (id > 0) {
//            return consultTeamDao.findDoctorIngNoTitleList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorIngNoTitleList(uid, pageRequest);
//        }
//    }
    /**
     * 查询全部咨询记录
     */
//    public Page<ConsultTeamDo> findByDoctorType0(String uid, long id, String patient, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isEmpty(patient)) {
//            if (id > 0) {
//                return consultTeamDao.findDoctorList(uid, id, pageRequest);
//            } else {
//                return consultTeamDao.findDoctorList(uid, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findDoctorPatientList(uid, patient, id, pageRequest);
//            } else {
//                return consultTeamDao.findDoctorPatientList(uid, patient, pageRequest);
//            }
//        }
//    }
    /**
     * 指定医生三师咨询列表查询
     *
     * @param uid  医生标识
     * @param type 咨询类型:1、咨询我的,2、公共的, 3、参与过的,4、已结束的
     */
//    public Page<ConsultTeamDo> findByDoctorType1(String uid, int type, long id, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (id > 0) {
//            return consultTeamDao.findDoctorPointList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorPointList(uid, pageRequest);
//        }
//    }
    /**
     * 指定医生三师咨询列表查询
     *
     * @param uid 医生标识
     */
    public Page<ConsultTeamDo> findByDoctorType9(String uid, long id, int pagesize) {
        return null;
    }
    /**
     * 公共三师咨询列表查询
     *
     * @param uid  医生标识
     * @param type 咨询类型:1、咨询我的,2、公共的, 3、参与过的,4、已结束的
     */
//    public Page<ConsultTeamDo> findByDoctorType2(String uid, int type, long id, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//
//        // 设置查询条件
//        Map<String, SearchFilter> filters = new HashMap<>();
//        // 未指定医生
//        filters.put("type", new SearchFilter("type", Operator.EQ, 0));
//        if (id > 0) {
//            filters.put("id", new SearchFilter("id", Operator.LT, id));
//        }
//        // 未回复
//        filters.put("status", new SearchFilter("status", Operator.EQ, 0));
//        // 未作废
//        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//        Specification<ConsultTeamDo> spec = DynamicSpecifications.bySearchFilter(filters.values(), ConsultTeam.class);
//
//        return consultTeamDao.findAll(spec, pageRequest);
//    }
    /**
     * 医生参与过的未结束的三师咨询列表查询
     */
//    public Page<ConsultTeamDo> findByDoctorType3(String uid, long id, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (id > 0) {
//            return consultTeamDao.findDoctorJoinList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorJoinList(uid, pageRequest);
//        }
//    }
    /**
     * 医生参与过的已结束的三师咨询列表查询
     */
//    public Page<ConsultTeamDo> findByDoctorType4(String uid, long id, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (id > 0) {
//            return consultTeamDao.findDoctorFinishList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorFinishList(uid, pageRequest);
//        }
//    }
    /**
     * 网络咨询咨询日志查询
     *
     * @param consult  咨询标识
     * @param pagesize 每页显示数,默认为10
     */
//    public Page<ConsultTeamLog> findLogByConsult(String consult, long id, int pagesize) {
//        if (id < 0) {
//            id = 0;
//        }
//
//        // 设置查询条件
//        Map<String, SearchFilter> filters = new HashMap<>();
//        filters.put("consult", new SearchFilter("consult", Operator.EQ, consult));
//
//        if (id > 0) {
//            if (pagesize > 0)
//                filters.put("id", new SearchFilter("id", Operator.LT, id));
//            else
//                filters.put("id", new SearchFilter("id", Operator.GT, id));
//        }
//        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//        Specification<ConsultTeamLog> spec = DynamicSpecifications.bySearchFilter(filters.values(), ConsultTeamLog.class);
//
//        if (pagesize <= 0) {
//            Page<ConsultTeamLog> p = new PageImpl<>(consultTeamLogDao.findAll(spec));
//            return p;
//        }
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        return consultTeamLogDao.findAll(spec, pageRequest);
//    }
    /**
     * 批量回复
     */
//    public void reply(List<ConsultTeamLogDo> logs, String patient) throws Exception {
//        ConsultTeamDo consultTeam = consultTeamDao.findByConsult(logs.get(0).getConsult());
//        WlyyTalkGroup wlyyTalkGroup = talkGroupService.findConsultTalkGroupByType(logs.get(0).getConsult(), 2);
//        for (ConsultTeamLog log : logs) {
//            reply(log, patient, null, log.getType());
//            //判断当前咨询是否创建讨论租
//            if (wlyyTalkGroup != null) {
//                sendGroupIM(patient, wlyyTalkGroup.getCode(), log.getChatType() + "", log.getContent());
//            } else {
//                //推送给IM
//                sendIM(patient, consultTeam.getDoctor(), log.getChatType() + "", log.getContent());
//            }
//        }
//    }
    /**
     * 查询居民咨询记录
     */
//    public JSONArray findByPatientAndTeam(String patient, Long teamCode, int page, int pageSize) {
//        PageRequest pageRequest = new PageRequest(page, pageSize);
//        BasePatientDO  p = patientDao.findByCode(patient);
//        Page<Object> result = consultDao.findByPatientAll(patient, pageRequest);
//        JSONArray array = new JSONArray();
//
//        for (Object obj : result) {
//            JSONObject consult = new JSONObject();
//            Object[] objArr = (Object[]) obj;
//            consult.put("id", objArr[0]);
//            consult.put("code", objArr[2]);
//            consult.put("type", objArr[1]);
//            consult.put("title", objArr[3]);
//            consult.put("symptoms", objArr[4]);
//            consult.put("czrq", objArr[5]);
//            consult.put("status", objArr[6]);
//            consult.put("adminTeamCode", objArr[7]);
//            consult.put("team", objArr[8]);
//            consult.put("patient", patient);
//            consult.put("patientName", p.getName());
//            consult.put("patientPhoto", p.getPhoto());
//            consult.put("total", result.getTotalElements());
//            array.put(consult);
//        }
//
//        return array;
//    }
    /**
     * 添加咨询记录
     *
     * @param log  日志对象
     * @param type 类型,0问,1回复,2追问,3评价
     */
//    public ConsultTeamLogDo reply(ConsultTeamLogDo log, String patient, String teamOrDoctor, int type) {
//        log.setCzrq(clock.getCurrentDate());
//        // 保存咨询记录
//        ConsultTeamLogDo temp = consultTeamLogDao.save(log);
//        if (temp != null) {
//            // 发送消息
//            if (type == 1) {
//                // 医生回复,给患者发消息
//                // 患者未读数量+1
//                consultTeamDao.increasePatientRead(log.getConsult());
//                // 医生有回复
//                consultTeamDoctorDao.updateReply(log.getConsult(), teamOrDoctor);
//
//                //shenzaixin v1.2.0 推送消息给患者
//                //HttpUtil.sendWeixinWebsocketMsg(patient, "{busiType:'qianyuezixun',msgid:'" + log.getId() + "'}");
//            } else if (type == 0 || type == 2) {
//                // 查询相关联的医生
//                Iterable<ConsultTeamDoctorDo> iterable = consultTeamDoctorDao.findByConsult(log.getConsult());
//                if (iterable != null && iterable.iterator().hasNext()) {
//                    Iterator<ConsultTeamDoctorDo> iterator = iterable.iterator();
//                    while (iterator.hasNext()) {
//                        // 患者提问或追问,给医生发消息
//                        ConsultTeamDoctorDo ctd = iterator.next();
//                        if (ctd == null) {
//                            continue;
//                        }
//                        // 推送消息给医生
//                        pushMsgTask.put(ctd.getTo(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.D_CT_02.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.指定咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.您有新的消息.name(), temp.getConsult());
//                    }
//                }
//                // 医生未读数量+1
//                consultTeamDao.increaseDoctorRead(log.getConsult());
//            }
//        }
//        return temp;
//    }
    /**
     * 患者直接发起康复咨询
     */
//    public JSONObject addRecoverConsult(ConsultTeamDo ct, Long teamId, String patient, String agent, String times) throws Exception {
//        JSONObject re = new JSONObject();
//        if (exist(patient, ct.getType())) {//判断是否有未结束的咨询移到同步方法中
//            re.put("status", -3);
//            return re;
//        }
//
//        //议题添加团队内所有成员
//        JSONObject users = new JSONObject();
//        String specialDoctorCode = "";
//        List<BaseDoctorDO> docList = doctorAdminTeamMemberDao.findAllMembers(teamId);
//        for (BaseDoctorDO doc : docList) {
//            if (StringUtils.isBlank(specialDoctorCode) && doc.getLevel() == 1) {
//                specialDoctorCode = doc.getId();
//            }
//            users.put(doc.getId(), 0);
//        }
//
//        if (patient.equals(agent)) {
//            agent = null;
//        }
//
//        // 获取家庭医生
//        SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
//        if (sf == null) {
//            // 不存在家庭签约
//            re.put("status", -1);
//            return re;
//        }
//        ct.setTeam(sf.getTeamCode());
//        // 设置健康管理师,家庭医生咨询默认给健康管理师处理
//        //查找病人所在的团队
//        //1.3.3.2 更改从签约记录判断团队成员,分配建管师
//        if (StringUtils.isNotBlank(sf.getDoctorHealth())) {
//            users.put(sf.getDoctorHealth(), 0);
//            ct.setDoctor(sf.getDoctorHealth());
//            if (StringUtils.isNotBlank(sf.getDoctor())) {
//                if (users.isNull(sf.getDoctor())) {
//                    //全科需要判断是否开启健管师邀请后在接收消息
//                    int isGetMessage = 1;
//                    if (!messageService.getMessageNoticeSettingByMessageType(sf.getDoctor(), "1", MessageNoticeSetting.MessageTypeEnum.familyTopicSwitch.getValue())) {
//                        isGetMessage = 0;
//                    }
//                    users.put(sf.getDoctor(), isGetMessage);
//                }
//            }
//        } else {
//            ct.setDoctor(sf.getDoctor());
//            users.put(sf.getDoctor(), 0);
//        }
//        ct.setAdminTeamId(teamId);
//
//        // 设置患者信息
//        ct.setPatient(patient);
//        // 查询患者信息
//        Patient tempPatient = patientDao.findByCode(patient);
//        // 设置患者姓名
//        ct.setName(tempPatient.getName());
//        // 设置患者生日
//        ct.setBirthday(tempPatient.getBirthday());
//        //新增性别
//        ct.setSex(tempPatient.getSex());
//        // 设置患者头像
//        ct.setPhoto(tempPatient.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        ct.setEvaluate(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), tempPatient.getName() + "康复咨询", ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置关联指导
//        consult.setGuidance(ct.getGuidance());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        String sessionId = patient + "_" + ct.getDoctor() + "_" + specialDoctorCode + "_" + ct.getType();
//        //推送给IM去创建议题,取得成员消息
//        JSONObject messages = ImUtill.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), consult.getSymptoms(), consult.getImages(), ct.getVoice(), agent);
//        users.put(patient, 0);//+ " "+(tempPatient.getSex()==1?"(男 ":"(女 ") + IdCardUtil.getAgeForIdcard(tempPatient.getIdcard())+")"
//        JSONObject obj = ImUtill.createTopics(sessionId, consult.getCode(), tempPatient.getName(), users, messages, ImUtill.SESSION_TYPE_KANGFU);
//        //specialDoctorCode
//        if (obj == null) {
//            throw new ServiceException("IM消息发送异常!");
//        }
//        if (obj.getInt("status") == -1) {//im议题创建失败
//            throw new ServiceException(obj.getString("message"));
//        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        try {
//            //发送图片
//            if (StringUtils.isNotBlank(ct.getVoice())) {
//                String voices[] = ct.getVoice().split(",");
//                String tims[] = times.split(",");
//                for (int i = 0; i < voices.length; i++) {
//                    String voice = voices[i];
//                    JSONObject json = new JSONObject();
//                    json.put("path", voice);
//                    json.put("times", tims[i]);
//                    ImUtill.sendImMsg(patient, tempPatient.getName(), sessionId, "3", json.toString(), "1");
//                }
//                jdbcTemplate.update("update " + imdb + ".topics set reply=0,reply_time=null,reply_message_id=null,reply_user=null where id = '" + consult.getCode() + "' ");
//            }
//            SpecialDiseaseMessages diseaseMessages = new SpecialDiseaseMessages();
//            diseaseMessages.setCode(patient);
//            diseaseMessages.setName(tempPatient.getName());
//            diseaseMessages.setAddress(tempPatient.getAddress());
//            diseaseMessages.setCodeType("2");
//            diseaseMessages.setCreateTime(sdf.format(new Date()));
//            diseaseMessages.setResult("发起康复咨询");
//            specialDiseaseMessagesDao.save(diseaseMessages);
//        } catch (Exception e) {
//            logger.info("ConsultTeamService中 addRecoverConsult 方法保存出错");
//            e.printStackTrace();
//        }
//        ct.setStartMsgId(obj.get("start_msg_id").toString());
//        consultTeamDao.save(ct);
//        consultDao.save(consult);
//
//        JSONArray doctor = new JSONArray();
//        for (String key : users.keySet()) {
//            if (patient.equals(key)) {
//                continue;
//            }
//            doctor.put(key);
//            //记录咨询的医生详情误删
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(key);
//            consultTeamDoctorDao.save(cd);
//        }
//
//        // 保存医生咨询信息
//        // 添加咨询转发记录
//        // 添加医生咨询日志
//        addLogs(ct);
//        re.put("doctor", doctor);
//        re.put("status", 1);
//        return re;
//
//    }
    /**
     * 患者端
     * 添加三师咨询
     *
     * @param ct      三师咨询对象
     * @param patient 患者标识
     */
//    public JSONObject addTeamConsult(ConsultTeamDo ct, String patient, String agent, String times) throws Exception {
//        JSONObject re = new JSONObject();
//        if (exist(patient, ct.getType())) {//判断是否有未结束的咨询移到同步方法中
//            re.put("status", -3);
//            return re;
//        }
//
//        JSONObject users = new JSONObject();
//
//        if (patient.equals(agent)) {
//            agent = null;
//        }
//
//        if (ct.getType() == 2) {
//            // 咨询家庭医生
//            SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
//
//            if (sf == null) {
//                // 不存在家庭签约
//                re.put("status", -1);
//                return re;
//            }
//            ct.setTeam(sf.getTeamCode());
//            // 设置健康管理师,家庭医生咨询默认给健康管理师处理
//            //查找病人所在的团队
//            //1.3.3.2 更改从签约记录判断团队成员,分配建管师
//            if (StringUtils.isNotBlank(sf.getDoctorHealth())) {
//                users.put(sf.getDoctorHealth(), 0);
//                ct.setDoctor(sf.getDoctorHealth());
//                if (StringUtils.isNotBlank(sf.getDoctor())) {
//                    if (users.isNull(sf.getDoctor())) {
//                        //全科需要判断是否开启健管师邀请后在接收消息
//                        int isGetMessage = 1;
//                        if (!messageService.getMessageNoticeSettingByMessageType(sf.getDoctor(), "1", MessageNoticeSetting.MessageTypeEnum.familyTopicSwitch.getValue())) {
//                            isGetMessage = 0;
//                        }
//                        users.put(sf.getDoctor(), isGetMessage);
//                    }
//                }
//            } else {
//                ct.setDoctor(sf.getDoctor());
//                users.put(sf.getDoctor(), 0);
//            }
//
//            // 设置家庭医生
//            ct.setAdminTeamId(sf.getAdminTeamId());
//        }
//        // 设置患者信息
//        ct.setPatient(patient);
//        // 查询患者信息
//        Patient tempPatient = patientDao.findByCode(patient);
//        // 设置患者姓名
//        ct.setName(tempPatient.getName());
//        // 设置患者生日
//        ct.setBirthday(tempPatient.getBirthday());
//        //新增性别
//        ct.setSex(tempPatient.getSex());
//        // 设置患者头像
//        ct.setPhoto(tempPatient.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        ct.setEvaluate(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置关联指导
//        consult.setGuidance(ct.getGuidance());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//
//        //推送给IM去创建议题,取得成员消息
//        JSONObject messages = ImUtill.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), consult.getSymptoms(), consult.getImages(), ct.getVoice(), agent);
//        users.put(patient, 0);//+ " "+(tempPatient.getSex()==1?"(男 ":"(女 ") + IdCardUtil.getAgeForIdcard(tempPatient.getIdcard())+")"
//        String sessionId = patient + "_" + ct.getTeam() + "_" + ct.getType();
//        JSONObject obj = ImUtill.createTopics(sessionId, consult.getCode(), tempPatient.getName(), users, messages, ImUtill.SESSION_TYPE_MUC);
//        if (obj == null) {
//            throw new ServiceException("IM消息发送异常!");
//        }
//        if (obj.getInt("status") == -1) {//im议题创建失败
//            throw new ServiceException(obj.getString("message"));
//        }
//        try {
//            //发送图片
//            if (StringUtils.isNotBlank(ct.getVoice())) {
//                String voices[] = ct.getVoice().split(",");
//                String tims[] = times.split(",");
//                for (int i = 0; i < voices.length; i++) {
//                    String voice = voices[i];
//                    JSONObject json = new JSONObject();
//                    json.put("path", voice);
//                    json.put("times", tims[i]);
//                    ImUtill.sendImMsg(patient, tempPatient.getName(), sessionId, "3", json.toString(), "1");
//                }
//                jdbcTemplate.update("update " + imdb + ".topics set reply=0,reply_time=null,reply_message_id=null,reply_user=null where id = '" + consult.getCode() + "' ");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        ct.setStartMsgId(obj.get("start_msg_id").toString());
//        consultTeamDao.save(ct);
//        consultDao.save(consult);
//
//        JSONArray doctor = new JSONArray();
//        for (String key : users.keySet()) {
//            if (patient.equals(key)) {
//                continue;
//            }
//            doctor.put(key);
//            //记录咨询的医生详情误删
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(key);
//            consultTeamDoctorDao.save(cd);
//        }
//
//        // 保存医生咨询信息
//        // 添加咨询转发记录
//        // 添加医生咨询日志
//        addLogs(ct);
//        re.put("doctor", doctor);
//        re.put("status", 1);
//        return re;
//
//    }
    /**
     * 添加续方咨询
     *
     * @param signTag      0为家签 1为非家签
     * @param hospital     机构CODE
     * @param hospitalName 机构名称
     * @param adminTeamId  机构名称
     */
//    public Integer addPrescriptionConsult(String jwCode, String patient, String agent, String doctorCode, ConsultTeam ct,
//                                          String reason, Integer type, String addressJson, int dispensaryType, Integer signTag,
//                                          String hospital, String hospitalName, Long adminTeamId, String systolic,
//                                          String diastolic, String bloodSugar, String bloodSugarType, String rateType) throws Exception {
//
//        synchronized (jwCode.intern()) {
//            String check = prescriptionInfoService.presCheckState(jwCode);
//            if ("0".equals(check)) {//存在未审核的续方
//                return -1;
//            }
//
//            Doctor doctor = doctorDao.findByCode(doctorCode);
//            if (signTag == null) {
//                signTag = 0;
//            }
//            //非家签 下线非家签可续方
////            if(1 == signTag){
////                ct.setAdminTeamId(adminTeamId);
////            }else{
//            //家签
//            SignFamily signFamily = signFamilyDao.findByPatient(patient);
//            if (signFamily == null) {
//                return -2;
//            }
//
//            ct.setAdminTeamId(signFamily.getAdminTeamId());
//            doctor = doctorDao.findByAdminTeamId(signFamily.getAdminTeamId());
//            doctorCode = doctor.getCode();
//            adminTeamId = signFamily.getAdminTeamId();
////            }
//
//            // 查询患者信息
//            BasePatientDO  p = patientDao.findByCode(patient);
//
//            //1、获取基位处方详情(保存续方表、药品续方信息表、续方疾病类型表)
//            Prescription prescription = new Prescription();
//            //家签,非家签的标签
//            prescription.setSignTag(signTag);
//
//            prescription.setDiastolic(diastolic);
//            prescription.setSystolic(systolic);
//            prescription.setBloodSugar(bloodSugar);
//            prescription.setBloodSugarType(bloodSugarType);
//
//            prescription = savePrescription(prescription, jwCode, doctor, p, ct, reason, hospital, rateType);
//
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("title", p.getName() + "申请续方");
//
//            //2、获取体征记录
//            List<PatientDevice> devices = patientDeviceDao.findByPatient(patient);
//            if (devices != null && devices.size() > 0) {
//                int count = messageDao.findTzMessage(patient);
//                jsonObject.put("tzMsg", "最近七天有" + count + "条异常记录");
//            } else {
//                jsonObject.put("tzMsg", "居民未绑定体征设备");
//            }
//            //3、获取上次续方时间:与平安的“智慧医保的审方系统”对接,判断居民上次续方时间,点击跳转上次续方记录。(此功能需与第三方系统对接,如果本次版本无法实现,则消息中不显示此条信息)
//            jsonObject.put("lastTime", "");
//
//            String content = jsonObject.toString();
//
//            //4、创建咨询
//            JSONObject users = new JSONObject();//咨询参与者
//            users.put(patient, 0);
//            users.put(doctorCode, 0);
//            if (patient.equals(agent)) {
//                agent = null;
//            }
//            //关联业务code
//            ct.setRelationCode(prescription.getCode());
//            //医生信息
//            ct.setDoctor(doctorCode);
//            ct.setDoctorName(doctor.getName());
//            // 设置患者信息
//            ct.setPatient(patient);
//            if (1 == type) {
//                ct.setSymptoms("高血压");
//            } else if (2 == type) {
//                ct.setSymptoms("糖尿病");
//            } else if (3 == type) {
//                ct.setSymptoms("高血压,糖尿病");
//            } else if (4 == type) {
//                ct.setSymptoms("其他疾病");
//            }
//
//            // 设置患者姓名
//            ct.setName(p.getName());
//            // 设置患者生日
//            ct.setBirthday(p.getBirthday());
//            //新增性别
//            ct.setSex(p.getSex());
//            // 设置患者头像
//            ct.setPhoto(p.getPhoto());
//            // 设置操作日期
//            ct.setCzrq(new Date());
//            ct.setDel("1");
//            ct.setStatus(0);
//            ct.setEvaluate(0);
//            // 医生未读数量为1
//            ct.setDoctorRead(1);
//            // 添加咨询记录
//            Consult consult = addConsult(ct.getPatient(), "申请续方", ct.getSymptoms(), ct.getImages(), ct.getType());
//            // 设置关联指导
//            consult.setGuidance(ct.getGuidance());
//            //关联业务code
//            consult.setRelationCode(prescription.getCode());
//            // 设置咨询标识
//            ct.setConsult(consult.getCode());
//
//            //推送给IM去创建议题,取得成员消息
//            JSONObject messages = ImUtill.getCreateTopicMessage(patient, p.getName(), consult.getTitle(), content, consult.getImages(), agent);
//
//            //5、(im创建咨询) 续方咨询的sessionid为居民code+续方code+咨询类型
//            String sessionId = patient + "_" + consult.getCode() + "_" + ct.getType();
//            JSONObject obj = ImUtill.createTopics(sessionId, consult.getCode(), p.getName(), users, messages, ImUtill.SESSION_TYPE_PRESCRIPTION);
//            if (obj == null) {
//                throw new ServiceException("IM消息发送异常!");
//            }
//            if (obj.getInt("status") == -1) {//im议题创建失败
//                throw new ServiceException(obj.getString("message"));
//            }
//            ct.setStartMsgId(obj.get("start_msg_id").toString());
//            consultTeamDao.save(ct);
//            consultDao.save(consult);
//
//            //设置咨询code
//            prescription.setConsult(consult.getCode());
//            prescription.setViewSuifang(0);
//            prescription.setViewWenjuan(0);
//            prescription.setViewXufang(0);
//            prescription.setViewChufang(0);
//            prescription.setViewTizhen(0);
//            prescription.setViewJiancha(0);
//            prescriptionDao.save(prescription);
//
//            //6、记录咨询的医生详情
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(doctorCode);
//            consultTeamDoctorDao.save(cd);
//
//            //7、发送系统消息提示团队长有未审核的消息
//            addCheckMessage(prescription, sessionId, p);
//
//            //8、 保存医生咨询信息
//            // 添加咨询转发记录
//            // 添加医生咨询日志
//            addLogs(ct);
//
//            Patient patientObj = patientDao.findByCode(patient);
//
//            //9、添加续方的随访记录
//            Followup followup = new Followup();
//            followup.setFollowupDate(new Date());
//            followup.setFollowupPlanDate(new Date());
//            followup.setDoctorCode(doctorCode);
//            followup.setDoctorName(doctor.getName());
//            followup.setOrgCode(doctor.getHospital());
//            followup.setOrgName(doctor.getHospitalName());
//            followup.setPatientCode(patient);
//            followup.setPatientName(patientObj.getName());
//            followup.setIdcard(patientObj.getIdcard());
//
//            if (3 == type) {
//                followup.setFollowupClass("1,2");
//            } else {
//                followup.setFollowupClass(String.valueOf(type));
//            }
//
//            followup.setFollowupType("1");//门诊随访
//
//            followup.setDataFrom("2");//数据来源 1基卫 2APP
//            followup.setStatus("2");     //状态 0取消 1已完成 2未开始 3进行中
//            followup.setCreateTime(new Date());
//            followup.setCreater(doctorCode);
//            followup.setAdminTeamCode(adminTeamId);
//            followup.setSignType(2);
//            //保存质询code
//            followup.setSignCode(patientService.getSignCodeByPatient(patient));
//            followup.setPrescriptionCode(prescription.getCode());
//            followupDao.save(followup);
//
//
//            PrescriptionExpressage expressage = expressageDao.findByPrescriptionPay(prescription.getCode());
//            if (expressage == null) {
//                expressage = new PrescriptionExpressage();
//                expressage.setCode(getCode());
//            }
//            expressage.setPrescriptionCode(prescription.getCode());
//            com.alibaba.fastjson.JSONObject addressInfo = JSON.parseObject(addressJson);
//
//            String phone = addressInfo.getString("phone");
//            expressage.setMobile(phone);//收货人手机号码
////        配药机构信息(签约机构)
//            expressage.setHospitalCode(prescription.getHospital());
//            expressage.setHospitalName(prescription.getHospitalName());
////            expressage.setHospitalAddress(signAddress);
//
//            //微信登录患者信息
//            String userName = p.getName();
//            String userProvince = p.getProvince();
//            String userProvinceName = p.getProvinceName();
//            String userCity = p.getCity();
//            String userCityName = p.getCityName();
//            String userTown = p.getTown();
//            String userTownName = p.getTownName();
//            String userStreet = p.getStreet();
//            String userStreetName = p.getStreetName();
//            String userAddress = p.getAddress();
//            switch (dispensaryType) {
//                case 1:
//                    prescription.setDispensaryType(1);//取药类型:1 自取 2快递配送 3健管师配送
//                    //自取保存居民信息
//                    expressage.setName(userName);//居民姓名
//                    expressage.setProvinceCode(userProvince);//省代码
//                    expressage.setProvinceName(userProvinceName);//省名称
//                    expressage.setCityCode(userCity);//市代码
//                    expressage.setCityName(userCityName);//市名称
//                    expressage.setTownCode(userTown);//区code
//                    expressage.setTownName(userTownName);//区名称
//                    expressage.setStreetCode(userStreet);//街道code
//                    expressage.setStreetName(userStreetName);//街道名称
//                    expressage.setAddress(userAddress);//居民详细地址
//
//                    expressage.setCreateTime(new Date());//创建时间
//                    expressage.setOneselfPickupFlg(1);//是否自取 1是 0否
//                    expressage.setDel(1);//有效
//                    break;
//                case 2:
//                    prescription.setDispensaryType(2);//取药类型:1 自取 2快递配送 3健管师配送
//                    //快递保存信息
//                    String name = addressInfo.getString("receiver");
//                    String proviceCode = addressInfo.getString("provinceCode");
//                    String proviceName = addressInfo.getString("provinceName");
//                    String cityCode = addressInfo.getString("cityCode");
//                    String cityName = addressInfo.getString("cityName");
//                    String townCode = addressInfo.getString("townCode");
//                    String townName = addressInfo.getString("townName");
//                    String streeCode = addressInfo.getString("streeCode");
//                    String streeName = addressInfo.getString("streeName");
//                    String address = addressInfo.getString("address");
//
//                    expressage.setName(name);//居民姓名
//                    expressage.setProvinceCode(proviceCode);//省代码
//                    expressage.setProvinceName(proviceName);//省名称
//                    expressage.setCityCode(cityCode);//市代码
//                    expressage.setCityName(cityName);//市名称
//                    expressage.setTownCode(townCode);//区code
//                    expressage.setTownName(townName);//区名称
//                    expressage.setStreetCode(streeCode);//街道code
//                    expressage.setStreetName(streeName);//街道名称
//                    expressage.setAddress(address);//居民详细地址
//
//                    expressage.setExpressageHospitalName("顺丰快递");
//
//                    expressage.setCreateTime(new Date());//创建时间
//                    expressage.setOneselfPickupFlg(0);//是否自取 1是 0否
//                    expressage.setDel(1);//有效
//                    break;
//                case 3:
//                    prescription.setDispensaryType(3);//取药类型:1 自取 2快递配送 3健管师配送
//                    //健管师配送
//                    expressage.setName(userName);//居民姓名
//                    expressage.setProvinceCode(userProvince);//省代码
//                    expressage.setProvinceName(userProvinceName);//省名称
//                    expressage.setCityCode(userCity);//市代码
//                    expressage.setCityName(userCityName);//市名称
//                    expressage.setTownCode(userTown);//区code
//                    expressage.setTownName(userTownName);//区名称
//                    expressage.setStreetCode(userStreet);//街道code
//                    expressage.setStreetName(userStreetName);//街道名称
//                    expressage.setAddress(userAddress);//居民详细地址
//
//                    //居民选择的要送达的服务站
//                    String userOrgCode = addressInfo.getString("code");
//                    String userOrgName = addressInfo.getString("name");
//                    String userOrgAddress = addressInfo.getString("address");
//                    expressage.setPatientHospitalCode(userOrgCode);
//                    expressage.setPatientHospitalName(userOrgName);
//                    expressage.setPatientHospitalAddress(userOrgAddress);
//
//                    expressage.setCreateTime(new Date());//创建时间
//                    expressage.setOneselfPickupFlg(0);//是否自取 1是 0否
//                    expressage.setDel(1);//有效
//                    break;
//                case 4:
//                    prescription.setDispensaryType(4);//取药类型:1 自取 2快递配送 3健管师配送 4网格员派送
//
//                    expressage.setName(addressInfo.getString("receiver"));//居民姓名
//                    expressage.setProvinceCode(addressInfo.getString("provinceCode"));//省代码
//                    expressage.setProvinceName(addressInfo.getString("provinceName"));//省名称
//                    expressage.setCityCode(addressInfo.getString("cityCode"));//市代码
//                    expressage.setCityName(addressInfo.getString("cityName"));//市名称
//                    expressage.setTownCode(addressInfo.getString("townCode"));//区code
//                    expressage.setTownName(addressInfo.getString("townName"));//区名称
//                    expressage.setStreetCode(addressInfo.getString("streeCode"));//街道codestreetCode
//                    expressage.setStreetName(addressInfo.getString("streeName"));//街道名称
//                    expressage.setAddress(addressInfo.getString("address"));//居民详细地址
//
//                    expressage.setCreateTime(new Date());//创建时间
//                    expressage.setOneselfPickupFlg(1);//是否自取 1是 0否
//                    expressage.setDel(1);//有效
//                    break;
//            }
//
//            //保存物流信息
//            expressageDao.save(expressage);
//
//            return 1;
//        }
//    }
    /**
     * 保存审核提醒消息
     */
//    public void addCheckMessage(Prescription prescription, String sessionId, BasePatientDO p) {
//        SystemMessageDO message = new SystemMessageDO();
//        message.setCreateTime(new Date());
//        message.setCreateTime(new Date());
//        message.setIsRead("1");//设置未读
//        message.setOver("1");
//        message.setSenderPhoto(p.getPhoto());
//        message.setReceiver(prescription.getDoctor());
//        message.setSender(prescription.getPatient());
//        message.setCode(getCode());
//        message.setSenderName(prescription.getPatientName());
//        message.setTitle(prescription.getPatientName() + "申请续方");
//        message.setContent("您有一条新的续方申请待处理!");
//        message.setType(6);//续方咨询待审核提醒
//        message.setReadonly(1);//是否只读消息
//        message.setDel("1");
//        message.setRelationCode(prescription.getConsult());
//        message.setPrescriptionStatus("0");
//        message.setSessionId(sessionId);
//        message.setSessionName(prescription.getPatientName());
//        messageDao.save(message);
//    }
    /**
     * 保存续方信息
     */
//    public Prescription savePrescription(Prescription prescription, String jwCode, Doctor doctor, Patient p, ConsultTeam ct, String reason, String hospital, String ratType) throws Exception {
//        //获取智业处方详细
//        String response = jwPrescriptionService.getRecipe(jwCode, p.getSsc(), null, hospital);
//        com.alibaba.fastjson.JSONObject jsonObject = presModeAdapter.modelToSinglePrescription(response);
//
//        //续方主表
//        prescription.setCode(getCode());
//        prescription.setParentCode(jwCode);
//        prescription.setHospitalName(doctor.getHospitalName());
//        prescription.setHospital(doctor.getHospital());
//        prescription.setAdminTeamId(ct.getAdminTeamId());
//        prescription.setCreateTime(new Date());
//        prescription.setDept(doctor.getDept());
//        prescription.setDeptName(doctor.getDeptName());
//        prescription.setDoctor(doctor.getCode());
//        prescription.setDoctorName(doctor.getName());
//        prescription.setJwCode(jwCode);
//        prescription.setPatient(p.getCode());
//        prescription.setPatientName(p.getName());
//        prescription.setSsc(p.getSsc());
//        prescription.setReason(reason);
//        prescription.setType(2);
//        prescription.setStatus(PrescriptionLog.PrescriptionLogStatus.revieweding.getValue());
//        prescription.setConsult(ct.getConsult());
//        prescription.setJwPayStatus(0);//处方结算状态,0为未结算,1为结算成功,默认为0
//        prescription.setZyCancelState(0);//智业取消状态
//        //保存智业的医生信息
//        Map<String, Object> map = zyDictService.findJwDoctorByDoctor(doctor.getCode());
//        if (map != null) {
//            prescription.setJwDoctorCode(map.get("jw_doctor").toString());
//            prescription.setJwHospital(map.get("jw_doctor_hospital").toString());
//        }
//        //设置费别类型
//        prescription.setJwRateTypeCode(zyDictService.getRateType(ratType));
//        prescription.setPresCreateTime(DateUtil.stringToDate(jsonObject.getString("createTime"), "yyyy-MM-dd"));
//
//
//        //保存续方药品(处方)信息
//        com.alibaba.fastjson.JSONArray infos = jsonObject.getJSONArray("prescriptionInfo");
//        int day = 0;
//        if (infos != null && infos.size() > 0) {
//            day = infos.getJSONObject(0).getInteger("dayCount");
//        }
//        for (int i = 0; i < infos.size(); i++) {
//            com.alibaba.fastjson.JSONObject info = infos.getJSONObject(i);
//            PrescriptionInfo prescriptionInfo = new PrescriptionInfo();
//            prescriptionInfo.setPrescriptionCode(prescription.getCode());
//            prescriptionInfo.setCode(getCode());
//            prescriptionInfo.setDel(1);
//            prescriptionInfo.setDirection(info.getString("USAGE_NAME"));//药品用法
//            prescriptionInfo.setDrugCode(info.getString("drugCode"));//药品code
//            prescriptionInfo.setDrugName(info.getString("drugName"));//药品名称
//            prescriptionInfo.setDrugRate(info.getString("drugRate"));//吃药频率
//            prescriptionInfo.setDrugRateName(getZyCommonDictName(info.getString("drugRate")));
//            prescriptionInfo.setDrugFormat(info.getString("drugFormat"));//药品规格
//            prescriptionInfo.setNum(info.getInteger("num"));//药品数目
//            prescriptionInfo.setPrice(CommonUtil.doubleToInt(info.getDouble("price")));//药品单价
////            prescriptionInfo.setIsRefrigerate(0);//是否冷藏 1是 0否
//            prescriptionInfo.setJwSubCode(info.getString("jwSubCode"));//智业子处方号
//
//            prescriptionInfo.setDrugNumUnit(info.getString("drugNumUnit"));//数量单位编码
//            prescriptionInfo.setDrugNumUnitName(info.getString("drugNumUnitName"));//数量单位名称
//            prescriptionInfo.setCost(CommonUtil.doubleToInt(info.getDouble("cost")));//金额
//            prescriptionInfo.setCharge(CommonUtil.doubleToInt(info.getDouble("charge")));//自付
//            prescriptionInfo.setBindFlag(info.getString("bindFlag"));//成组标志, 0.非成组,1.成组
//            prescriptionInfo.setDayCount(info.getInteger("dayCount"));//用药天数
//            //设置最小用药天数
//            if (prescriptionInfo.getDayCount() != null && prescriptionInfo.getDayCount() < day) {
//                day = prescriptionInfo.getDayCount();
//            }
//            prescriptionInfo.setDrugUsage(info.getString("drugUsage"));//用药方法编码
//            prescriptionInfo.setUsageName(info.getString("usageName"));//用药方法名称
//            prescriptionInfo.setPhysicDose(info.getString("physicDose"));//用药剂量
//            prescriptionInfo.setPhysicDoseUnit(info.getString("physicDoseUnit"));//剂量单位编码
//            prescriptionInfo.setPhysicDoseUnitName(info.getString("physicDoseUnitName"));//剂量单位名称
//            prescriptionInfo.setPhysicInjectPlace(info.getString("physicInjectPlace"));//注射地点编码
//            prescriptionInfo.setPhysicInjectPlaceName(info.getString("physicInjectPlaceName"));//注射地点名称
//            prescriptionInfo.setPhysicSkinTest(info.getString("physicSkinTest"));//注射地点名称
//            prescriptionInfo.setPhysicSkinTestName(info.getString("physicSkinTestName"));//皮试类型名称
//            prescriptionInfo.setRemark(info.getString("Remark"));//备注
//            //需要特殊处理的字段
//            ZyIvPhysicDict physicDict = zyDictService.findByPhysicCode(prescriptionInfo.getDrugCode());
//            String subjectClass = info.getString("subjectClass");//科目类型
//            String physicAmount = info.getString("physicAmount");//用药总量
//            String physicAmountUnit = info.getString("physicAmountUnit");//总量单位编码
//            String physicAmountUnitName = info.getString("physicAmountUnitName");//总量单位名称
//            int isRefrigerate = 0;
//            if (physicDict != null) {
//                subjectClass = physicDict.getSubjectClass();
//                isRefrigerate = "2".equals(physicDict.getStorageConditions()) ? 1 : isRefrigerate;
//                physicAmount = null;
//                physicAmountUnit = physicDict.getPackUnit();
//                physicAmountUnitName = zyDictService.findByDictNameAndCode("IV_MEASURE_UNIT_DICT", physicAmountUnit);
//            }
//            prescriptionInfo.setPhysicAmount(physicAmount);
//            prescriptionInfo.setPhysicAmountUnit(physicAmountUnit);
//            prescriptionInfo.setPhysicAmountUnitName(physicAmountUnitName);
//            prescriptionInfo.setIsRefrigerate(isRefrigerate);
//            prescriptionInfo.setSubjectClass(subjectClass);//科目编码
//
//            prescriptionInfoDao.save(prescriptionInfo);
//        }
//        //设置最小用药天数
//        prescription.setMinDrugDay(day);
//        //保存续方记录
//        prescriptionDao.save(prescription);
//
//
//        //保存续方疾病类型
//        com.alibaba.fastjson.JSONArray jaDiagnosis = jsonObject.getJSONArray("prescriptionDt");
//        for (Iterator iterator = jaDiagnosis.iterator(); iterator.hasNext(); ) {
//            com.alibaba.fastjson.JSONObject json = (com.alibaba.fastjson.JSONObject) iterator.next();
//            PrescriptionDiagnosis diagnosis = new PrescriptionDiagnosis();
//            diagnosis.setCode(json.getString("code"));
//            diagnosis.setPrescriptionCode(prescription.getCode());
//            diagnosis.setCreateTime(new Date());
//            diagnosis.setName(json.getString("name"));
//            diagnosis.setHealthProblemName(json.getString("healthProblemName"));
//            diagnosis.setHealthProblem(json.getString("healthProblem"));
//            diagnosis.setUpdateTime(new Date());
//            prescriptionDiagnosisDao.save(diagnosis);
//        }
//
//        //保存审核信息
//        PrescriptionReviewed reviewed = new PrescriptionReviewed();
//        reviewed.setPrescriptionCode(prescription.getCode());
//        reviewed.setCode(getCode());
//        reviewed.setStatus(PrescriptionReviewed.PrescriptionReviewedStatus.reviewed_wait.getValue());
//        reviewed.setCreateTime(new Date());
//        reviewed.setDoctor(prescription.getDoctor());
//        reviewed.setDoctorName(prescription.getDoctorName());
//        reviewed.setHospital(prescription.getHospital());
//        reviewed.setHospitalName(prescription.getHospitalName());
//        prescriptionReviewedDao.save(reviewed);
//
//        //添加保存日志
//        prescriptionLogService.addLog(prescription, PrescriptionLog.PrescriptionLogType.create.getValue(), 1, 1);
//
//        return prescription;
//    }
    public String getZyCommonDictName(String code) {
        try {
            String sql = "SELECT t.name FROM zy_common_dict t WHERE t.code=? AND t.dict_name='IV_RECIPE_FREQUENCY_DICT'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, new Object[]{code});
            if (list != null && list.size() > 0) {
                return (String) (list.get(0).get("name"));
            }
            return "";
        } catch (Exception e) {
            return "";
        }
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    private String sendIM(String from, String to, String contentType, String content) {
        String imAddr = im_list_get + "api/v1/chats/pm";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("from", from));
        params.add(new BasicNameValuePair("to", to));
        params.add(new BasicNameValuePair("contentType", contentType));
        params.add(new BasicNameValuePair("content", content));
        String response = httpClientUtil.post(imAddr, params, "UTF-8");
        return response;
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    private String sendGroupIM(String from, String groupCode, String contentType, String content) {
        String imAddr = im_list_get + "api/v1/chats/gm";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("from", from));
        params.add(new BasicNameValuePair("group", groupCode));
        params.add(new BasicNameValuePair("groupType", "1"));
        params.add(new BasicNameValuePair("contentType", contentType));
        params.add(new BasicNameValuePair("content", content));
        String response = httpClientUtil.post(imAddr, params, "UTF-8");
        return response;
    }
    /**
     * 添加三师咨询日志
     */
//    private String addLogs(ConsultTeamDo ct) {
//        List<ConsultTeamLogDo> logs = new ArrayList<>();
//        // 添加问题咨询日志
//        String content = "";
//
//        if (ct.getGuidance() != null && ct.getGuidance() > 0) {
//            //先判断从健康指导转咨询是否存在指导。
//            JSONObject json = guidanceService.findById(ct.getGuidance());
//
//            if (json == null) {
//                //再判断从健康教育文章转咨询是否存在文章 20170602
//                HealthEduArticle article = healthEduArticleService.findArticleById(ct.getGuidance());
//                if (article != null) {
//                    return verdictAddLogs(ct);
//                }
//                throw new ServiceException("健康指导不存在");
//            } else {
//                //  健康指导转咨询的指导内容
//                content += "医生" + (json.get("doctorName") != null ? json.get("doctorName").toString() : "")
//                        + "发出的指导:" + (json.getString("content") != null ? json.getString("content") : "") + "<br/>";
//            }
//
//        }
//
//        content += "咨询问题:" + (StringUtils.isEmpty(ct.getSymptoms()) ? "无" : ct.getSymptoms());
//
//        // 生成提问日志,并推送相关消息
//        ConsultTeamLog infoLog = new ConsultTeamLog();
//        infoLog.setConsult(ct.getConsult());
//        if (content.length() > 2500) {
//            content = content.substring(0, 2500);
//        }
//        infoLog.setContent(content);
//        infoLog.setDel("1");
//        infoLog.setType(0);
//        infoLog.setChatType(1);
//        infoLog.setCzrq(new Date());
//        logs.add(infoLog);
//        // 图片日志
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    ConsultTeamLog imgLog = new ConsultTeamLog();
//                    // 设置咨询标识
//                    imgLog.setConsult(ct.getConsult());
//                    // 设置图片URL
//                    imgLog.setContent(image);
//                    imgLog.setDel("1");
//                    infoLog.setType(0);
//                    imgLog.setCzrq(new Date());
//                    // 图片类型
//                    imgLog.setChatType(2);
//                    // 添加到待保存队列
//                    logs.add(imgLog);
//                }
//            }
//        }
//        // 语音日志
//        if (StringUtils.isNotEmpty(ct.getVoice())) {
//            ConsultTeamLog voiceLog = new ConsultTeamLog();
//            // 设置咨询标识
//            voiceLog.setConsult(ct.getConsult());
//            // 设置语音URL
//            voiceLog.setContent(ct.getVoice());
//            voiceLog.setDel("1");
//            infoLog.setType(0);
//            // 语音类型
//            voiceLog.setChatType(3);
//            voiceLog.setCzrq(new Date());
//            // 添加到待保存队列
//            logs.add(voiceLog);
//        }
//        if (!logs.isEmpty()) {
//            Iterable<ConsultTeamLog> iterable = consultTeamLogDao.save(logs);
//            if (iterable == null || !iterable.iterator().hasNext()) {
//                // 日志保存失败
//                throw new RuntimeException("咨询日志保存失败!");
//            }
//        }
//        return content;
//    }
    /**
     * 添加三师咨询日志(增加咨询来源是否存在判断)
     */
//    private String verdictAddLogs(ConsultTeamDo ct) {
//        List<ConsultTeamLogDo> logs = new ArrayList<>();
//        // 添加问题咨询日志
//        String content = "";
//
//        if (ct.getGuidance() != null && ct.getGuidance() > 0) {
//            //再判断从健康教育文章转咨询是否存在文章 20170602
//            HealthEduArticle article = healthEduArticleService.findArticleById(ct.getGuidance());
//            if (article == null) {
//                throw new RuntimeException("健康教育文章不存在!");
//            } else {
//                //  健康指导转咨询的指导内容
//                JSONObject jsonArticle = new JSONObject();
//
//                jsonArticle.put("doctorName", ct.getDoctorName() != null ? ct.getDoctorName() : "");
//                jsonArticle.put("content", article.getSummary() != null ? article.getSummary() : "");
//                jsonArticle.put("czrq", article.getCzrq() != null ? DateUtil.dateToStr(article.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM) : "");
//
//                content += "医生" + (jsonArticle.get("doctorName") != null ? jsonArticle.get("doctorName").toString() : "")
//                        + "发出的文章:" + (jsonArticle.getString("content") != null ? jsonArticle.getString("content") : "") + "<br/>";
//            }
//
//        }
//
//        content += "咨询问题:" + (StringUtils.isEmpty(ct.getSymptoms()) ? "无" : ct.getSymptoms());
//
//        // 生成提问日志,并推送相关消息
//        ConsultTeamLogDo infoLog = new ConsultTeamLogDo();
//        infoLog.setConsult(ct.getConsult());
//        infoLog.setContent(content);
//        infoLog.setDel("1");
//        infoLog.setType(0);
//        infoLog.setChatType(1);
//        infoLog.setCzrq(new Date());
//        logs.add(infoLog);
//        // 图片日志
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    ConsultTeamLogDo imgLog = new ConsultTeamLogDo();
//                    // 设置咨询标识
//                    imgLog.setConsult(ct.getConsult());
//                    // 设置图片URL
//                    imgLog.setContent(image);
//                    imgLog.setDel("1");
//                    infoLog.setType(0);
//                    imgLog.setCzrq(new Date());
//                    // 图片类型
//                    imgLog.setChatType(2);
//                    // 添加到待保存队列
//                    logs.add(imgLog);
//                }
//            }
//        }
//        // 语音日志
//        if (StringUtils.isNotEmpty(ct.getVoice())) {
//            ConsultTeamLogDo voiceLog = new ConsultTeamLogDo();
//            // 设置咨询标识
//            voiceLog.setConsult(ct.getConsult());
//            // 设置语音URL
//            voiceLog.setContent(ct.getVoice());
//            voiceLog.setDel("1");
//            infoLog.setType(0);
//            // 语音类型
//            voiceLog.setChatType(3);
//            voiceLog.setCzrq(new Date());
//            // 添加到待保存队列
//            logs.add(voiceLog);
//        }
//        if (!logs.isEmpty()) {
//            Iterable<ConsultTeamLogDo> iterable = consultTeamLogDao.saveAll(logs);
//            if (iterable == null || !iterable.iterator().hasNext()) {
//                // 日志保存失败
//                throw new RuntimeException("咨询日志保存失败!");
//            }
//        }
//        return content;
//    }
    /**
     * 查询咨询列表
     *
     * @param patientCode 患者标志
     * @param status      咨询状态(0未结束,1已结束,-1 已取消)
     * @param pageSize    页数
     */
//    public Page<ConsultTeamDo> findByPatient(String patientCode, int status, long id, int pageSize) {
//        if (id < 0) {
//            id = 0;
//        }
//        if (pageSize <= 0) {
//            pageSize = 10;
//        }
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pageSize, sort);
//
//        Page<ConsultTeamDo> list = null;
//        switch (status) {
//            case 0:
//                // 未结束
//                if (id > 0) {
//                    list = consultTeamDao.findNotFinishedBypatient(patientCode, id, pageRequest);
//                } else {
//                    list = consultTeamDao.findNotFinishedBypatient(patientCode, pageRequest);
//                }
//                break;
//            case 1:
//                // 已结束
//                if (id > 0) {
//                    list = consultTeamDao.findFinishedBypatient(patientCode, id, pageRequest);
//                } else {
//                    list = consultTeamDao.findFinishedBypatient(patientCode, pageRequest);
//                }
//                break;
//            case -1:
//                // 已取消
//                if (id > 0) {
//                    list = consultTeamDao.findCancelBypatient(patientCode, id, pageRequest);
//                } else {
//                    list = consultTeamDao.findCancelBypatient(patientCode, pageRequest);
//                }
//                break;
//        }
//        return list;
//    }
    /**
     * 医生关闭三师咨询(续方咨询)
     *
     * @param consult 三师咨询标识
     */
//    public int finish(String consult, String endOperator, int endType) throws Exception {
//
//        ConsultTeam consultTeam = consultTeamDao.findByConsult(consult);
//
//        //新增续方咨询结束判断 (续方未审核时不可由医生或居民关闭)
//        if (consultTeam.getType() == 8) {
//            Prescription prescription = prescriptionDao.findByCode(consultTeam.getRelationCode());
//            if (prescription.getStatus() == 0) {
//                return -2;
//            }
//        }
//
//        String name = "";
//        String returnJson = "";
//        //推送给IM文字消息
//        if (endType == 1) {
//            BasePatientDO  p = patientDao.findByCode(endOperator);
//            name = p.getName();
//            returnJson = sendIM(consultTeam.getPatient(), consultTeam.getDoctor(), "7", name + "结束了本次咨询");
//        } else {
//            Doctor d = doctorDao.findByCode(endOperator);
//            name = d.getName();
//            returnJson = sendIM(consultTeam.getDoctor(), consultTeam.getPatient(), "7", name + "结束了本次咨询");
//        }
//
//        if (StringUtils.isEmpty(returnJson)) {
//            throw new ServiceException("send consult finished IM message failed");
//        } else {
//            JSONObject jo = new JSONObject(returnJson);            //设置消息ID
//            consultTeam.setEndMsgId(jo.getInt("startId") + "");
//            consultTeam.setEndOperator(endOperator);
//            consultTeam.setEndType(endType);
//        }
//
//        JSONObject group = talkGroupService.findConsultTalkGroup(consultTeam.getConsult());
//
//        if (group != null) {
//            String json = sendGroupIM(endOperator, group.getString("code"), "7", name + "结束了本次咨询");
//
//            if (StringUtils.isEmpty(json)) {
//                throw new ServiceException("send consult finished IM message failed");
//            }
//        }
//
//        return consultTeamDao.updateStatusByConsult(consult);
//    }
                content = "一条消息";
            }
            String url = temp.getUrl() + "&openid=" + p.getOpenid() + "&peerId=" + doctor + "&peerName=" + doctorName;
            json.put("consultcontent", temp.getKeyword1());
            json.put("replycontent", content);
            json.put("doctorName", doctorName);
            json.put("remark", "");
            json.put("url", url);
            pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 3, p.getOpenid(), p.getName(), json);
        }
    }
    /**
     * 设置咨询已读
@ -2171,12 +191,6 @@ public class ConsultTeamService extends ConsultService {
        return 1;
    }
    /**
     * 取消三师咨询
     */
//    public int cancel(String consult) {
//        return consultTeamDao.cancel(consult);
//    }
    public ConsultTeamDo findByCode(String code) {
        return consultTeamDao.findByConsult(code);
    }
@ -2185,208 +199,11 @@ public class ConsultTeamService extends ConsultService {
        return consultTeamDao.findById(id).orElse(null);
    }
    /**
     * 三师咨询转接医生
     *
     * @param from    转出医生标识
     * @param to      转入医生标识
     * @param consult 三师咨询标识
     */
//    public void transfer(String from, String to, String consult) {
//        // 检查是否存在
//        if (consultTeamDoctorDao.isExist(consult, to) == 0) {
//            ConsultTeam ct = consultTeamDao.findByConsult(consult);
//            int count = consultTeamLogDao.countByConsult(consult);
//            // 设置未读消息数
//            ct.setDoctorRead(count);
//            consultTeamDao.save(ct);
//            // 查询医生信息
//            Doctor d = doctorDao.findByCode(from);
//            // 再保存
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult);
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setFrom(d.getCode());
//            cd.setFromName(d.getName());
//            cd.setTo(to);
//            consultTeamDoctorDao.save(cd);
//        }
//    }
    /**
     * 查询患者视频和三师咨询记录
     */
//    public Page<ConsultDo> findConsultRecordByPatientType(String patient, long id, int pagesize) {
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        // 设置查询条件
//        Map<String, SearchFilter> filters = new HashMap<>();
//        filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
//        filters.put("type", new SearchFilter("type", Operator.LT, 3));
//        if (id > 0) {
//            filters.put("id", new SearchFilter("id", Operator.LT, id));
//        }
//        // 未作废
//        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//        Specification<Consult> spec = DynamicSpecifications.bySearchFilter(filters.values(), Consult.class);
//        return consultDao.findAll(spec, pageRequest);
//    }
    /**
     * 清空医生未读数量
     */
//    public void clearDoctorRead(String consult) {
//        consultTeamDao.clearDoctorRead(consult);
//    }
    /**
     * 查询医生的咨询统计
     */
//    public Map<String, Long> getAllCount(String doctorCode) {
//        Map<String, Long> result = new HashMap<>();
//
//        //根据医生code查询总咨询数
//        long allCount = consultTeamDoctorDao.getAllCountByDoctorCode(doctorCode);
//
//        //根据医生code查询今日咨询数
//        long todayCount = consultTeamDoctorDao.getTodayCountByDoctorCode(doctorCode);
//
//        result.put("all", allCount);
//        result.put("today", todayCount);
//
//        return result;
//    }
    /**
     * 查找未完成咨询
     */
//    public List<ConsultTeamDo> getUnfinishedConsult(String patient) {
//        return consultTeamDao.findUnfinishedConsult(patient);
//    }
//    public List<ConsultHelp> findUnfinishedByPatientAndSpecialist(String patient, String doctor) {
//        return consultHelpDao.findUnfinishedByPatientAndSpecialist(patient, doctor);
//    }
    /**
     * 查询居民与某个医生未结束的咨询
     *
     * @param patient 居民
     * @param doctor  医生
     */
//    public List<ConsultTeamDo> getUnfinishedConsult(String patient, String doctor) {
//        return consultTeamDao.findUnfinishedConsultType(patient, doctor);
//    }
    /**
     * 查询患者全部的咨询数目
     */
//    public Integer findByDoctorSize(String patientCode, String doctorCode) {
//
//        return consultDao.findByPatient(patientCode, doctorCode);
//    }
    public List<Map<String, Object>> getConsultSign(String[] consults) {
        String params = "";
        List<String> paramList = new ArrayList<>();
        for (int i = 0; i < consults.length; i++) {
            params += (i == 0 ? "?" : ",?");
        }
        paramList.addAll(Arrays.asList(consults));
        paramList.addAll(Arrays.asList(consults));
        String sqlgp = "select DISTINCT consult,to_doctor from wlyy_consult_team_doctor ctd,wlyy_doctor d where ctd.to_doctor = d.code and d.level = 2 and ctd.consult in (" + params + ") and ctd.del = '1'";
        String sqlgpm = "select DISTINCT to_doctor from wlyy_consult_team_doctor ctd,wlyy_doctor d where ctd.to_doctor = d.code and d.level = 2 and ctd.consult in (" + params + ") and ctd.del = '1'";
        String sqlQu = "select * from wlyy_quota_result where qkdoctor_code in (" + sqlgpm + ") and quato_code = '1' and level1_type = '1'";
        String sqlQuSum = "select a.consult,sum(ifnull(b.result,0)) sign from (" + sqlgp + ") a left join (" + sqlQu + ") b on a.to_doctor = b.qkdoctor_code group by a.consult ";
        return jdbcTemplate.queryForList(sqlQuSum, paramList.toArray());
    }
    public ConsultTeamLogDo oneLog(Long logId) {
        return consultTeamLogDao.findById(String.valueOf(logId)).orElse(null);
    }
//    public boolean isExistConsult(String uid, String doctor) {
//        int consultTeam = consultTeamDao.countByPatient(uid, 2, doctor);
//        return consultTeam > 0;
//    }
    /**
     * 进入咨询
     */
//    public int intoTopic(String consult, String patient, String agent) throws Exception {
//        ConsultTeamDo ct = consultTeamDao.findByConsult(consult);
//        if (ct.getStatus() != 0) {
//            return -1;
//        }
//
//        String content = "进入了咨询";
//        BasePatientDO  p = patientDao.findById(patient);
//        String intoUserName = p.getName();
//        if (patient.equals(agent)) {
//            content = intoUserName + content;
//        } else {
//            PatientFamilyMember familyMember = familyMemberDao.findByPatientAndFamilyMember(patient, agent);
//            Patient member = patientDao.findByCode(agent);
//            content = member.getName() + "(" + relations.get(familyMember.getFamilyRelation()) + ")" + content;
//        }
//
//        imUtil.sendIntoTopicIM(ct.getPatient(), ct.getPatient(), ct.getConsult(), content, agent, intoUserName);
//
//        return 0;
//    }
    /**
     * 根据健康管理师和患者 找到正在进行中的咨询
     */
//    public ConsultTeam getConsultByPatientAndDoctor(String patientCode, String doctor) {
//        ConsultTeam consultTeam = consultTeamDao.findByParientCodeAndSignTypeAndDoctor(patientCode, doctor, 2);
//        return consultTeam;
//    }
//    public List<String> getConsultListByPatientAndDoctor(String doctor) throws Exception {
//        List<String> list = consultTeamDao.findParientListByDoctor(doctor);
//        return list;
//    }
//    public void transfers(String uid, String doctor, String consult) {
//        String[] doctors = doctor.split(",");
//        for (int i = 0; i < doctors.length; i++) {
//            transfer(uid, doctors[i], consult);
//        }
//    }
//    public String produceConsultAdminTeamCode() {
//        StringBuffer sf = new StringBuffer();
//        StringBuffer sf1 = new StringBuffer();
//        long size = 0L;
//        //找出家庭签约中团队code是空的
//        List<ConsultTeamDo> consultTeams = consultTeamDao.findByTypeAndAdminTeamIdIsNull(2);
//        sf.append("家庭签约咨询中团队code是空的数据数:" + consultTeams.size());
//        for (ConsultTeam consultTeam : consultTeams) {
//            //得到签约中的全科医生的团队
//            SignFamily signfamily = signFamilyDao.findByjiatingPatient(consultTeam.getPatient());
//            if (signfamily != null) {
//                if (signfamily.getAdminTeamId() != null && signfamily.getAdminTeamId() > 0) {
//                    consultTeam.setAdminTeamId(signfamily.getAdminTeamId());
//                    size++;
//                }
//            } else {
//                sf1.append(",找不到医生所属的团队,家庭签约咨询的Id:" + consultTeam.getId());
//            }
//        }
//        sf.append(",填充团队的签约数据数:" + size);
//        sf.append(sf1);
//        return sf.toString();
//    }
    public void save(ConsultTeamDo consult) {
        consultTeamDao.save(consult);
    }
@ -2395,675 +212,6 @@ public class ConsultTeamService extends ConsultService {
        return consultTeamDao.findByConsult(consultCode);
    }
//    public List<ConsultTeamLogDo> getConsultLog(String consultCode) {
//        return consultTeamLogDao.getConsultLogByConsultLog(consultCode);
//    }
//    public void addForHelpTeamConsult(ConsultTeamDo ct, String uid, String oldConsultCode) throws Exception {
//        // 设置患者信息
//        ct.setPatient(uid);
//        BaseDoctorDO doctorTemp = doctorDao.findById(uid);
//        // 设置医生姓名
//        ct.setName(doctorTemp.getName());
//        // 设置医生生日
//        ct.setBirthday(doctorTemp.getBirthday());
//        //新增性别
//        ct.setSex(doctorTemp.getSex());
//        // 设置医生头像
//        ct.setPhoto(doctorTemp.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 患者未读数量为0
//        ct.setPatientRead(0);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        // 添加咨询转发记录
//        ConsultTeamDoctor cd = new ConsultTeamDoctor();
//        cd.setConsult(consult.getCode());
//        cd.setDel("1");
//        cd.setCzrq(new Date());
//        cd.setTo(ct.getDoctor());
//        // 添加医生咨询日志
//        String content = addLogs(ct);
//        //推送给IM文字消息
//        String returnJson = null;
//        JSONObject jo;
//        if (StringUtils.isNotEmpty(oldConsultCode)) {
//            ConsultTeam oldConsult = consultTeamDao.findByConsult(oldConsultCode);
//            if (oldConsult != null) {
//                returnJson = sendIM(ct.getPatient(), ct.getDoctor(), "6", "居民问题:" + oldConsult.getSymptoms());
//                //推送给IM图片
//                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
//                    String[] images = oldConsult.getImages().split(",");
//                    for (String image : images) {
//                        if (StringUtils.isNoneEmpty(image)) {
//                            sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
//                        }
//                    }
//                }
//            }
//        }
//        if (StringUtils.isEmpty(returnJson))
//            returnJson = sendIM(ct.getPatient(), ct.getDoctor(), "6", content);
//        else
//            sendIM(ct.getPatient(), ct.getDoctor(), "6", content);
//        jo = new JSONObject(returnJson);
//        //设置消息ID
//        ct.setStartMsgId(jo.getInt("startId") + "");
//        //推送给IM图片
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
//                }
//            }
//        }
//        consultTeamDao.save(ct);  // 保存医生咨询信息
//        consultTeamDoctorDao.save(cd);
//        consultDao.save(consult);
//    }
//    public void sendForHelpMsg(ConsultTeam ct, String uid, String oldConsultCode) {
//        ct.setPatient(uid);
//        //推送给IM文字消息
//        if (StringUtils.isNotEmpty(oldConsultCode)) {
//            ConsultTeam oldConsult = consultTeamDao.findByConsult(oldConsultCode);
//            if (oldConsult != null) {
//                sendIM(ct.getPatient(), ct.getDoctor(), "6", "居民问题:" + oldConsult.getSymptoms());
//                //推送给IM图片
//                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
//                    String[] images = oldConsult.getImages().split(",");
//                    for (String image : images) {
//                        if (StringUtils.isNoneEmpty(image)) {
//                            sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
//                        }
//                    }
//                }
//            }
//        }
//        sendIM(ct.getPatient(), ct.getDoctor(), "6", "咨询问题:" + ct.getSymptoms());
//        //推送给IM图片
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
//                }
//            }
//        }
//    }
//    public List<ConsultTeamDo> hasUnfinished(String doctorCode, String uid) {
//        return consultTeamDao.findUnfinishedConsult(uid, doctorCode);
//    }
    /**
     * 判断两医生是否在同一团队内
     */
    public boolean isCommonTeam(String docCode1, String docCode2) {
        String sqlQuSum =
                "SELECT c.team_id FROM " +
                        "(SELECT a.* FROM wlyy_admin_team_member a where a.doctor_code='" + docCode1 + "' ) c " +
                        "LEFT JOIN " +
                        "(SELECT b.* FROM wlyy_admin_team_member b where b.doctor_code='" + docCode2 + "' ) d " +
                        "on c.team_id=d.team_id " +
                        "WHERE d.team_id IS NOT NULL";
        List ls = jdbcTemplate.queryForList(sqlQuSum);
        return ls != null && ls.size() > 0;
    }
    /**
     * 通过team获取医生code
     *
     * @param consult 关联的上一个咨询
     */
//    public List findByTeam(String consult) {
//        return consultTeamDao.findByTeamAndType(consult, 10);
//    }
    /**
     * 全科医生求助专科医生(同团队)
     *
     * @param isSend 是否转发患者咨询内容
     */
//    public void addSeekHelpTeam(ConsultTeamDo ct, String uid, String oldConsultCode, int isSend) {
//        ct.setPatient(uid);
//        //推送给IM文字消息
//        JSONObject participants = new JSONObject();
//        participants.put(ct.getPatient(), 0);
//        participants.put(ct.getDoctor(), 0);
//        BaseDoctorDO doctor = doctorService.findDoctorByCode(uid);
//        JSONObject sessionJson = imUtill.createSession(participants, imUtill.SESSION_TYPE_P2P, doctor.getName() + "发起求助!", "");
//        if (sessionJson.getString("status").equals("-1")) {
//            throw new RuntimeException(sessionJson.getString("message"));
//        }
//        JSONObject session = sessionJson.getJSONObject("data");
//        if (StringUtils.isNotEmpty(oldConsultCode)) {
//            ct.setTeam(oldConsultCode);
//            ConsultTeamDo oldConsult = consultTeamDao.findByConsult(oldConsultCode);
//            if (oldConsult != null && isSend == 1) {
//                imUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "1", "居民问题:" + oldConsult.getSymptoms(), "1");
//                //推送给IM图片
//                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
//                    String[] images = oldConsult.getImages().split(",");
//                    for (String image : images) {
//                        if (StringUtils.isNoneEmpty(image)) {
//                            imUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "2", image, "1");
//                        }
//                    }
//                }
//            }
//            BaseDoctorDO doctorTemp = doctorDao.findById(ct.getDoctor());
//            JSONObject qiuzuObj = new JSONObject();
//            qiuzuObj.put("session_id", oldConsult.getPatient() + "_consult_" + oldConsult.getType());
//            qiuzuObj.put("patient", ct.getPatient());
//            qiuzuObj.put("old_consult_code", oldConsultCode);
//            qiuzuObj.put("doctor", ct.getDoctor());
//            qiuzuObj.put("doctor_name", doctorTemp.getName());
//            imUtill.sendTopicIM(doctor.getId(), doctor.getName(), oldConsultCode, "5", qiuzuObj.toString(), null);
//        }
//
//
//        ImUtil.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "1", "咨询问题:" + ct.getSymptoms(), "1");
//        //推送给IM图片
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    ImUtil.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "2", image, "1");
//                }
//            }
//        }
//    }
    /**
     * 全科医生求助专科医生(不同团队)
     */
//    public void addSeekHelpOtherTeam(ConsultTeam ct, String uid, String oldConsultCode, int isSend) throws Exception {
//        // 设置患者信息
//        ct.setPatient(uid);
//        Doctor doctorTemp = doctorDao.findByCode(uid);
//        Doctor doctor = doctorDao.findByCode(ct.getDoctor());
//        // 设置医生姓名
//        ct.setName(doctorTemp.getName());
//        // 设置医生生日
//        ct.setBirthday(doctorTemp.getBirthday());
//        //新增性别
//        ct.setSex(doctorTemp.getSex());
//        // 设置医生头像
//        ct.setPhoto(doctorTemp.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 患者未读数量为0
//        ct.setPatientRead(0);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        // 添加咨询转发记录
//        ConsultTeamDoctor cd = new ConsultTeamDoctor();
//        cd.setConsult(consult.getCode());
//        cd.setDel("1");
//        cd.setCzrq(new Date());
//        cd.setTo(ct.getDoctor());
//        // 添加医生咨询日志
//        String content = addLogs(ct);
//        if (StringUtils.isBlank(oldConsultCode)) {
//            JSONObject messages = ImUtill.getCreateTopicMessage(doctorTemp.getCode(), doctorTemp.getName(), consult.getTitle(), content, consult.getImages(), null);
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put(ct.getPatient(), 0);
//            jsonObject.put(ct.getDoctor(), 0);
//            //设置消息ID
//            JSONObject obj = ImUtill.createTopics(null, consult.getCode(), doctorTemp.getName(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
//            if (obj == null || obj.getInt("status") == -1) {
//                throw new ServiceException("im消息创建异常!" + obj == null ? "" : obj.getString("message"));
//            }
//            ct.setStartMsgId(obj.get("start_msg_id").toString());
//        } else {
//            //转发咨询问题
//            Consult oldConsult = consultDao.findByCode(oldConsultCode);
//            ConsultTeam consultTeam = consultTeamDao.findByConsult(oldConsultCode);
//            ct.setTeam(oldConsultCode);
//            if (oldConsult != null && isSend == 1) {
//                JSONObject messages = ImUtill.getCreateTopicMessage(doctorTemp.getCode(), doctorTemp.getName(), consult.getTitle(), "居民问题:" + oldConsult.getSymptoms(), oldConsult.getImages(), null);
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put(ct.getPatient(), 0);
//                jsonObject.put(ct.getDoctor(), 0);
//                JSONObject obj = ImUtill.createTopics(null, consult.getCode(), doctorTemp.getName(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
//                if (obj == null || obj.getInt("status") == -1) {
//                    throw new ServiceException("im消息创建异常!" + obj == null ? "" : obj.getString("message"));
//                }
//                ct.setStartMsgId(obj.get("start_msg_id").toString());
//                Thread.sleep(100);//消息发送顺序问题处理
//                ImUtill.sendTopicIM(doctorTemp.getCode(), doctorTemp.getName(), consult.getCode(), "6", content, null);
//                if (StringUtils.isNotBlank(consult.getImages())) {
//                    String imgs[] = consult.getImages().split(",");
//                    for (String url : imgs)
//                        ImUtill.sendTopicIM(doctorTemp.getCode(), doctorTemp.getName(), consult.getCode(), "2", url, null);
//                }
//            } else if (oldConsult != null && isSend == 0) {
//                JSONObject messages = ImUtill.getCreateTopicMessage(doctorTemp.getCode(), doctorTemp.getName(), consult.getTitle(), content, oldConsult.getImages(), null);
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put(ct.getPatient(), 0);
//                jsonObject.put(ct.getDoctor(), 0);
//                JSONObject obj = ImUtill.createTopics(null, consult.getCode(), doctorTemp.getName(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
//                if (obj == null || obj.getInt("status") == -1) {
//                    throw new ServiceException("im消息创建异常!" + obj == null ? "" : obj.getString("message"));
//                }
//            }
//            JSONObject qiuzuObj = new JSONObject();
//            qiuzuObj.put("session_id", oldConsult.getPatient() + consultTeam.getTeam() + consult.getType());
//            qiuzuObj.put("patient", ct.getPatient());
//            qiuzuObj.put("old_consult_code", oldConsultCode);
//            qiuzuObj.put("doctor", ct.getDoctor());
//            qiuzuObj.put("doctor_name", doctor.getName());
//            ImUtill.sendTopicIM(doctorTemp.getCode(), doctorTemp.getName(), oldConsultCode, "5", qiuzuObj.toString(), null);
//        }
//        consultTeamDao.save(ct);  // 保存医生咨询信息
//        consultTeamDoctorDao.save(cd);
//        consultDao.save(consult);
//    }
//    public int finishConsult(String consult, String endOperator, int endType) throws Exception {
//        ConsultTeam consultTeam = consultTeamDao.findByConsult(consult);
//        Consult cons = consultDao.findByCode(consult);
//
//        if (consultTeam.getStatus() == 1) {
//            return -1;
//        }
//
//        //新增续方咨询结束判断 (续方未审核时不可由医生或居民关闭)
//        if (consultTeam.getType() == 8) {
//            Prescription prescription = prescriptionDao.findByCode(consultTeam.getRelationCode());
//            if (prescription.getStatus() == 0) {
//                return -2;
//            }
//        }
//
//        String endName = "";
//        String endId = "";
//        //结束咨询才发送推送给IM文字消息
//        if (endType == 1) {
//            BasePatientDO  p = patientDao.findByCode(endOperator);
//            endName = p.getName();
//            endId = p.getCode();
//        } else {
//            if (endOperator.equals("admin")) {
//                endId = "system";
//                endName = "咨询超时未回复,系统自动";
//            } else {
//                Doctor d = doctorDao.findByCode(endOperator);
//                endId = d.getCode();
//                endName = d.getName();
//            }
//        }
//
//        JSONObject obj = ImUtill.endTopics(consultTeam.getPatient(), endId, endName, consultTeam.getConsult());
//        if (obj == null) {
//            throw new ServiceException("IM消息结束异常!");
//        }
//        if (obj.getInt("status") == -1) {
//            throw new ServiceException(String.valueOf(obj.get("message")));
//        }
//
//        //结束咨询才发送推送给IM文字消息
//        if (endType == 1) {
//            BasePatientDO  p = patientDao.findByCode(endOperator);
//            endName = p.getName();
//            if (consultTeam.getType() == 2 || consultTeam.getType() == 8) {
//                String openId = p.getOpenid();
//
//                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zxpj");
//                String first = templateConfig.getFirst();
//                first = first.replace("key1", (endName == null ? "" : endName));
//                String keyword1 = templateConfig.getKeyword1();
//
//                JSONObject json = new JSONObject();
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                json.put("keyword1", keyword1);
//                json.put("keyword2", sdf.format(new Date()));
//                json.put("toUser", p.getCode());
//                json.put("represented", p.getCode());//被代理人
//                json.put("remark", "");
//                json.put("consult", consult);
////                String first = endName + ",您好!您有1条";;
//                if (consultTeam.getType() == 8) {
////                    first += "续方";
//                    first = first.replace("key2", "续方");
//                } else {
//                    first = first.replace("key2", "");
//                }
////                first += "咨询已结束,请及时对咨询医生进行评价。";
//                json.put("first", first);
//                if (StringUtils.isNotBlank(p.getOpenid())) {
//                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, openId, p.getName(), json);
//                } else {
//                    //发送代理人
//                    JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(), p.getOpenid());
//                    if (jsonArray != null && jsonArray.length() > 0) {
//                        for (int i = 0; i < jsonArray.length(); i++) {
//                            JSONObject j = jsonArray.getJSONObject(i);
//                            Patient member = (Patient) j.get("member");
//                            JSONObject data = json;
//                            data.remove("toUser");
//                            data.put("toUser", member.getCode());
//                            data.remove("first");
//                            data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
//                            pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, member.getOpenid(), p.getName(), data);
//                        }
//                    }
//                }
//            }
//        } else {
//            if (consultTeam.getType() == 2 || consultTeam.getType() == 8) {
//                BasePatientDO  p = patientDao.findByCode(consultTeam.getPatient());
//                String name = p.getName();
//                String openId = p.getOpenid();
//
//                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zxpj");
//
//                if (endOperator.equals("admin")) {
//                    templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zxcspj");
//                }
//                String first = templateConfig.getFirst();
//                first = first.replace("key1", (name == null ? "" : name));
//                String keyword1 = templateConfig.getKeyword1();
//
//                JSONObject json = new JSONObject();
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                json.put("keyword1", keyword1);
//                json.put("keyword2", sdf.format(new Date()));
//                json.put("toUser", p.getCode());
//                json.put("represented", p.getCode());//被代理人
//                json.put("remark", "");
//                json.put("consult", consult);
////                String first = name + ",您好!您有1条";;
//                if (consultTeam.getType() == 8) {
////                    first += "续方";
//                    first = first.replace("key2", "续方");
//                } else {
//                    first = first.replace("key2", "");
//                }
//                /*if (endOperator.equals("admin")) {
//                    first += "咨询超时未回复,系统自动关闭,请及时对咨询医生进行评价。";
//                }else {
//                    first += "咨询已结束,请及时对咨询医生进行评价。";
//                }*/
//                json.put("first", first);
//                if (StringUtils.isNotBlank(p.getOpenid())) {
//                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, openId, p.getName(), json);
//                } else {
//                    //发送代理人
//                    JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(), p.getOpenid());
//                    if (jsonArray != null && jsonArray.length() > 0) {
//                        for (int i = 0; i < jsonArray.length(); i++) {
//                            JSONObject j = jsonArray.getJSONObject(i);
//                            Patient member = (Patient) j.get("member");
//                            JSONObject data = json;
//                            data.remove("toUser");
//                            data.put("toUser", member.getCode());
//                            data.remove("first");
//                            data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
//                            pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, member.getOpenid(), p.getName(), data);
//                        }
//                    }
//                }
//
//            }
//        }
//
//        consultTeam.setEndMsgId(obj.getString("id"));
//        cons.setEndTime(new Date());
//        consultTeam.setEndTime(new Date());
//        consultTeam.setStatus(1);
//        consultDao.save(cons);
//        consultTeamDao.save(consultTeam);
//
//        //结束医生求组的记录
//        endConsultHelp(consult);
//        return 1;
//    }
    /**
     * 新增名医咨询
     * type  1患者 2医生
     * agent 代理人
     */
//    public JSONObject famousConsult(ConsultTeam ct, String uid, String type, String agent) throws Exception {
//        // 设置患者信息
//        agent = uid.equals(agent) ? null : agent;
//        ct.setPatient(uid);
//        String senderId = "";
//        String senderName = "";
//        if ("1".equals(type)) {
//            // 查询患者信息
//            Patient tempPatient = patientDao.findByCode(uid);
//            // 设置患者姓名
//            ct.setName(tempPatient.getName());
//            // 设置患者生日
//            ct.setBirthday(tempPatient.getBirthday());
//            //新增性别
//            ct.setSex(tempPatient.getSex());
//            // 设置患者头像
//            ct.setPhoto(tempPatient.getPhoto());
//
//            senderId = tempPatient.getCode();
//
//            senderName = tempPatient.getName();
//
//        } else if ("2".equals(type)) {
//            Doctor doctorTemp = doctorDao.findByCode(uid);
//            // 设置医生姓名
//            ct.setName(doctorTemp.getName());
//            // 设置医生生日
//            ct.setBirthday(doctorTemp.getBirthday());
//            //新增性别
//            ct.setSex(doctorTemp.getSex());
//            // 设置医生头像
//            ct.setPhoto(doctorTemp.getPhoto());
//
//            senderId = doctorTemp.getCode();
//
//            senderName = doctorTemp.getName();
//        }
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 患者未读数量为0
//        ct.setPatientRead(0);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        // 添加咨询转发记录
//        ConsultTeamDoctor cd = new ConsultTeamDoctor();
//        cd.setConsult(consult.getCode());
//        cd.setDel("1");
//        cd.setCzrq(new Date());
//        cd.setTo(ct.getDoctor());
//        // 添加医生咨询日志
//        String content = addLogs(ct);
//        //推送给IM文字消息
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put(ct.getPatient(), 0);
//        jsonObject.put(ct.getDoctor(), 0);
//
//        JSONObject messages = ImUtill.getCreateTopicMessage(senderId, senderName, senderName + "发起咨询", content, ct.getImages(), agent);
//
//        JSONObject obj = ImUtill.createTopics(null, consult.getCode(), consult.getSymptoms(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
//        if (obj == null) {
//            throw new ServiceException("im消息创建异常!");
//        }
//        if (obj.getInt("status") == -1) {
//            throw new ServiceException(obj.getString("message"));
//        }
//        //设置消息ID
//        ct.setStartMsgId(obj.getString("start_msg_id"));
//        JSONObject object = ImUtill.getTopic(ct.getConsult());
//        JSONArray array = new JSONArray(object.get("data").toString());
//        consultTeamDao.save(ct);  // 保存医生咨询信息
//        consultTeamDoctorDao.save(cd);
//        consultDao.save(consult);
//        if (array.length() == 0) {
//            //由于IM是异步操作,会话生成后,可能还未生成到数据库导致无法
//            //获取会话ID。休眠1秒后继续获取相应信息
//            // PS:可以通过前端请求两次去解决,由于离职,就不挖坑了,后来者可以改善、
//            Thread.sleep(1000);
//            object = ImUtill.getTopic(ct.getConsult());
//            array = new JSONArray(object.get("data").toString());
//        }
//        return array.getJSONObject(0);
//    }
//    @Override
//    public void sendMucMessageBySingnType(String doctor, String doctorName, String patient, String content, String contentType, String title) {
//        super.sendMucMessageBySingnType(doctor, doctorName, patient, content, contentType, title);
//    }
    //过滤非本次咨询专科医生
//    public void removeSpecialist(JSONObject jsonObject, String uid, String consult) {
//        JSONArray j = jsonObject.getJSONArray("users");
//        List<Integer> indexs = new ArrayList<>();
//        List<ConsultHelp> helpList = consultHelpDao.findConsult(consult);
//        Map<String, String> speMap = helpList.stream().collect(Collectors.toMap(ConsultHelp::getSpecialist, ConsultHelp::getSpecialist));
//        SignFamily signFamily = signFamilyDao.findByPatient(uid);
//        if (signFamily != null) {
//            speMap.put(signFamily.getDoctor(), "1");
//            if (StringUtils.isNotBlank(signFamily.getDoctorHealth())) {
//                speMap.put(signFamily.getDoctorHealth(), "1");
//            }
//        }
//        if (j != null && j.length() > 0) {
//            for (int i = 0; i < j.length(); i++) {
//                JSONObject doctor = (JSONObject) j.get(i);
//                String code = (String) doctor.get("id");
//                if (!speMap.containsKey(code)) {
//                    j.remove(i);
//                }
//            }
//        }
//    }
//    public void removeRenewPerson(JSONObject jsonObject, String uid) {
//        JSONArray j = jsonObject.getJSONArray("users");
//        List<Integer> indexs = new ArrayList<>();
//        if (j != null && j.length() > 0) {
//            for (int i = 0; i < j.length(); i++) {
//                JSONObject doctor = (JSONObject) j.get(i);
//                String code = (String) doctor.get("id");
//                String SQL = "SELECT t.id FROM wlyy_sign_family_renew t " +
//                        " WHERE (t.doctor ='" + code + "' OR t.doctor_health ='" + code + "' ) " +
//                        " AND t.sign_year ='" + DateUtil.getSignYear() + "' AND t.patient ='" + uid + "' ";
//
//                String SQL2 = "SELECT t.id FROM wlyy_sign_family t " +
//                        " WHERE (t.doctor ='" + code + "' OR t.doctor_health ='" + code + "' ) " +
//                        " AND t.sign_year ='" + (DateUtil.getSignYear() - 1) + "' AND t.patient ='" + uid + "' AND t.status>0 AND t.expenses_status ='1' ";
//                List<Map<String, Object>> isExits = jdbcTemplate.queryForList(SQL);
//                List<Map<String, Object>> isExitsSign = jdbcTemplate.queryForList(SQL2);
//                if (isExitsSign == null) {
//                    if (isExits != null && isExits.size() > 0) {
//                        indexs.add(i);
//                    }
//                }
//            }
//            if (indexs != null && indexs.size() > 0) {
//                for (Integer index : indexs) {
//                    j.remove(index);
//                }
//            }
//        }
//    }
//    public void removeRenewPerson(JSONArray j, String uid) {
//        List<Integer> indexs = new ArrayList<>();
//        if (j != null && j.length() > 0) {
//            for (int i = 0; i < j.length(); i++) {
//                JSONObject doctor = (JSONObject) j.get(i);
//                String code = (String) doctor.get("id");
//                String SQL = "SELECT t.id FROM wlyy_sign_family_renew t " +
//                        " WHERE (t.doctor ='" + code + "' OR t.doctor_health ='" + code + "' ) " +
//                        " AND t.sign_year ='" + DateUtil.getSignYear() + "' AND t.patient ='" + uid + "' ";
//
//                String SQL2 = "SELECT t.id FROM wlyy_sign_family t " +
//                        " WHERE (t.doctor ='" + code + "' OR t.doctor_health ='" + code + "' ) " +
//                        " AND t.sign_year ='" + (DateUtil.getSignYear() - 1) + "' AND t.patient ='" + uid + "' AND t.status>0 AND t.expenses_status ='1' ";
//                List<Map<String, Object>> isExits = jdbcTemplate.queryForList(SQL);
//                List<Map<String, Object>> isExitsSign = jdbcTemplate.queryForList(SQL2);
//                if (isExitsSign == null) {
//                    if (isExits != null && isExits.size() > 0) {
//                        indexs.add(i);
//                    }
//                }
//            }
//            if (indexs != null && indexs.size() > 0) {
//                for (Integer index : indexs) {
//                    j.remove(index);
//                }
//            }
//        }
//    }
    /**
     * 医生发送血糖血压快捷回复咨询
     */
//    public void addPrescriptionBloodStatusConsult(String prescriptionCode, String type, String followupid) throws Exception {
//
//        if ("1".equals(type)) {//血压
//            prescriptionFollowupContentService.importPatientBloodPressureToFollowup(prescriptionCode, followupid, true, "");
//        } else if ("2".equals(type)) {//血糖
//            prescriptionFollowupContentService.importPatientBloodSugarToFollowup(prescriptionCode, followupid, true, "");
//        }
//
//    }
    /**
     * 医生发送症状、体征及生活方式回复咨询
     */
//    public void addPrescriptionFollowupContentConsult(String prescriptionCode, String type, String followupid) throws Exception {
//        Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
//        org.json.JSONObject contentobj = new org.json.JSONObject();
//        //医生发送的消息
//        if ("1".equals(type)) {
//            contentobj.put("text", "请填写您近期身体异常症状问卷");
//        } else {
//            contentobj.put("text", "请填写您近期体征及生活方式调查问卷");
//        }
//        contentobj.put("doctorremind", "已向居民发送问卷填写请求,填写完成后您将收到消息提醒");
//        contentobj.put("patientremind", "填写完成并提交后,医生将可以查看您的问卷内容");
//        contentobj.put("msgType", type);
//        contentobj.put("isSendWxTemplate", true);//是否发送咨询回复的微信模板
//        //医生发送Im消息
//        ImUtil.sendTopicIM(prescription.getDoctor(), prescription.getDoctorName(), prescription.getConsult(), "17", contentobj.toString(), null);
//    }
    /**
     * 根据续方code获取咨询
     */
    public ConsultTeamDo getConsultStatus(String prescriptionCode) {
        //先注释掉
//        WlyyPrescriptionDO prescription = prescriptionDao.findByCode(prescriptionCode);
//        if (prescription != null) {
//            return consultTeamDao.findByConsult(prescription.getConsult());
//        }
        return null;
    }
    /**
     * pcim 使用
@ -3085,31 +233,6 @@ public class ConsultTeamService extends ConsultService {
        return re;
    }
    /**
     * 根据居民code获取剩余家庭咨询次数
     */
//    public JSONObject countRemainConsult(String patient) {
//        JSONObject json = new JSONObject();
//        try {
//            String consultTimes = systemDictDao.findByDictNameAndCode("CONSULT_TIMES", "1.4.2");
//            int count = Integer.parseInt(consultTimes);
//            json.put("count", count);
//            SignFamily signFamily = signFamilyDao.findByjiatingPatient(patient);
//            if (signFamily == null) {
//                return json;
//            }
//            int amount = consultTeamDao.countRemainConsult(patient, 2, signFamily.getBegin(), signFamily.getEnd());
//            amount = count - amount;
//            if (amount < 0) {
//                amount = 0;
//            }
//            json.put("amount", amount);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return json;
//    }
    /**
     * 返回json
     */
@ -3151,21 +274,6 @@ public class ConsultTeamService extends ConsultService {
        return re.toString();
    }
    //判断居民家庭医生专科是否有共管关系
    public int getSpecialDoctorFamilyDoctorPatientCount(String patient, String special_doctor, String family_doctor) {
        String sql = "SELECT " +
                "count(a.id) FROM wlyy_specialist_patient_relation a " +
                "JOIN wlyy.wlyy_sign_family b " +
                "ON a.patient=b.patient " +
                "AND b.`status`=1 " +
                "WHERE a.sign_status> 0 " +
                "AND a.`status`>=0 " +
                "AND a.doctor='" + special_doctor + "' " +
                "AND (b.doctor='" + family_doctor + "' or b.doctor_health='" + family_doctor + "')" +
                "AND a.patient='" + patient + "'";
        int count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }
    /**
     * 添加在线复诊咨询
@ -3304,32 +412,6 @@ public class ConsultTeamService extends ConsultService {
//        }
//    }
    /**
     * 保存审核提醒消息
     */
//    public void addExaminationCheckMessage(Examination examination, String sessionId, BasePatientDO p) {
//        SystemMessageDO message = new SystemMessageDO();
//        message.setCreateTime(new Date());
//        message.setCreateTime(new Date());
//        message.setIsRead("1");//设置未读
//        message.setOver("1");
//        message.setSenderPhoto(p.getPhoto());
//        message.setReceiver(examination.getDoctor());
//        message.setSender(examination.getPatient());
//        message.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
//        message.setSenderName(examination.getPatientName());
//        message.setTitle(examination.getPatientName() + "申请在线复诊");
//        message.setContent("您有一条新的续方申请待处理!");
//        message.setType(31);//在线复诊咨询待审核提醒
//        message.setReadonly(1);//是否只读消息
//        message.setDel("1");
//        message.setRelationCode(examination.getConsult());
//        message.setPrescriptionStatus("0");
//        message.setSessionId(sessionId);
//        message.setSessionName(examination.getPatientName());
//        messageDao.save(message);
//    }
    /**
     * 根据关联业务code查询咨询记录 wlyyDoorServiceOrderService.queryOneDetail(consult.getRelationCode());
@ -3352,9 +434,6 @@ public class ConsultTeamService extends ConsultService {
        }
        //这是id
        ConsultDo consult = consultDao.queryByIdAndType(code, type);
//        ConsultDo consult = consultDao.findByRelationCode(code);
        if (null == consult) {
            result.put("data", "");
            return result;
@ -3389,108 +468,4 @@ public class ConsultTeamService extends ConsultService {
        return new org.json.JSONObject(response);
    }
//    public JSONObject addTeamSpecialConsult(ConsultTeam ct, String patientCode, String agent, String specialDoctorCode, String doctorCode) throws Exception {
//        JSONObject re = new JSONObject();
////        if (exist(patientCode, ct.getType())) {//判断是否有未结束的咨询移到同步方法中
////            re.put("status", -3);
////            return re;
////        }
//
//        JSONObject users = new JSONObject();
//
//        if (patientCode.equals(agent)) {
//            agent = null;
//        }
//
//        users.put(doctorCode, 0);
//        users.put(specialDoctorCode, 0);
//
//        // 设置患者信息
//        ct.setPatient(patientCode);
//        // 查询患者信息
//        Patient tempPatient = patientDao.findByCode(patientCode);
//        // 设置患者姓名
//        ct.setName(tempPatient.getName());
//        // 设置患者生日
//        ct.setBirthday(tempPatient.getBirthday());
//        //新增性别
//        ct.setSex(tempPatient.getSex());
//        // 设置患者头像
//        ct.setPhoto(tempPatient.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        ct.setEvaluate(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), tempPatient.getName() + "康复咨询", ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置关联指导
//        consult.setGuidance(ct.getGuidance());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        ct.setDoctor(doctorCode);
//
//        //推送给IM去创建议题,取得成员消息
//        JSONObject messages = ImUtill.getCreateTopicMessage(patientCode, tempPatient.getName(), consult.getTitle(), consult.getSymptoms(), consult.getImages(), agent);
//        users.put(patientCode, 0);
//        JSONObject obj = ImUtill.createTopics(patientCode + "_" + doctorCode + "_" + specialDoctorCode + "_" + ct.getType(), consult.getCode(), tempPatient.getName(), users, messages, ImUtill.SESSION_TYPE_KANGFU);
//        if (obj == null) {
//            throw new ServiceException("IM消息发送异常!");
//        }
//        if (obj.getInt("status") == -1) {//im议题创建失败
//            throw new ServiceException(obj.getString("message"));
//        }
//        ct.setStartMsgId(obj.get("start_msg_id").toString());
//        consultTeamDao.save(ct);
//        consultDao.save(consult);
//
//        JSONArray doctor = new JSONArray();
//        for (String key : users.keySet()) {
//            if (patientCode.equals(key)) {
//                continue;
//            }
//            doctor.put(key);
//            //记录咨询的医生详情误删
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(key);
//            consultTeamDoctorDao.save(cd);
//        }
//
//        // 保存医生咨询信息
//        // 添加咨询转发记录
//        // 添加医生咨询日志
//        String content = addLogs(ct);
//        re.put("doctor", doctor);
//        re.put("status", 1);
//        return re;
//    }
//    public JSONObject getConsultDoctorForConsulting(String patientCode) {
//        JSONObject result = new JSONObject();
//        String sql = "SELECT DISTINCT p.patient, p.name AS patient_name, p.`team_code`,te.`name` AS team_name, d.`code` as special_code, d.`name` as special_name, d.dept_name,d.hospital_name \n" +
//                "FROM wlyy_patient_rehabilitation_plan p, wlyy_doctor d ,wlyy_admin_team te\n" +
//                "WHERE p.patient = '" + patientCode + "' AND d.`code`= p.create_user and te.id = p.team_code AND te.available=1 GROUP BY p.patient, p.create_user,p.team_code";
//        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName2(sql);
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
//        result.put("ConsultTeamList", list);
//        //家庭医生
//        SignFamily sf = signFamilyDao.findByjiatingPatient(patientCode);
//        if (StringUtils.isNoneBlank(sf.getDoctor())) {
//            result.put("doctor", sf.getDoctor());
//            result.put("doctorName", sf.getDoctorName());
//        }
//        if (StringUtils.isNoneBlank(sf.getDoctorHealth())) {
//            result.put("doctorHealth", sf.getDoctorHealth());
//            result.put("doctorHealthName", sf.getDoctorHealthName());
//        }
//        return result;
//    }
}

+ 14 - 12
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoorOrderController.java

@ -62,19 +62,21 @@ public class DoorOrderController extends EnvelopRestEndpoint {
    @Autowired
    JdbcTemplate jdbcTemplate;
//    @Autowired
//    private ZyDictService zyDictService;
//    @Autowired
//    private JwDoorPrescriptionService jwDoorPrescriptionService;
//    @Autowired
//    private FamilyContractService familyContractService;
//    @Autowired
//    private ServerPackageService serverPackageService;
//    @Autowired
//    private ServiceItemService serviceItemService;
//    @Autowired
//    private HospitalService hospitalService;
    @GetMapping(value = "getOgrById")
    @ApiOperation(value = "服务人员列表(医生列表)")
    public Envelop getOgrById(
            @ApiParam(name = "name", value = "医生姓名") @RequestParam(value = "name", required = false) String name,
            @ApiParam(name = "page", value = "第几页",required = true) @RequestParam(value = "page", required = true) Integer page,
            @ApiParam(name = "size", value = "分页大小",required = true) @RequestParam(value = "size", required = true) Integer size) {
        try {
            List<Map<String, Object>> list = wlyyDoorServiceOrderService.findDoctorList(name,page,size);
            return success("查询成功", list);
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("获取失败");
        }
    }
    /**
     * 获取登录医生的信息

+ 8 - 6
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/ServiceItemPlanDao.java

@ -15,13 +15,15 @@ import java.util.List;
 */
public interface ServiceItemPlanDao extends PagingAndSortingRepository<ServiceItemPlanDO, String>, JpaSpecificationExecutor<ServiceItemPlanDO> {
    @Query("from ServiceItemPlanDO w where w.signId =?1 ")
    List<ServiceItemPlanDO> findBySignId(String signId);
    @Query("from ServiceItemPlanDO w where w.planId =?1 ")
    List<ServiceItemPlanDO> findByPlanId(String planId);
    @Query(value = "select * from base_service_item_plan w where w.sign_id =?1 and w.service_item_id=?2 order by w.plan_time desc", nativeQuery = true)
    List<ServiceItemPlanDO> findBySignIdAndServiceItemId(String signId, String serviceItemId);
    ServiceItemPlanDO findByRelationCodeAndRelationType(String relationCode,String relationType);
    @Query("from ServiceItemPlanDO w where w.planDetailId =?1 and w.status=?2")
    List<ServiceItemPlanDO> findByPlanDetailId(String planDetailId,String status);
    @Modifying
    @Query(value ="UPDATE  base_service_item_plan SET status='1' ,complete_time=?3 WHERE status='0' AND sign_id=?1 AND service_pack_id=?2 ORDER BY plan_time DESC LIMIT 1", nativeQuery = true)
    void updateState(String signId, String packageId, Date date);
    @Query(value ="UPDATE  base_service_item_plan SET status='1' ,complete_time=?3 WHERE status='0' AND plan_id=?1 AND plan_detail_id=?2 ORDER BY plan_time DESC LIMIT 1", nativeQuery = true)
    void updateState(String planId, String planDetailId, Date date);
}

+ 13 - 67
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/DoorOrderService.java

@ -67,10 +67,6 @@ public class DoorOrderService {
    @Autowired
    private HttpClientUtil httpClientUtil;
    //    @Value("${sign.check_upload}")
    private String jwUrl;
    //    @Value("${server.server_url}")
    private String wxServerUrl;
    //图片服务地址
    @Value("${fastDFS.fastdfs_file_url}")
    private String imgUrlDomain;
@ -99,7 +95,6 @@ public class DoorOrderService {
    @Autowired
    private DoorServiceVoucherDao doorServiceVoucherDao;
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
@ -110,7 +105,6 @@ public class DoorOrderService {
    @Autowired
    private DoctorRegistrationTempService templateService;
    @Autowired
    private WlyyDoorPrescriptionDao doorPrescriptionDao;
    @Autowired
@ -123,10 +117,6 @@ public class DoorOrderService {
    @Autowired
    private WxTemplateConfigDao wxTemplateConfigDao;
    //    @Autowired
//    private HttpUtil httpUtil;
    @Autowired
    private WlyyDoorCommentDao doorCommentDao;
    @Autowired
    private PushMsgTask pushMsgTask;
@ -140,39 +130,19 @@ public class DoorOrderService {
    /**
     * 服务项查询
     *
     * @param signId 签约id
     * @param type   doorService 上门服务
     * type =4
     */
    public PageEnvelop getServiceItem(String signId, String name, String type, Integer page, Integer size) {
//        String sql = "SELECT si.* ";
//        String countSql = "select count(si.id) ";
//        String filter = " from base_service_package_sign_record r," +
//                "base_service_package_item i,base_service_package_sub_item si,base_service_package_item_relational ir " +
//                "WHERE r.id = '"+signId+"' and i.service_package_id=r.service_package_id and i.`code`='"+type+"' and si.status='1' " +
//                " and i.id = ir.item_id and ir.sub_item_id= si.id ";
//        if(StringUtils.isNotBlank(name)){
//            filter += " and si.name like '%"+name+"%' ";
//        }
//        String oderBy = " order by si.sort limit "+(page-1)*size+","+size;
        String sql = "SELECT e.* ";
        String countSql = "select count(e.id) ";
        String filter =
                "FROM\n" +
                        "	base_service_package_sign_record a \n" +
                        "	INNER JOIN base_service_package_item b ON a.service_package_id = b.service_package_id\n" +
                        "	INNER JOIN base_service_package_item c ON c.id=b.service_package_item_id\n" +
                        "	INNER JOIN base_service_package_item_relational d ON d.item_id=c.id \n" +
                        "	INNER JOIN base_service_package_sub_item e ON e.id=d.sub_item_id\n" +
                        "WHERE 1=1\n" +
                        "	AND b.`code` = '" + type + "' \n" +
                        "	AND e.`status` = '1' \n" +
                        "	AND a.id = '" + signId + "' ";
    public PageEnvelop getServiceItem(String name, String type, Integer page, Integer size) {
        String sql = "SELECT a.* ";
        String countSql = "select count(a.id) ";
        String filter = "FROM " +
                        "	base_service_package_sub_item a " +
                        "WHERE a.dict_item_id = '" + type + "' \n" +
                        "	AND a.`status` = '1' ";
        if (StringUtils.isNotBlank(name)) {
            filter += " and e.name like '%" + name + "%' ";
            filter += " and a.name like '%" + name + "%' ";
        }
        String oderBy = " order by e.sort limit " + (page - 1) * size + "," + size;
        String oderBy = " order by a.sort limit " + (page - 1) * size + "," + size;
        sql = sql + filter + oderBy;
        countSql = countSql + filter;
@ -1398,11 +1368,11 @@ public class DoorOrderService {
        doorServiceOrderDao.save(one);
        //
        String signId = one.getSignId();//签约id
        String packageId = one.getPackageId();//服务包id
        String planId = one.getPlanId();//计划id
        String planItemDetailId = one.getPlanItemDetailId();//计划服务项id
        Date date = new Date();
        //更新计划状态为完成
        serviceItemPlanDao.updateState(signId, packageId, date);
        serviceItemPlanDao.updateState(planId, planItemDetailId, date);
        WlyyDoorServiceOrderDO doorServiceOrderDO = this.getDoorServiceOrderById(orderId, level);
@ -2346,30 +2316,6 @@ public class DoorOrderService {
        return list;
    }
    public JSONObject getAllDoorOrder(String idCard, String doctorSignTime) throws Exception {
        if (StringUtils.isEmpty(idCard)) {
            idCard = "";
        }
        if (StringUtils.isEmpty(doctorSignTime)) {
            doctorSignTime = "";
        }
        JSONObject object = new JSONObject();
        String url = jwUrl + "/third/allDoor/getAllDoorOrder?idCard=" + idCard + "&doctorSignTime=" + doctorSignTime;
        String response = httpClientUtil.get(url, "UTF-8");
        if (!org.apache.commons.lang3.StringUtils.isEmpty(response)) {
            org.json.JSONObject jsonObject = new org.json.JSONObject(response);
            int status = jsonObject.getInt("status");
            if (status == 200) {
                object = JSONObject.parseObject(response);
            } else {
                throw new Exception(jsonObject.getString("msg"));
            }
        } else {
            throw new Exception("null response.");
        }
        return object;
    }
//    /**
//     * 导出咨询未及时回复数据

+ 24 - 132
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorServiceOrderService.java

@ -9,7 +9,6 @@ import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.door.*;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.file_upload.FileUploadService;
@ -653,10 +652,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                "	1 = 1 \n" +
                "	AND t.`code` = 'dispatcher' \n";
//        if (StringUtils.isNotBlank(hospitalCode)) {
//            sql += " AND a.org_code = '" + hospitalCode + "' \n";
//        }
        List<Map<String, Object>> dispatcherInfoList = jdbcTemplate.queryForList(sql);
        return dispatcherInfoList;
    }
@ -700,7 +695,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            orderDO.setStatus(1);//待派单(调度员)
        }
        if (StringUtils.isEmpty(orderDO.getPatient())) {
            throw new Exception("当前服务对象code为空,请联系管理员检查参数!patient = " + orderDO.getPatient());
        }
@ -762,71 +756,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        boolean flag = true;
        JSONObject result = new JSONObject();
//        //创建订单信息
//        BasePatientDO pateint = patientDao.findById(orderDO.getPatient());
//        //查询是否存在订单信息
//        BusinessOrderDO businessOrderDO = businessOrderDao.findByOrderId(orderDO.getId());
//        if (businessOrderDO == null) {
//            businessOrderDO = new BusinessOrderDO();
//            businessOrderDO.setPatient(pateint.getId());
//            //支付账号
//            businessOrderDO.setYkOrderId(pateint.getMobile());
//            businessOrderDO.setPatientName(pateint.getName());
//            businessOrderDO.setOrderType(1);
//            businessOrderDO.setOrderCategory(type);
//            Date date = new Date();
//            Long lastPayTime = date.getTime() + 1000 * 60 * 30;//订单截至支付日期
//            businessOrderDO.setDescription("上门服务");
//            businessOrderDO.setRelationCode(orderDO.getId());//订单id
//            businessOrderDO.setRelationName("上门服务");
//            businessOrderDO.setCreateTime(date);
//            businessOrderDO.setUpdateTime(date);
//            businessOrderDO.setStatus(0);
//            businessOrderDO.setOrderNo(orderDO.getNumber());
//            businessOrderDO.setUploadStatus(0);
//            businessOrderDO.setPayType(1);
//            businessOrderDO.setPayPrice(Double.valueOf(orderDO.getTotalFee().doubleValue()));
//            businessOrderDO.setLastPayTime(lastPayTime);
//        } else {
//            /**
//             * 暂时没用,线下付款的
//             * 1、是否付款完成
//             * 2、判断付款时间是否超过时长了--还需要定时任务监听订单修改状态,把未付款改成已取消
//             */
////            if (businessOrderDO.getStatus() != 1) {
////                long nowTime = System.currentTimeMillis();
////                Long lastPayTime = businessOrderDO.getLastPayTime();
////                if (lastPayTime > nowTime) {
////                    //超时了 修改工单状态成已取消
////                    orderDO.setStatus(-1);//-已取消
////                    wlyyDoorServiceOrderDao.saveAll(orderDO);//更新上门工单
////                    businessOrderDO.setStatus(2);//已取消
////                    businessOrderDao.saveAll(businessOrderDO);//更新业务表
////                    flag = false;//不用创建咨询内容
////                }
////            }
//        }
        /**
         *  1、费用0时无需支付
         *  2、调用微信支付 再来更新flag标识
         */
//        if ("5".equals(type) && 0.0 == orderDO.getTotalFee().doubleValue()) {
//            businessOrderDO.setStatus(1);//1已支付
//            businessOrderDao.saveAll(businessOrderDO);
//        } else {
//            /**
//             * 保存订单信息-这边要判断付款回调修改状态值-付款失败取消订单
//             * businessOrderService
//             */
//            businessOrderDO.setStatus(0);//0待支付
//            businessOrderDao.saveAll(businessOrderDO);
//        }
        //保存业务表
//        businessOrderDao.saveAll(businessOrderDO);
        /**
         * 目前是线下付款的
         * 给出标识是否成功,往下面创建咨询信息发送内容
@ -839,12 +768,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            JSONObject successOrNot = consultTeamService.addDoorServiceConsult(orderDO.getId());
            ConsultTeamDo consultTeam = (ConsultTeamDo) successOrNot.get(ResponseContant.resultMsg);
            System.out.println("===调度员的信息开始======");
            for (Map<String, Object> map : dispatcherList) {
                System.out.println("调度员=>" + JSON.toJSONString(map));
            }
            System.out.println("===调度员的信息结束======");
            //判断其是否有分配执行人。如果有不用走调度平台
            if (StringUtils.isNotBlank(orderDO.getDoctor())) {
                orderDO.setStatus(2);//待接单
@ -891,22 +814,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            int flagCount = qucikSendIM(orderDO.getId(), "system", "智能助手", "2101", orderInfoContent.toJSONString());
            System.out.println("flagCount==>" + flagCount);
            //模拟一,重试3次
//            int tryCount = 3;
//            int flagCount = 0;
//            for (int i = 0; i < tryCount; i++) {
//                //发送消息
//                flagCount = qucikSendIM(orderDO.getId(), "system", "智能助手", "2101", orderInfoContent.toJSONString());
//                if (flagCount == 1) {
//                    break;
//                }
//            }
//            //模式2,睡眠1秒钟
//            Thread.sleep(1000);
//            flagCount = qucikSendIM(orderDO.getId(), "system", "智能助手", "2101", orderInfoContent.toJSONString());
            //后面这个要修改下,加个字段判断下是否转派
            if (StringUtils.isNoneBlank(orderDO.getDoctor())) {
                //服务医生修改,直接转派
@ -1404,7 +1311,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                "  ifnull(de.order_id,concat(rand(),'_notExist')) AS feeOrderId, " +
                "  a.mobile AS hospitalPhone, " +
                "  count(de.number) as itemCount ," +
                "  o.sign_id 'signId' , o.package_id 'packageId' " +
                "  o.plan_id 'planId' , o.plan_item_detail_id 'planItemDetailId' " +
                " FROM " +
                "  ( wlyy_door_service_order o " +
                " LEFT JOIN base_doctor d ON o.doctor = d.`id`) " +
@ -1668,20 +1575,20 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        // 发送微信模板消息,通知居民工单已取消(smyyyqx-上门预约已取消)
        BasePatientDO patient = patientService.findPatientById(orderDO.getPatient());
        WxTemplateConfigDO templateConfig = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndScene("xm_test_ihealth_wx", "template_process_feedback", "smyyyqx");
        String first = templateConfig.getFirst().replace("key1", null != patient.getName() ? patient.getName() : "");
        org.json.JSONObject json = new org.json.JSONObject();
        json.put("first", first);
        json.put("keyword1", DateUtil.dateToStrShort(new Date()));
        json.put("keyword2", "上门预约已取消");
        json.put("url", templateConfig.getUrl());
        json.put("remark", templateConfig.getRemark());
        if (consult != null) {
            json.put("consult", consult.getId());
        } else {
            json.put("id", orderDO.getId());
        }
        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 30, patient.getOpenid(), patient.getName(), json);
//        WxTemplateConfigDO templateConfig = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndScene("xm_test_ihealth_wx", "template_process_feedback", "smyyyqx");
//        String first = templateConfig.getFirst().replace("key1", null != patient.getName() ? patient.getName() : "");
//        org.json.JSONObject json = new org.json.JSONObject();
//        json.put("first", first);
//        json.put("keyword1", DateUtil.dateToStrShort(new Date()));
//        json.put("keyword2", "上门预约已取消");
//        json.put("url", templateConfig.getUrl());
//        json.put("remark", templateConfig.getRemark());
//        if (consult != null) {
//            json.put("consult", consult.getId());
//        } else {
//            json.put("id", orderDO.getId());
//        }
//        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 30, patient.getOpenid(), patient.getName(), json);
        // 工单状态变更记录
        WlyyDoorProcessLogDO processLogDO = new WlyyDoorProcessLogDO();
@ -3122,29 +3029,14 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
    }
    public List<Map<String, Object>> getOgrById(String signId, String orderId) {
        String sql = "";
        if (StringUtils.isNotBlank(signId)) {
            sql = "SELECT\n" +
                    "	b.* \n" +
                    "FROM\n" +
                    "	base_service_package_sign_record a\n" +
                    "	INNER JOIN base_service_package_item b ON a.service_package_id = b.service_package_id\n" +
                    "	AND a.id='" + signId + "'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            return list;
        }
        if (StringUtils.isNotBlank(orderId)) {
            sql = "SELECT\n" +
                    "	DISTINCT b.* \n" +
                    "FROM\n" +
                    "	base_service_package_sign_record a\n" +
                    "	INNER JOIN wlyy_door_service_order b ON a.service_package_id=b.package_id\n" +
                    "	INNER JOIN base_service_package_item c ON b.package_id = c.service_package_id\n" +
                    "	AND b.id='" + orderId + "'\n";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            return list;
        }
        return null;
    //获取医生列表
    public List<Map<String, Object>> findDoctorList(String name,Integer page,Integer size) {
        String sql = "select id,name from base_doctor where del='1' and enabled=1";
        if(StringUtils.isNotBlank(name)){
            sql += " and name like '%"+name+"%'";
        }
        sql+= " limit "+(page-1)*size+","+size;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
}

+ 725 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/controller/DoctorFollowUpController.java

@ -0,0 +1,725 @@
package com.yihu.jw.hospital.module.followup.controller;
import com.yihu.jw.entity.followup.Followup;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.followup.service.FollowUpService;
import com.yihu.jw.hospital.module.followup.service.FollowupDrugsService;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * 医生端:随访接口
 *
 * @author hzp add 2016-12-07
 */
@RestController
@RequestMapping(value = "/doctor/followup")
@Api(description = "医生端-随访接口")
public class DoctorFollowUpController extends BaseController {
    @Autowired
    private FollowUpService followUpService;
    @Autowired
    private FollowupDrugsService followupDrugsService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /*************************************** 随访计划 ****************************************************************************/
    @ApiOperation("获取随访列表")
    @RequestMapping(value = "/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getList(@ApiParam(name = "startTime", value = "开始时间", defaultValue = "2016-12-07 00:00:00")
                          @RequestParam(value = "startTime", required = true) String startTime,
                          @ApiParam(name = "endTime", value = "结束时间", defaultValue = "2016-12-14 00:00:00")
                          @RequestParam(value = "endTime", required = true) String endTime) {
        try {
            List<Map<String, Object>> result = followUpService.getListByDoctor(getUID(), startTime, endTime);     //"64de9952-5b15-11e6-8344-fa163e8aee56"
            return write(200, "获取随访列表成功!", "data", result);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访列表失败!" + e.getMessage());
        }
    }
    /**
     * 查询居民随访列表
     *
     * @param patient
     * @param teamCode
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping(value = "/list_by_team", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询居民随访列表")
    public String getListByPatientAndTeam(@RequestParam @ApiParam(value = "居民Code") String patient,
                                          @RequestParam @ApiParam(value = "医生Code") String doctor,
                                          @RequestParam @ApiParam(value = "团队code") Long teamCode,
                                          @RequestParam @ApiParam(value = "第几页") int page,
                                          @RequestParam @ApiParam(value = "页大小") int pagesize,
                                          @RequestParam(value = "type",required = false) @ApiParam(value = "类型:放空为全部,1计划,2记录",defaultValue = "0") String type) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "请输入需查询的居民");
            }
            if (teamCode == null || teamCode < 1) {
                return error(-1, "请输入需查询的居民的团队");
            }
            page = page > 0 ? page - 1 : 0;
            JSONArray result = followUpService.getListByPatientAndTeam(patient,doctor, teamCode, page, pagesize,type);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    /**
     * 查询居民随访列表
     *
     * @param patient
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping(value = "/list_by", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询居民随访列表")
    public String getListByPatient(@RequestParam @ApiParam(value = "居民Code") String patient,
                                          @RequestParam @ApiParam(value = "第几页") int page,
                                          @RequestParam @ApiParam(value = "页大小") int pagesize,
                                          @RequestParam(value = "type",required = false) @ApiParam(value = "类型:放空为全部,1计划,2记录",defaultValue = "0") String type) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "请输入需查询的居民");
            }
            page = page > 0 ? page - 1 : 0;
            JSONArray result = followUpService.getListByPatient(patient, page, pagesize,type);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @ApiOperation("获取随访列表(创建者)")
    @RequestMapping(value = "/createrList", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getCreaterList(@ApiParam(name = "startTime", value = "开始时间", defaultValue = "2016-12-07 00:00:00")
                                 @RequestParam(value = "startTime", required = true) String startTime,
                                 @ApiParam(name = "endTime", value = "结束时间", defaultValue = "2016-12-14 00:00:00")
                                 @RequestParam(value = "endTime", required = true) String endTime,
                                 @ApiParam(name = "page", value = "第几页", defaultValue = "1")
                                 @RequestParam(value = "page", required = true) String page,
                                 @ApiParam(name = "pageSize", value = "每页几行", defaultValue = "10")
                                 @RequestParam(value = "pageSize", required = true) String pageSize) {
        try {
            List<Map<String, String>> result = followUpService.getListByCreater(getUID(), startTime, endTime, page, pageSize);     //"64de9952-5b15-11e6-8344-fa163e8aee56"
            return write(200, "获取随访列表成功!", "data", result);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访列表失败!" + e.getMessage());
        }
    }
    @ApiOperation("新增随访计划(批量)")
    @RequestMapping(value = "/addFollowupPlan", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String addFollowupPlan(@ApiParam(name = "patient", value = "患者代码", defaultValue = "443a196ef8744536a531260eb26c05d7")
                                  @RequestParam(value = "patient", required = true) String patient,
                                  @ApiParam(name = "data", value = "随访计划列表json", defaultValue = "[{\"date\":\"2016-12-16 20:00:00\",\"type\":\"10\",\"doctor\":\"64de9952-5b15-11e6-8344-fa163e8aee56\"},{\"date\":\"2016-12-17 15:00:00\",\"type\":\"3\",\"doctor\":\"64de9952-5b15-11e6-8344-fa163e8aee56\"}]")
                                  @RequestParam(value = "data", required = true) String data) {
        try {
            Iterable<Followup> followups = followUpService.addFollowupPlan(getUID(), patient, data);
            return write(200, "新增随访计划成功!","data",followups);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "新增随访计划失败!" + e.getMessage());
        }
    }
    @ApiOperation("编辑随访计划")
    @RequestMapping(value = "/editFollowupPlan", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String editFollowupPlan(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                   @RequestParam(value = "id", required = true) String id,
                                   @ApiParam(name = "planDate", value = "随访计划时间", defaultValue = "2016-12-14 20:00:00")
                                   @RequestParam(value = "planDate", required = true) String planDate,
                                   @ApiParam(name = "followupType", value = "随访方式【字典FOLLOWUP_WAY_DICT】", defaultValue = "12")
                                   @RequestParam(value = "followupType", required = true) String followupType) {
        try {
            followUpService.editFollowupPlan(getUID(), id, planDate, followupType);
            return write(200, "编辑随访计划成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "编辑随访计划失败!" + e.getMessage());
        }
    }
    @ApiOperation("开始随访记录")
    @RequestMapping(value = "/startFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String startFollowup(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                @RequestParam(value = "id", required = true) String id,
                                @ApiParam(name = "followupNo", value = "随访记录编码")
                                @RequestParam(value = "followupNo", required = false) String followupNo,
                                @ApiParam(name = "date", value = "随访时间", defaultValue = "2016-12-14 20:00:00")
                                @RequestParam(value = "date", required = true) String date,
                                @ApiParam(name = "followupType", value = "随访方式【字典FOLLOWUP_WAY_DICT】", defaultValue = "12")
                                @RequestParam(value = "followupType", required = true) String followupType,
                                @ApiParam(name = "followupClass", value = "随访类别【1.高血压 2.糖尿病,3高糖】", defaultValue = "1")
                                @RequestParam(value = "followupClass", required = true) String followupClass,
                                @ApiParam(name = "followupManagerStatus", value = "随访管理状态【字典FOLLOWUP_MANAGER_STATUS】", defaultValue = "1")
                                @RequestParam(value = "followupManagerStatus", required = false) String followupManagerStatus,
                                @ApiParam(name = "plandate", value = "下次随访时间", defaultValue = "2016-12-14 20:00:00")
                                @RequestParam(value = "plandate", required = false) String plandate,
                                @ApiParam(name = "prescriptioncode", value = "续方CODE", defaultValue = "")
                                    @RequestParam(value = "prescriptioncode", required = false) String prescriptioncode) {
        try {
            Followup followup = followUpService.startFollowup( id, followupNo, date, followupType, followupClass, followupManagerStatus,plandate,prescriptioncode);
//            followUpService.getNotStartFollowup(getUID(), followup.getFollowupPlanDate());
            return write(200, "开始随访记录成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "开始随访记录失败!" + e.getMessage());
        }
    }
    @ApiOperation("新增临时随访记录(返回ID)")
    @RequestMapping(value = "/addFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String addFollowup(@ApiParam(name = "patient", value = "患者代码", defaultValue = "443a196ef8744536a531260eb26c05d7")
                              @RequestParam(value = "patient", required = true) String patient,
                              @ApiParam(name = "date", value = "下次随访时间", defaultValue = "2016-12-15 20:00:00")
                              @RequestParam(value = "date", required = true) String date,
                              @ApiParam(name = "followupType", value = "随访方式【字典FOLLOWUP_WAY_DICT】", defaultValue = "12")
                              @RequestParam(value = "followupType", required = true) String followupType,
                              @ApiParam(name = "followupClass", value = "随访类别【1.高血压 2.糖尿病 3高糖】", defaultValue = "1")
                              @RequestParam(value = "followupClass", required = true) String followupClass,
                              @ApiParam(name = "followupManagerStatus", value = "随访管理状态【字典FOLLOWUP_MANAGER_STATUS】", defaultValue = "1")
                              @RequestParam(value = "followupManagerStatus", required = false) String followupManagerStatus,
                              @ApiParam(name = "plandate", value = "下次随访时间", defaultValue = "2016-12-14 20:00:00")
                              @RequestParam(value = "plandate", required = false) String plandate,
                              @ApiParam(name = "prescriptioncode", value = "续方CODE", defaultValue = "续方CODE")
                              @RequestParam(value = "prescriptioncode", required = false) String prescriptioncode,
                              @ApiParam(name = "type", value = "随访类型", defaultValue = "0")
                              @RequestParam(value = "type", required = false) Integer type) {
        try {
            String response = followUpService.addFollowup(getUID(), patient, date, followupType, followupClass, followupManagerStatus,plandate,prescriptioncode,type);
            return write(200, "新增临时随访记录成功!", "data", response);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "新增临时随访记录失败!" + e.getMessage());
        }
    }
    @ApiOperation("取消随访计划")
    @RequestMapping(value = "/cancelFollowupPlan", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String cancelFollowupPlan(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                     @RequestParam(value = "id", required = true) String id) {
        try {
            followUpService.cancelFollowupPlan(id);
            return write(200, "取消随访计划成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "取消随访计划失败!" + e.getMessage());
        }
    }
    @ApiOperation("完成随访记录")
    @RequestMapping(value = "/finishFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String finishFollowup(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                 @RequestParam(value = "id", required = true) String id) {
        try {
            followUpService.finishFollowup(id);
            return write(200, "完成随访记录成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "完成随访记录失败!" + e.getMessage());
        }
    }
    /*********************************** 随访详情 *******************************************************************/
    @ApiOperation("获取随访信息")
    @RequestMapping(value = "/getFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getFollowup(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "4")
                              @RequestParam(value = "id", required = true) String id) {
        try {
            Map<String, String> response = followUpService.getFollowup(id);
            try {
                String sql = "UPDATE `wlyy`.`wlyy_followup` SET `doctor_read_status`='1' WHERE (`id`='"+id+"') ";
                jdbcTemplate.update(sql);
            }catch (Exception e){
                e.printStackTrace();
            }
            return write(200, "获取随访信息成功!", "data", response);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访信息失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取随访项目列表")
    @RequestMapping(value = "/getFollowupProject", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getFollowupProject(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "4")
                                     @RequestParam(value = "id", required = true) String id) {
        try {
            List<Map<String, String>> list = followUpService.getFollowupProject(id);
            return write(200, "获取随访项目列表成功!", "data", list);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访项目列表失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取随访项目数据")
    @RequestMapping(value = "/getFollowupProjectData", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getFollowupProjectData(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "4")
                                         @RequestParam(value = "id", required = true) String id,
                                         @ApiParam(name = "followupProject", value = "随访项目")
                                         @RequestParam(value = "followupProject", required = false) String followupProject) {
        try {
            Map<String, String> maps = followUpService.getFollowupProjectData(id, followupProject);
            return write(200, "获取随访项目数据成功!", "data", maps);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "获取随访项目数据失败!");
        }
    }
    @ApiOperation("保存随访项目数据")
    @RequestMapping(value = "/saveFollowupProjectData", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveFollowupProjectData(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "4")
                                          @RequestParam(value = "id", required = true) String id,
                                          @ApiParam(name = "followupProject", value = "随访项目", defaultValue = "2")
                                          @RequestParam(value = "followupProject", required = false) String followupProject,
                                          @ApiParam(name = "followupProjectData", value = "随访项目数据", defaultValue = "{\"BLOOD_SUGAR\":\"33.3\",\"BLOOD_SUGAR_TYPE\":\"1\",\"WEIGHT\":\"76\",\"WEIGHT_EXP\":\"60\",\"BMI\":\"11\"}")
                                          @RequestParam(value = "followupProjectData", required = true) String followupProjectData) {
        try {
            followUpService.saveFollowupProjectData(id, followupProject, followupProjectData);
            return write(200, "保存随访项目数据成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存随访项目数据失败!" + e.getMessage());
        }
    }
    /*********************************** 电话随访 *****************************************************************/
    @ApiOperation("获取电话随访内容")
    @RequestMapping(value = "/getFollowupPhone", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getFollowupPhone(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                   @RequestParam(value = "id", required = true) String id) {
        try {
            String response = followUpService.getFollowupPhone(id);
            return write(200, "获取电话随访内容成功!", "data", response);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取电话随访内容失败!" + e.getMessage());
        }
    }
    @ApiOperation("记录电话随访内容")
    @RequestMapping(value = "/saveFollowupPhone", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveFollowupPhone(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                    @RequestParam(value = "id", required = true) String id,
                                    @ApiParam(name = "content", value = "电话随访内容", defaultValue = "")
                                    @RequestParam(value = "content", required = true) String content) {
        try {
            followUpService.saveFollowupPhone(id, content);
            return write(200, "记录电话随访内容成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "记录电话随访内容失败!" + e.getMessage());
        }
    }
    /*************************************** 上次随访 ********************************************/
    @ApiOperation("获取上次随访")
    @RequestMapping(value = "/getLastFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getLastFollowup(@ApiParam(name = "patient", value = "患者代码", defaultValue = "P20161008001")
                                  @RequestParam(value = "patient", required = true) String patient,
                                  @ApiParam(name = "followClass", value = "随访类别", defaultValue = "1")
                                  @RequestParam(value = "followClass", required = true) String followClass) {
        try {
            Map<String, String> response = followUpService.getLastFollowup(getUID(), patient, followClass);
            return write(200, "获取上次随访成功!", "data", response);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取上次随访失败!" + e.getMessage());
        }
    }
//    @ApiOperation("复制上次随访数据")
//    @RequestMapping(value = "/copyFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
//    public String copyFollowup(@ApiParam(name = "id", value = "本地随访ID", defaultValue = "")
//                               @RequestParam(value = "id", required = true) Long id,
//                               @ApiParam(name = "fromId", value = "拷贝随访记录ID", defaultValue = "")
//                               @RequestParam(value = "fromId", required = true) Long fromId) {
//        try {
//            followUpService.copyFollowup(id, fromId);
//
//            return write(200, "复制上次随访成功!");
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "复制上次随访失败!" + e.getMessage());
//        }
//    }
    /*************************************** 发送随访计划消息 ********************************************/
    @ApiOperation("发送随访计划消息")
    @RequestMapping(value = "/sendMessage", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String sendMessage(@ApiParam(name = "date", value = "日期", defaultValue = "2017-01-05")
                              @RequestParam(value = "date", required = true) String date) {
        try {
            followUpService.sendMessage(date);
            return write(200, "发送随访计划消息成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "发送随访计划消息失败!" + e.getMessage());
        }
    }
    
    
//    @RequestMapping(value = "/checkfollowupcontent", method = RequestMethod.GET)
//    @ApiOperation("检查续方关联的随访记录是否对应的详情记录")
//    public String getfollowupcontent(
//            @ApiParam(name = "followupid", value = "随访ID", defaultValue = "")
//            @RequestParam(value = "followupid", required = true) String followupid,
//            @ApiParam(name = "type", value = "支持传多个以英文逗号连接,drug为药品,1-9为随访分类", defaultValue = "")
//            @RequestParam(value = "type", required = true) String type){
//        try {
//            int count = followUpService.getfollowupcontent(followupid,type);
//            return write(200, "操作成功!","data",count);
//        }catch (Exception e){
//            //日志文件中记录异常信息
//            //返回接口异常信息处理结果
//            return errorResult(e);
//        }
//    }
    
//    @RequestMapping(value = "/checkfollowupcompleted", method = RequestMethod.GET)
//    @ApiOperation("检查续方关联的随访记录是否对应的详情记录")
//    public String checkfollowupcompleted(
//            @ApiParam(name = "followupid", value = "随访ID", defaultValue = "")
//            @RequestParam(value = "followupid", required = true) String followupid){
//        try {
//            boolean completed = followUpService.checkfollowupcompleted(followupid);
//            return write(200, "操作成功!","data",completed);
//        }catch (Exception e){
//            //日志文件中记录异常信息
//            //返回接口异常信息处理结果
//            return errorResult(e);
//        }
//    }
    //=======================1.5.7上门访视相关接口====================================
    @RequestMapping(value = "/findFollowupByMonth",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取访视计划按月日历形式")
    public String findFollowupByMonth(@ApiParam(name = "doctor", value = "医生", defaultValue = "zjm20190214")
                                          @RequestParam(value = "doctor", required = true) String doctor,
                                      @ApiParam(name = "patient", value = "居民")
                                          @RequestParam(value = "patient", required = false) String patient,
                                      @ApiParam(name = "followupClass", value = "随访类别,多类别“,”分割")
                                          @RequestParam(value = "followupClass", required = false) String followupClass,
                                      @ApiParam(name = "patientName", value = "居民姓名")
                                          @RequestParam(value = "patientName", required = false) String patientName,
                                      @ApiParam(value = "开始时间,格式(yyyy-MM-dd)", name = "startDate",required = false)
                                          @RequestParam(value = "startDate", required = false) String startDate,
                                      @ApiParam(value = "结束时间,格式(yyyy-MM-dd)", name = "endDate",required = false)
                                          @RequestParam(value = "endDate", required = false) String endDate,
                                      @ApiParam(name = "flag", value = "区分上门访视(1-是)")
                                          @RequestParam(value = "flag", required = false) String flag,
                                      @ApiParam(name = "type", value = "区分随访计划1、新增随访2、临时随访3、入户随访")
                                          @RequestParam(value = "type", required = false) Integer type,
                                      @ApiParam(name = "status", value = "随访状态")
                                          @RequestParam(value = "status", required = false) String status){
        try {
            return write(200, "操作成功!","data",followUpService.findFollowupByMonth(doctor,patient,followupClass,patientName,startDate,endDate,flag,type,status));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findFollowupList",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取访视列表形式")
    public String findFollowupList(@ApiParam(name = "doctor", value = "医生", defaultValue = "zjm20190214")
                                       @RequestParam(value = "doctor", required = true) String doctor,
                                   @ApiParam(name = "patient", value = "居民")
                                       @RequestParam(value = "patient", required = false) String patient,
                                   @ApiParam(name = "followupClass", value = "随访类别,多类别“,”分割")
                                       @RequestParam(value = "followupClass", required = false) String followupClass,
                                   @ApiParam(name = "patientName", value = "居民姓名")
                                       @RequestParam(value = "patientName", required = false) String patientName,
                                   @ApiParam(value = "开始时间,格式(yyyy-MM-dd)", name = "startDate",required = false)
                                       @RequestParam(value = "startDate", required = false) String startDate,
                                   @ApiParam(value = "结束时间,格式(yyyy-MM-dd)", name = "endDate",required = false)
                                       @RequestParam(value = "endDate", required = false) String endDate,
                                   @ApiParam(name = "flag", value = "区分上门访视(1-是)")
                                       @RequestParam(value = "flag", required = false) String flag,
                                   @ApiParam(name = "type", value = "")
                                       @RequestParam(value = "type", required = false) Integer type,
                                   @ApiParam(name = "status", value = "随访状态")
                                       @RequestParam(value = "status", required = false) String status){
        try {
            return write(200, "操作成功!","data",followUpService.findFollowupList(null,doctor,patient,followupClass,patientName,startDate,endDate,flag,type,status));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findLabelListWithCount",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取随访标签列表带居民数")
    public String findLabelListWithCount(){
        try {
            return write(200, "操作成功!","data",followUpService.findLabelListWithCount());
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findFollowupLabel",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取随访标签列表")
    public String findFollowupLabel(){
        try {
            return write(200, "操作成功!","data",followUpService.findFollowupLabel());
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findFollowUpPatient",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取可随访居民列表")
    public String findFollowUpPatient(@ApiParam(name = "namekey", value = "居民姓名模糊", defaultValue = "")
                                      @RequestParam(value = "namekey", required = false)String namekey,
                                      @ApiParam(name = "labelCode", value = "标签code", defaultValue = "1")
                                      @RequestParam(value = "labelCode", required = false)String labelCode,
                                      @ApiParam(name = "doctor", value = "医生", defaultValue = "zjm20190214")
                                      @RequestParam(value = "doctor", required = true)String doctor,
                                      @ApiParam(name = "page", value = "页数,1开始", defaultValue = "1")
                                      @RequestParam(value = "page", required = true)Integer page,
                                      @ApiParam(name = "size", value = "每页大小", defaultValue = "10")
                                      @RequestParam(value = "size", required = true)Integer size)throws Exception {
        try {
            return write(200, "操作成功!","data",followUpService.findFollowUpPatient(namekey,doctor,labelCode,page,size));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findPatientInfo",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取居民单条信息")
    public String findPatientInfo(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
                                  @RequestParam(value = "patient", required = true)String patient) {
        try {
            return write(200, "操作成功!","data",followUpService.findPatientInfo(patient));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findPatientFollowList",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取居民随访列表")
    public String findPatientFollowList(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
                                        @RequestParam(value = "patient", required = true)String patient,
                                        @ApiParam(name = "doctor", value = "医生code", defaultValue = "")
                                        @RequestParam(value = "doctor", required = true)String doctor){
        try {
            return write(200, "操作成功!","data",followUpService.findPatientFollowList(patient,doctor));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/saveFollowup",produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation("保存随访访视")
    public String saveFollowup(@ApiParam(name = "jsonFollowup", value = "创建访视json", defaultValue = "")
                               @RequestParam(value = "jsonFollowup", required = true)String jsonFollowup){
        try {
            return write(200, "操作成功!","data",followUpService.saveFollowup(jsonFollowup));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/delFollowup",produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation("删除随访访视")
    public String delFollowup(@ApiParam(name = "followupId", value = "随访ID", defaultValue = "")
                               @RequestParam(value = "followupId", required = true)Long followupId)throws Exception {
        try {
            Followup followup = followUpService.delFollowup(followupId);
            followUpService.getNotStartFollowup(getUID(), followup.getFollowupPlanDate());
            return write(200, "操作成功!","data", true);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findFollowupInfo",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取随访详情")
    public String findFollowupInfo(@ApiParam(name = "followupId", value = "随访ID", defaultValue = "")
                                   @RequestParam(value = "followupId", required = true)Long followupId) {
        try {
            return write(200, "操作成功!","data",followUpService.findFollowupInfo(followupId));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/saveFollowupSign",produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation("签到")
    public String saveFollowupSign(@ApiParam(name = "jsonSign", value = "签到", defaultValue = "")
                                   @RequestParam(value = "jsonSign", required = true)String jsonSign)throws Exception {
        try {
            return write(200, "操作成功!","data",followUpService.saveFollowupSign(jsonSign));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/updateFollowupSign",produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation("更新签到")
    public String updateFollowupSign(@ApiParam(name = "jsonSign", value = "签到", defaultValue = "")
                                     @RequestParam(value = "jsonSign", required = true)String jsonSign)throws Exception {
        try {
            return write(200, "操作成功!","data",followUpService.updateFollowupSign(jsonSign));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/urlAnalysis",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("门牌解析上门地址")
    public String urlAnalysis(@ApiParam(name = "url", value = "地址解析", defaultValue = "")
                              @RequestParam(value = "url", required = true)String url)throws Exception {
        try {
            return write(200, "操作成功!","data",followUpService.urlAnalysis(url));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findByFollowupId",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("签约详情")
    public String findByFollowupId(@ApiParam(name = "followupId", value = "签到", defaultValue = "")
                                   @RequestParam(value = "followupId", required = true)Long followupId) {
        try {
            return write(200, "操作成功!","data",followUpService.findByFollowupId(followupId));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/isFirstTimeFollowup",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("判断居民该类别随访是否为第一次")
    public String isFirstTimeFollowup(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
                                      @RequestParam(value = "patient", required = true)String patient,
                                      @ApiParam(name = "followupClass", value = "随访类别", defaultValue = "")
                                      @RequestParam(value = "followupClass", required = true)String followupClass,
                                      @ApiParam(name = "followupId", value = "随访类别", defaultValue = "")
                                      @RequestParam(value = "followupId", required = true)Integer followupId) {
        try {
            return write(200, "操作成功!","data",followUpService.isFirstTimeFollowup(getUID(),patient,followupClass,followupId));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    //=======================end ==================================================
    @ApiOperation("保存全部随访表单数据")
    @RequestMapping(value = "/saveAllFollowupProjectData", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveAllFollowupProjectData(@ApiParam(name = "id", value = "随访记录ID")
                                                 @RequestParam(value = "id", required = true) String id,
                                             @ApiParam(name = "followupNo", value = "随访记录编码")
                                             @RequestParam(value = "followupNo", required = false) String followupNo,
                                             @ApiParam(name = "date", value = "随访时间", defaultValue = "2016-12-14 20:00:00")
                                                 @RequestParam(value = "date", required = false) String date,
                                             @ApiParam(name = "followupType", value = "随访方式【字典FOLLOWUP_WAY_DICT】", defaultValue = "12")
                                                 @RequestParam(value = "followupType", required = false) String followupType,
                                             @ApiParam(name = "followupClass", value = "随访类别【1.高血压 2.糖尿病,3高糖】", defaultValue = "1")
                                                 @RequestParam(value = "followupClass", required = false) String followupClass,
                                             @ApiParam(name = "followupManagerStatus", value = "随访管理状态【字典FOLLOWUP_MANAGER_STATUS】", defaultValue = "1")
                                                 @RequestParam(value = "followupManagerStatus", required = false) String followupManagerStatus,
                                             @ApiParam(name = "plandate", value = "下次随访时间", defaultValue = "2016-12-14 20:00:00")
                                                 @RequestParam(value = "plandate", required = false) String plandate,
                                             @ApiParam(name = "prescriptioncode", value = "续方CODE")
                                                 @RequestParam(value = "prescriptioncode", required = false) String prescriptioncode,
                                          @ApiParam(name = "followupProjectData", value = "随访项目数据", defaultValue = "{\"WEIGHT\":\"76\",\"WEIGHT_EXP\":\"60\",\"BMI\":\"11\"}")
                                          @RequestParam(value = "followupProjectData", required = true) String followupProjectData) {
        try {
            JSONObject jsonObject = new JSONObject(followupProjectData);
            Followup followup = followUpService.startFollowup(id, followupNo, date, followupType, followupClass, followupManagerStatus, plandate, prescriptioncode);
            followUpService.finishFollowup(id);
//            followUpService.saveAllFollowupProjectData(id, jsonObject.getJSONObject("followupProjectData").toString());
            followupDrugsService.saveFollowupDrugs(id,jsonObject.getJSONArray("drugsData").toString());
            return write(200, "保存随访项目数据成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存随访项目数据失败!" + e.getMessage());
        }
    }
}

+ 78 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/controller/DoctorFollowupDrugsController.java

@ -0,0 +1,78 @@
package com.yihu.jw.hospital.module.followup.controller;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.followup.service.FollowupDrugsService;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
 * 医生端:随访接口
 * 
 * @author hzp add 2016-12-07
 *
 */
@RestController
@RequestMapping(value = "/doctor/followup/drugs")
@Api(description = "医生端-随访用药接口")
public class DoctorFollowupDrugsController extends BaseController {
	@Autowired
	private FollowupDrugsService followupDrugsService;
	@ApiOperation("获取面访用药数据")
	@RequestMapping(value = "/getFollowupDrugs", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public String getFollowupDrugs(@ApiParam(name="id",value="随访记录ID",defaultValue = "")
									@RequestParam(value="id",required = true) String id)
	{
		try {
			Map<String,Object> response = followupDrugsService.getFollowupDrugs(id);
			return write(200, "获取面访用药数据成功!","data",response);
		} catch (Exception e) {
			return invalidUserException(e, -1, "获取面访用药数据失败!"+e.getMessage());
		}
	}
	@ApiOperation("保存面访用药数据")
	@RequestMapping(value = "/saveFollowupDrugs", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public String saveFollowupDrugs(@ApiParam(name="id",value="随访记录ID",defaultValue = "")
										  @RequestParam(value="id",required = true) String id,
									      @ApiParam(name="drugsData",value="面访用药数据",defaultValue = "[]")
										  @RequestParam(value="drugsData",required = true) String drugsData)
	{
		try {
			followupDrugsService.saveFollowupDrugs(id,drugsData);
			return write(200, "保存面访用药数据成功!");
		} catch (Exception e) {
			return invalidUserException(e, -1, "保存面访用药数据失败!"+e.getMessage());
		}
	}
//	@ApiOperation("获取随访类别用药列表")
//	@RequestMapping(value = "/getFollowupClassDrugs", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
//	public String getFollowupClassDrugs(@ApiParam(name="followupClass",value="随访类别:1.高血压 2.糖尿病",defaultValue = "")
//									@RequestParam(value="followupClass",required = true) String followupClass)
//	{
//		try {
//			List<DmDrugsGroupItem> list = followupDrugsService.getFollowupClassDrugs(followupClass);
//
//			return write(200, "获取随访类别用药列表成功!","data",list);
//		} catch (Exception e) {
//			return invalidUserException(e, -1, "获取随访类别用药列表失败!"+e.getMessage());
//		}
//	}
}

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

@ -6,20 +6,23 @@ import com.fasterxml.jackson.databind.ObjectMapper;
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.system.SystemDictDO;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.followup.*;
import com.yihu.jw.entity.base.servicePackage.ServiceItemPlanDO;
import com.yihu.jw.entity.followup.Followup;
import com.yihu.jw.entity.followup.FollowupContent;
import com.yihu.jw.entity.followup.FollowupSign;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.message.MessageNoticeSetting;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.message.service.SystemMessageService;
import com.yihu.jw.hospital.module.followup.dao.*;
import com.yihu.jw.hospital.module.followup.dao.FollowUpDao;
import com.yihu.jw.hospital.module.followup.dao.FollowupContentDao;
import com.yihu.jw.hospital.module.followup.dao.FollowupDrugsDao;
import com.yihu.jw.hospital.module.followup.dao.FollowupSignDao;
import com.yihu.jw.hospital.module.rehabilitation.service.RehabilitationManageService;
import com.yihu.jw.hospital.module.system.service.SystemDictService;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.team.dao.WlyySignFamilyDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.util.date.DateUtil;
@ -79,10 +82,7 @@ public class FollowUpService {
    private FollowupContentDao followupContentDao;
    @Autowired
    private SystemDictService systemDictService;
    @Autowired
    private WlyySignFamilyDao signFamilyDao;
    private WlyyHospitalSysDictDao hospitalSysDictDao;
//    @Autowired
//    private DrHealthTeamService drHealthTeamService;
@ -93,15 +93,12 @@ public class FollowUpService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    SystemDictService dictService;
    @Autowired
    private BasePatientService patientService;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private FollowUpMappingDao followUpMappingDao;
    private RehabilitationManageService rehabilitationManageService;
    @Autowired
    private FollowupDrugsDao followupDrugsDao;
@ -127,26 +124,15 @@ public class FollowUpService {
    private FollowupSignDao followupSignDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Value("${fastDFS.fastdfs_file_url}")
    private String imgUrlDomain;
    @Autowired
    private RehabilitationManageService rehabilitationManageService;
//    @Autowired
//    private VisitDetailService visitDetailService;
//    @Autowired
//    private ElasticFactory elasticFactory;
//    @Autowired
//    private ElastricSearchSave elastricSearchSave;
//    @Autowired
//    private ElasticsearchUtil elasticsearchUtil;
//    @Autowired
//    private BusinessMappingDao businessMappingDao;
    //字典
    public String getDictValue(String dictName,String code){
        WlyyHospitalSysDictDO dictDO = hospitalSysDictDao.findOneByDictNameAndDictCode(dictName,code);
        if(dictDO!=null){
            return dictDO.getDictValue();
        }
        return null;
    }
    /**
     * 转译随访信息
@ -179,7 +165,7 @@ public class FollowUpService {
        //随访方式转译
        re.put("followupType", followup.getFollowupType());
        String followupTypeName = systemDictService.getDictValue("FOLLOWUP_WAY_DICT", followup.getFollowupType());
        String followupTypeName = getDictValue("FOLLOWUP_WAY_DICT", followup.getFollowupType());
        re.put("followupTypeName", followupTypeName);
        //随访类别转译
@ -187,12 +173,12 @@ public class FollowUpService {
        String followupClass = followup.getFollowupClass();
        re.put("followupClass", followupClass);
        String followupClassName = systemDictService.getDictValue("FOLLOWUP_CLASS_DICT", followup.getFollowupClass());
        String followupClassName = getDictValue("FOLLOWUP_CLASS_DICT", followup.getFollowupClass());
        if (StringUtils.isNoneBlank(followupClass) && followupClass.contains(",")) {
            String[] followupClassArray = followupClass.split(",");
            followupClassName = "";
            for (int i = 0; i < followupClassArray.length; i++) {
                followupClassName += systemDictService.getDictValue("FOLLOWUP_CLASS_DICT", followupClassArray[i]);
                followupClassName += getDictValue("FOLLOWUP_CLASS_DICT", followupClassArray[i]);
                if (i != followupClassArray.length - 1) {
                    followupClassName += ",";
                }
@ -203,7 +189,7 @@ public class FollowUpService {
        //随访管理状态转译
        re.put("followupManagerStatus", followup.getFollowupManagerStatus());
        String followupManagerStatusName = systemDictService.getDictValue("FOLLOWUP_MANAGER_STATUS", followup.getFollowupManagerStatus());
        String followupManagerStatusName = getDictValue("FOLLOWUP_MANAGER_STATUS", followup.getFollowupManagerStatus());
        re.put("followupManagerStatusName", followupManagerStatusName);
        re.put("doctorCode", followup.getDoctorCode());
@ -289,18 +275,16 @@ public class FollowUpService {
            Map<String, String> dictMap = new HashMap<>();
            Map<String, String> statusMap = new HashMap<>();
            Map<String, String> mngStatusMap = new HashMap<>();
            List<SystemDictDO> dicts = dictService.getDictByDictName("FOLLOWUP_WAY_DICT");
            List<SystemDictDO> mngDicts = dictService.getDictByDictName("FOLLOWUP_MANAGER_STATUS");
            List<WlyyHospitalSysDictDO> dicts = hospitalSysDictDao.findByDictName("FOLLOWUP_WAY_DICT");
            List<WlyyHospitalSysDictDO> mngDicts = hospitalSysDictDao.findByDictName("FOLLOWUP_MANAGER_STATUS");
            if (dicts != null) {
                for (SystemDictDO dict : dicts) {
//                    dictMap.put(dict.getCode(), dict.getValue());
                    dictMap.put(dict.getCode(), dict.getName());
                for (WlyyHospitalSysDictDO dict : dicts) {
                    dictMap.put(dict.getDictCode(), dict.getDictValue());
                }
            }
            if (mngDicts != null) {
                for (SystemDictDO dict : mngDicts) {
//                    mngStatusMap.put(dict.getCode(), dict.getValue());
                    mngStatusMap.put(dict.getCode(), dict.getName());
                for (WlyyHospitalSysDictDO dict : mngDicts) {
                    mngStatusMap.put(dict.getDictCode(), dict.getDictValue());
                }
            }
@ -400,18 +384,16 @@ public class FollowUpService {
            Map<String, String> dictMap = new HashMap<>();
            Map<String, String> statusMap = new HashMap<>();
            Map<String, String> mngStatusMap = new HashMap<>();
            List<SystemDictDO> dicts = dictService.getDictByDictName("FOLLOWUP_WAY_DICT");
            List<SystemDictDO> mngDicts = dictService.getDictByDictName("FOLLOWUP_MANAGER_STATUS");
            List<WlyyHospitalSysDictDO> dicts = hospitalSysDictDao.findByDictName("FOLLOWUP_WAY_DICT");
            List<WlyyHospitalSysDictDO> mngDicts = hospitalSysDictDao.findByDictName("FOLLOWUP_MANAGER_STATUS");
            if (dicts != null) {
                for (SystemDictDO dict : dicts) {
//                    dictMap.put(dict.getCode(), dict.getValue());
                    dictMap.put(dict.getCode(), dict.getName());
                for (WlyyHospitalSysDictDO dict : dicts) {
                    dictMap.put(dict.getDictCode(), dict.getDictCode());
                }
            }
            if (mngDicts != null) {
                for (SystemDictDO dict : mngDicts) {
//                    mngStatusMap.put(dict.getCode(), dict.getValue());
                    mngStatusMap.put(dict.getCode(), dict.getName());
                for (WlyyHospitalSysDictDO dict : mngDicts) {
                    mngStatusMap.put(dict.getDictCode(), dict.getDictCode());
                }
            }
@ -514,9 +496,6 @@ public class FollowUpService {
            if (patient == null) {
                throw new RuntimeException("获取不到用户信息!");
            }
            SignFamily signFamily = signFamilyDao.findByjiatingPatient(patientCode);
            Long adminCodeId = 0L;
            List<Followup> followupPlan = new ArrayList<>();
            for (Map<String, String> map : list) {
                //获取医生信息
@ -541,17 +520,10 @@ public class FollowUpService {
                followup.setStatus("2");     //状态 0取消 1已完成 2未开始 3进行中
                followup.setCreateTime(new Date());
                followup.setCreater(doctorCode);
                if (!map.get("followupClass").toString().equalsIgnoreCase("10")) {
                    if (signFamily == null) {
                        throw new RuntimeException("非家签居民仅支持创建体温异常随访");
                    } else {
                        adminCodeId = signFamily.getAdminTeamId();
                    }
                }
                followup.setFollowupClass(map.get("followupClass"));
                followup.setType(Integer.parseInt(map.get("type1").toString()));
                followup.setAdminTeamCode(adminCodeId);
//                followup.setAdminTeamCode(adminCodeId);
                followup.setSignType(2);
                //获取随访医生角色类型
@ -570,6 +542,38 @@ public class FollowUpService {
        return null;
    }
    //添加康复计划随访
    public Followup addRehabilatationFollowup(ServiceItemPlanDO itemPlanDO)  {
        try {
            Followup followup = new Followup();
            followup.setFollowupType("2");
            Date date = DateUtil.strToDate(itemPlanDO.getPlanTime());
            followup.setFollowupDate(date);
            followup.setFollowupPlanDate(date);
            followup.setDoctorCode(itemPlanDO.getDoctor());
            followup.setDoctorName(itemPlanDO.getDoctorName());
//        followup.setOrgCode(doctor.getHospital());
//        followup.setOrgName(doctor.getHospitalName());
            followup.setPatientCode(itemPlanDO.getPatient());
            BasePatientDO patient = patientDao.findById(itemPlanDO.getPatient()).orElse(null);
            followup.setPatientName(patient.getName());
            followup.setIdcard(patient.getIdcard());
            followup.setDataFrom("2");//数据来源 1基卫 2APP
            followup.setStatus("2");//状态 0取消 1已完成 2未开始 3进行中
            followup.setCreateTime(new Date());
            followup.setCreater(itemPlanDO.getDoctor());
            followup.setFollowupClass("21");
            followup.setType(1);
            followup.setSignType(2);
            //新增签约保存CODE
            followup = followupDao.save(followup);
            return followup;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 新增随访计划(单个)
     */
@ -579,9 +583,6 @@ public class FollowUpService {
        if (patient == null) {
            throw new RuntimeException("获取不到用户信息!");
        }
        SignFamily signFamily = signFamilyDao.findByjiatingPatient(patientCode);
        Long adminCodeId = 0L;
        //获取医生信息
        BaseDoctorDO doctor = doctorDao.findById(data.getString("doctor")).orElse(null);
        if (doctor == null) {
@ -593,7 +594,7 @@ public class FollowUpService {
        Date date = DateUtil.strToDate(data.getString("date"));
        followup.setFollowupDate(date);
        followup.setFollowupPlanDate(date);
//        followup.setDoctorCode(doctor.getCode());
        followup.setDoctorCode(doctor.getId());
        followup.setDoctorName(doctor.getName());
//        followup.setOrgCode(doctor.getHospital());
//        followup.setOrgName(doctor.getHospitalName());
@ -604,32 +605,12 @@ public class FollowUpService {
        followup.setStatus("2");     //状态 0取消 1已完成 2未开始 3进行中
        followup.setCreateTime(new Date());
        followup.setCreater(doctorCode);
        if (!data.getString("followupClass").toString().equalsIgnoreCase("10")) {
            if (signFamily == null) {
                throw new RuntimeException("非家签居民仅支持创建体温异常随访");
            } else {
                adminCodeId = signFamily.getAdminTeamId();
            }
        }
        followup.setFollowupClass(data.getString("followupClass"));
        followup.setType(Integer.parseInt(data.get("type1").toString()));
        followup.setAdminTeamCode(adminCodeId);
//        followup.setAdminTeamCode(adminCodeId);
        followup.setSignType(2);
        //获取随访医生角色类型
//        List<DoctorMapping> doctorMapping = doctorMappingDao.findListByDoctorCode(doctorCode);
//        if(doctorMapping.size() ==1 && StringUtils.isNotBlank(doctorMapping.get(0).getJwDoctorWorkType())){
//            followup.setJwDoctorWorkType(doctorMapping.get(0).getJwDoctorWorkType());
//        }
        //新增签约保存CODE
//        followup.setSignCode(patientService.getSignCodeByPatient(patientCode));
        followup = followupDao.save(followup);
//        远程2.0接口,参数在改改
//        rehabilitationManageService.updateRelationCodeByDetailId(data.getString("id"),followup.getId()+"");
//        rehabilitationManageService.saveRehabilitationOperateRecord(dataJson);
        return followup;
    }
@ -761,16 +742,6 @@ public class FollowUpService {
        if (patient == null) {
            throw new RuntimeException("查找不到居民信息!");
        }
        SignFamily signFamily = signFamilyDao.findByjiatingPatient(patientCode);
        Long adminId = 0L;
        if (!followupClass.equalsIgnoreCase("10")) {
            if (signFamily == null) {
                throw new RuntimeException("非家签居民仅支持创建体温异常随访");
            } else {
                adminId = signFamily.getAdminTeamId();
            }
        }
        Followup followup = new Followup();
        Date followDate = DateUtil.strToDate(date);
@ -790,7 +761,7 @@ public class FollowUpService {
        followup.setStatus("2");     //状态 0取消 1已完成 2未开始 3进行中
        followup.setCreateTime(new Date());
        followup.setCreater(doctorCode);
        followup.setAdminTeamCode(signFamily.getAdminTeamId());
//        followup.setAdminTeamCode(signFamily.getAdminTeamId());
        followup.setSignType(2);
        if (type != null && type != 0) {
            followup.setType(type);
@ -861,20 +832,8 @@ public class FollowUpService {
            followup.setStatus("1");  //状态 0取消 1已完成 2未开始 3进行中
            followup = followupDao.save(followup);
            //上传随访计划映射表记录
            FollowupMapping followupMapping = followUpMappingDao.findByFollowupId(Integer.parseInt(String.valueOf(followup.getId())));
            if (followupMapping == null) {
                followupMapping = new FollowupMapping();
            }
            followupMapping.setFollowupId(Integer.parseInt(String.valueOf(followup.getId())));
            followupMapping.setCode(UUID.randomUUID().toString());
            followupMapping.setCreateTime(DateUtil.getNowTimestamp());
            followupMapping.setUpdateTime(DateUtil.getNowTimestamp());
            followupMapping.setNeedUpload(1);
            followUpMappingDao.save(followupMapping);
            //关联康复计划完成
            rehabilitationManageService.completePlanFollowup(followup.getId());
            //随访完成,增加随访状态完成的标记
//            Prescription prescription = prescriptionDao.findByCode(followup.getPrescriptionCode());
@ -883,7 +842,6 @@ public class FollowUpService {
//                prescriptionDao.save(prescription);
//            }
//            new Thread(new FollowupUploadTask(String.valueOf(followup.getId()))).start();
        } else {
            throw new RuntimeException("查找不到该随访计划!");
        }
@ -910,18 +868,17 @@ public class FollowUpService {
    public List<Map<String, String>> getFollowupProject(String id) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        //获取已填写的面访项目
//        List<String> project = followupContentDao.findProjectByFollowupId(Long.valueOf(id));
        List<String> project = followupContentDao.findProjectByFollowupId(Long.valueOf(id));
        //修改为通过ES查询---2017.11.01--huangwenjie
//        List<String> project = esfindProjectByFollowupId(id);
        List<String> project = null;
        //获取所有面访项目
        List<SystemDictDO> dictList = systemDictService.getDictByDictName("FOLLOWUP_PROJECT");
        List<WlyyHospitalSysDictDO> dictList = hospitalSysDictDao.findByDictName("FOLLOWUP_PROJECT");
        if (dictList != null && dictList.size() > 0) {
            for (SystemDictDO dict : dictList) {
            for (WlyyHospitalSysDictDO dict : dictList) {
                Map<String, String> map = new HashMap<>();
                String code = dict.getCode();
                String code = dict.getDictCode();
                map.put("projectCode", code);
                map.put("projectName", dict.getName());
                map.put("projectName", dict.getDictValue());
                if (project != null && project.contains(code)) {
                    map.put("status", "1"); //已填写
                } else {
@ -973,21 +930,21 @@ public class FollowUpService {
        }
        Followup followup = followupDao.findById(Long.valueOf(id)).orElse(null);
//        Followup followup = followupDao.findById(Long.valueOf(id)).orElse(null);
        //如果该随访是已完成的,则添加随访信息上传映射,上传到基卫
        if ("1".equals(followup.getStatus())) {
            FollowupMapping followupMapping = followUpMappingDao.findByFollowupId(Integer.parseInt(id));
            if (followupMapping == null) {
                followupMapping = new FollowupMapping();
                followupMapping.setCode(UUID.randomUUID().toString());
                followupMapping.setFollowupId(Integer.parseInt(id));
                followupMapping.setUpdateTime(DateUtil.getNowTimestamp());
                followupMapping.setCreateTime(DateUtil.getNowTimestamp());
            }
            followupMapping.setNeedUpload(1);
            followUpMappingDao.save(followupMapping);
        }
//        if ("1".equals(followup.getStatus())) {
//            FollowupMapping followupMapping = followUpMappingDao.findByFollowupId(Integer.parseInt(id));
//            if (followupMapping == null) {
//                followupMapping = new FollowupMapping();
//                followupMapping.setCode(UUID.randomUUID().toString());
//                followupMapping.setFollowupId(Integer.parseInt(id));
//                followupMapping.setUpdateTime(DateUtil.getNowTimestamp());
//                followupMapping.setCreateTime(DateUtil.getNowTimestamp());
//            }
//            followupMapping.setNeedUpload(1);
//            followUpMappingDao.save(followupMapping);
//        }
    }
@ -1028,7 +985,7 @@ public class FollowUpService {
    private List<BaseDoctorDO> getTeamDoctors(String doctor, String patient) throws Exception {
        List<BaseDoctorDO> doctors = new ArrayList<>();
        //获取医生团队成员
        SignFamily signFamily = signFamilyDao.findByFamilyDoctorAndPatient(doctor, patient);
//        SignFamily signFamily = signFamilyDao.findByFamilyDoctorAndPatient(doctor, patient);
        // 查询家庭医生团队
//        if (signFamily != null) {
//            doctors = drHealthTeamService.findTeamDoctors(signFamily.getTeamCode());
@ -2032,12 +1989,6 @@ public class FollowUpService {
            BasePatientDO p = patientDao.findById(followup.getPatientCode()).orElse(null);
            followup.setPatientName(p.getName());
            followup.setIdcard(p.getIdcard());
            //新增保存签约id v1.6.8.3
            SignFamily signFamily = signFamilyDao.findByjiatingPatient(followup.getPatientCode());
            if (signFamily != null) {
                followup.setAdminTeamCode(signFamily.getAdminTeamId());
            }
        }
        List<Date> dateList = followupDao.findFollowupDateList(followup.getDoctorCode(), followup.getPatientCode());
        Date prior = null;

+ 98 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/service/FollowupDrugsService.java

@ -0,0 +1,98 @@
package com.yihu.jw.hospital.module.followup.service;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.followup.FollowupDrugs;
import com.yihu.jw.hospital.module.followup.dao.FollowupDrugsDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.transaction.Transactional;
import java.util.*;
/**
 * 随访用药服务
 * @author hzp add 2016-12-08
 *
 */
@Component
@Transactional(rollbackOn = Exception.class)
public class FollowupDrugsService {
	@Autowired
	private FollowupDrugsDao followupDrugsDao;
	@Autowired
	private ObjectMapper objectMapper;
	
	@Autowired
	private FollowUpService followUpService;
	private String drugsProject = "6";
	/**
	 * 获取面访用药数据
	 */
	public Map<String,Object> getFollowupDrugs(String id) throws Exception
	{
		Map<String,Object> re = new HashMap<>();
		
		//2017-11-16 修改为从ES获取--huangwenjie
//		FollowupContentESDO followupContentESDO = followUpService.esGetFollowupProjectData(id, "6");
//		if(followupContentESDO != null){
//			re.put("DRUG_COMPLIANCE_CODE",followupContentESDO.getDRUG_COMPLIANCE_CODE());
//		}
		//获取用药记录
		List<FollowupDrugs> drugsList = followupDrugsDao.findByFollowupId(Long.valueOf(id));
		re.put("DRUG_LIST",drugsList);
		return re;
	}
	/**
	 *保存面访用药数据
	 */
	@Transactional
	public void saveFollowupDrugs(String id,String drugsData) throws Exception {
		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Map.class);
		List<Map<String,String>> list = objectMapper.readValue(drugsData,javaType);
		Long followupId = Long.valueOf(id);
		//删除原有用药记录
		followupDrugsDao.deleteByFollowupId(Long.valueOf(followupId));
		if(list!=null && list.size()>0)
		{
			List<FollowupDrugs> newList = new ArrayList<>();
			for(Map<String,String> item:list)
			{
				FollowupDrugs drug = new FollowupDrugs();
				drug.setFollowupId(followupId);
				drug.setDrugsGroup(item.get("drugsGroup"));
				drug.setDrugsCode(item.get("drugsCode"));
				drug.setDrugsName(item.get("drugsName"));
				drug.setDose(item.get("dose"));
				drug.setUnit(item.get("unit"));
				drug.setFrequency(item.get("frequency"));
				drug.setCreateTime(new Date());
				newList.add(drug);
			}
			followupDrugsDao.saveAll(newList);
		}
	}
	/*********************************** 疾病用药 *****************************************************************/
	/**
	 *获取疾病用药
	 */
//	public List<DmDrugsGroupItem> getFollowupClassDrugs(String followupClass) throws Exception {
//		return dmDrugsGroupItemDao.findByFollowupClass(followupClass);
//	}
}

文件差異過大導致無法顯示
+ 2 - 1154
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/jw/service/JwSmjkService.java


+ 27 - 6
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/DoctorRehabilitaionInfoController.java

@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationAdviceDO;
import com.yihu.jw.hospital.module.rehabilitation.dao.RehabilitationPatientInfoDao;
import com.yihu.jw.hospital.module.rehabilitation.service.RehabilitationInfoService;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
@ -31,6 +32,8 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
    private RehabilitationInfoService rehabilitationInfoService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RehabilitationPatientInfoDao rehabilitationPatientInfoDao;
    /**
     * 查询患者基本信息
@ -46,7 +49,7 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
            return MixEnvelop.getSuccess(SpecialistMapping.api_success, list);
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
            return MixEnvelop.getError("查询失败");
        }
    }
@ -58,6 +61,7 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
    @RequestMapping(value = "getRehabilitationPatientListNew", method = RequestMethod.GET)
    @ApiOperation("获取康复下转居民列表")
    public String getRehabilitationPatientListNew(
            @ApiParam(name = "downPatientId", value = "下转表id", required = false) @RequestParam(value = "downPatientId", required = false) String downPatientId,
            @ApiParam(name = "doctorId", value = "医生id", required = false) @RequestParam(value = "doctorId", required = false) String doctorId,
            @ApiParam(name = "idcard", value = "身份证", required = false) @RequestParam(value = "idcard", required = false) String idcard,
            @ApiParam(name = "status", value = "", defaultValue = "0", required = false) @RequestParam(value = "status", required = false) String status,
@ -75,7 +79,7 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
                doctorId = getUID();
                System.out.println("医生id==>getUID()==>" + getUID());
            }
            JSONObject result = rehabilitationInfoService.getRehabilitationPatientListNew(idcard, doctorId, status, page, pagesize);
            JSONObject result = rehabilitationInfoService.getRehabilitationPatientListNew( downPatientId,idcard, doctorId, status, page, pagesize);
            return write(200, "请求成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
@ -97,7 +101,7 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
            List<Map<String, Object>> list = rehabilitationInfoService.getRehabilitationPatientCountNew(doctorId);
            return write(200, "请求成功", "data", list);
        } catch (Exception e) {
            return error(-1, e.getMessage());
            return error(-1, "查询失败");
        }
    }
@ -230,6 +234,20 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
        }
    }
    @RequestMapping(value = "findRehabilitationPatientInfo", method = RequestMethod.GET)
    @ApiOperation("查询下转居民信息")
    public String findRehabilitationPatientInfo(
            @ApiParam(name = "patientInfoCode", value = "下转居民信息code", required = true)
            @RequestParam(value = "patientInfoCode", required = true) String patientInfoCode
    ) {
        try {
            return write(200, "请求成功", "data", rehabilitationPatientInfoDao.findByCode(patientInfoCode));
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "请求失败");
        }
    }
    /**
     * 查询居民的康复计划
     * todo 还需要代办项目还需要重新join一张新表 todayTaskCount 今日任务项,等后面在整
@ -282,7 +300,8 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
            List<Map<String, Object>> result = rehabilitationInfoService.getPatientPlanItemList(patientId, planId, itemId, status);
            return write(200, "请求成功", "data", result);
        } catch (Exception e) {
            return error(-1, e.getMessage());
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
@ -305,7 +324,8 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
            List<Map<String, Object>> result = rehabilitationInfoService.getPatientPlanFrequencyItemList(patientId, planId, startTime, endTime, doctorId, type);
            return write(200, "请求成功", "data", result);
        } catch (Exception e) {
            return error(-1, e.getMessage());
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
@ -323,7 +343,8 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
            List<Map<String, Object>> result = rehabilitationInfoService.getPlanDoctorList(planId);
            return write(200, "请求成功", "data", result);
        } catch (Exception e) {
            return error(-1, e.getMessage());
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

+ 42 - 44
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/PatientRehabilitationManageController.java

@ -12,6 +12,7 @@ import com.yihu.jw.hospital.module.rehabilitation.service.RehabilitationManageSe
import com.yihu.jw.hospital.module.rehabilitation.service.RehabilitationPlanService;
import com.yihu.jw.hospital.prescription.service.DrugsPlanService;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@ -53,9 +54,22 @@ public class PatientRehabilitationManageController extends EnvelopRestEndpoint {
    private PatientRestTimeService patientRestTimeService;
    @Autowired
    private DrugsPlanService drugsPlanService;
//    @Autowired
//    private GuahaoXMService guahaoXM;//挂号
    @RequestMapping(value = "recentServiceItemPlanRecords", method = RequestMethod.GET)
    @ApiOperation("近期康复记录")
    public Envelop recentServiceItemPlanRecords(@ApiParam(name = "patient", value = "居民code", required = true)
                                      @RequestParam(value = "patient", required = true) String patient,
                                      @ApiParam(name = "page", value = "第几页", required = true)
                                      @RequestParam(value = "page", required = true) Integer page,
                                      @ApiParam(name = "size", value = "分页大小", required = true)
                                      @RequestParam(value = "size", required = true) Integer size) {
        try {
            return rehabilitationManageService.recentServiceItemPlanRecords(patient, page, size);
        } catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "selectPlanByPatient", method = RequestMethod.GET)
    @ApiOperation("康复管理-根据居民code查找康复计划")
@ -67,7 +81,7 @@ public class PatientRehabilitationManageController extends EnvelopRestEndpoint {
            List<Map<String, Object>> result = rehabilitationManageService.selectPlanByPatient(patient, status, null, null);
            return write(200, "获取成功", "data", result);
        } catch (Exception e) {
            return error(-1, "请求失败");
            return error(-1, "查询失败");
        }
    }
@ -316,52 +330,36 @@ public class PatientRehabilitationManageController extends EnvelopRestEndpoint {
    }
    /**
     * w;yy2.0的接口
     */
//    @RequestMapping(value = "calendarPlanDetailList", method = RequestMethod.GET)
//    @ApiOperation("康复管理-康复计划按列表展示-限定频次")
//    public String calendarPlanDetailList(
//            @ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true) @RequestParam(value = "executeStartTime", required = false)String executeStartTime,
//            @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true) @RequestParam(value = "executeEndTime", required = false)String executeEndTime,
//            @ApiParam(name = "planId", value = "计划id", required = true) @RequestParam(value = "planId", required = true)String planId,
//            @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)", required = false) @RequestParam(value = "searchTask", required = false)Integer searchTask,
//            @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)", required = false) @RequestParam(value = "doctorCode", required = false)String doctorCode,
//            @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false) @RequestParam(value = "status", required = false)Integer status,
//            @ApiParam(name="taskExecutor",value = "任务执行人:0全部;1我的任务:2他人任务",required = false) @RequestParam(value = "taskExecutor",required = false,defaultValue = "0")String taskExecutor
//    ){
//        try {
//            if(!StringUtils.isNotEmpty(doctorCode)){
//                doctorCode = getRepUID();
//            }
//            JSONArray result = rehabilitationManageService.calendarPlanDetailListWithTaskExecutor(executeStartTime,executeEndTime,planId,searchTask,status,doctorCode,taskExecutor);
//            return write(200, "获取成功", "data", result);
//        }  catch (Exception e) {
//            return error(-1, e.getMessage());
//        }
//    }
    /**
     * i健康接口
     */
    @RequestMapping(value = "calendarPlanDetailList", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划按列表展示")
    public String calendarPlanDetailList(
            @ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true) @RequestParam(value = "executeStartTime", required = true) String executeStartTime,
            @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true) @RequestParam(value = "executeEndTime", required = true) String executeEndTime,
            @ApiParam(name = "planId", value = "计划id", required = true) @RequestParam(value = "planId", required = true) String planId,
            @ApiParam(name = "searchTask", value = "快速查找任务:(1、我的任务,2、健康教育,3、复诊,4、随访)", required = false) @RequestParam(value = "searchTask", required = false) Integer searchTask,
            @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false) @RequestParam(value = "status", required = false) Integer status
    ) {
    @ApiOperation("康复管理-康复计划按列表展示-限定频次")
    public Envelop calendarPlanDetailList(
            @ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
            @RequestParam(value = "executeStartTime", required = false)String executeStartTime,
            @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
            @RequestParam(value = "executeEndTime", required = false)String executeEndTime,
            @ApiParam(name = "planId", value = "计划id", required = true)
            @RequestParam(value = "planId", required = true)String planId,
            @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊 8全部)", required = false)
            @RequestParam(value = "searchTask", required = false)Integer searchTask,
            @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)", required = false)
            @RequestParam(value = "doctorCode", required = false)String doctorCode,
            @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
            @RequestParam(value = "status", required = false)Integer status,
            @ApiParam(name="taskExecutor",value = "任务执行人:0全部;1我的任务:2他人任务",required = false)
            @RequestParam(value = "taskExecutor",required = false,defaultValue = "0")String taskExecutor
    ){
        try {
            JSONArray result = rehabilitationManageService.calendarPlanDetailList(executeStartTime, executeEndTime, planId, searchTask, status, null);
            return write(200, "获取成功", "data", result);
        } catch (Exception e) {
            return error(-1, "请求失败");
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            return rehabilitationManageService.calendarPlanDetailList(planId, searchTask, status, doctorCode, executeStartTime, executeEndTime, taskExecutor);
        }  catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
//    @RequestMapping(value = "calendarPlanDetailItems", method = RequestMethod.GET)
//    @ApiOperation("康复管理-康复计划服务项目按列表展示")
//    public String calendarPlanDetailItems(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)

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

@ -3,10 +3,10 @@ package com.yihu.jw.hospital.module.rehabilitation.controller;
import com.yihu.jw.entity.specialist.rehabilitation.PatientRehabilitationPlanDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationOperateRecordsDO;
import com.yihu.jw.hospital.module.rehabilitation.dao.RehabilitationOperateRecordsDao;
import com.yihu.jw.hospital.module.rehabilitation.service.RehabilitationManageService;
import com.yihu.jw.hospital.module.rehabilitation.service.SynchronizePatientService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
@ -23,7 +23,6 @@ import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.Map;
//import org.springframework.cloud.sleuth.Tracer;
/**
 * Created by 刘文彬 on 2018/8/16.
@ -35,12 +34,77 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
    @Autowired
    private RehabilitationManageService rehabilitationManageService;
    //    @Autowired
//    private Tracer tracer;
    @Autowired
    private RehabilitationOperateRecordsDao rehabilitationOperateRecordsDao;
    @Autowired
    SynchronizePatientService synchronizePatientService;
    private SynchronizePatientService synchronizePatientService;
    @PostMapping(value = "completePlan")
    @ApiOperation("确认完成服务,填写服务笔记")
    public Envelop completePlan(
            @ApiParam(name = "id", value = "执行计划id", required = true)
            @RequestParam(value = "id", required = true) String id,
            @ApiParam(name = "content", value = "服务完成笔记", required = false)
            @RequestParam(value = "content", required = false) String content,
            @ApiParam(name = "appendixs", value = "附件", required = false)
            @RequestParam(value = "appendixs", required = false) String appendixs) {
        try {
            rehabilitationManageService.completePlan(id,content,appendixs,getUID());
            return Envelop.getSuccess("操作成功");
        }catch (ServiceException se){
            return Envelop.getError(se.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError("操作失败");
        }
    }
    @GetMapping(value = "rehabilitationDetailInfo")
    @ApiOperation("康复计划服务项列表")
    public Envelop rehabilitationDetailInfo(
            @ApiParam(name = "planId", value = "康复计划id", required = true)
            @RequestParam(value = "planId", required = true) String planId,
            @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)", required = false)
            @RequestParam(value = "searchTask", required = false) String searchTask,
            @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
            @RequestParam(value = "status", required = false) String status) {
        try {
            return ListEnvelop.getSuccess("查询成功",rehabilitationManageService.rehabilitationDetailInfo(planId,status,searchTask));
        }catch (ServiceException se){
            return Envelop.getError(se.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @GetMapping(value = "findServiceItemPlanDetail")
    @ApiOperation("执行计划详情")
    public Envelop findServiceItemPlanDetail(
            @ApiParam(name = "itemPlanId", value = "执行计划id", required = true)
            @RequestParam(value = "itemPlanId", required = true) String itemPlanId) {
        try {
            return ObjEnvelop.getSuccess("查询成功",rehabilitationManageService.findServiceItemPlanDetail(itemPlanId));
        }catch (ServiceException se){
            return Envelop.getError(se.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @GetMapping(value = "findGuidanceMessageDetail")
    @ApiOperation("查询指导留言详情")
    public Envelop findGuidanceMessageDetail(
            @ApiParam(name = "itemPlanId", value = "执行计划id", required = true)
            @RequestParam(value = "itemPlanId", required = true) String itemPlanId) {
        try {
            return ObjEnvelop.getSuccess("查询成功",rehabilitationManageService.findGuidanceMessageDetail(itemPlanId));
        }catch (ServiceException se){
            return Envelop.getError(se.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @PostMapping(value = "assignExecutor")
    @ApiOperation("计划负责人分配执行人")
@ -72,7 +136,7 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
            }
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
            return MixEnvelop.getError("操作成功");
        }
    }
@ -94,7 +158,7 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
            return MixEnvelop.getError("获取失败");
        }
    }
@ -109,15 +173,15 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
            return ObjEnvelop.getError("获取失败");
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.calendarPlanDetail)
    @ApiOperation(value = "康复管理-康复计划按日历展示")
    public ObjEnvelop calendarPlanDetail(
            @ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)") @RequestParam(value = "executeStartTime", required = false) String executeStartTime,
            @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)") @RequestParam(value = "executeEndTime", required = false) String executeEndTime,
            @ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd)") @RequestParam(value = "executeStartTime", required = false) String executeStartTime,
            @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd)") @RequestParam(value = "executeEndTime", required = false) String executeEndTime,
            @ApiParam(name = "planId", value = "计划id,多个计划逗号隔开", required = true) @RequestParam(value = "planId", required = true) String planId,
            @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)", required = false) @RequestParam(value = "searchTask", required = false) Integer searchTask,
            @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false) @RequestParam(value = "status", required = false) Integer status,
@ -128,7 +192,7 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
            return rehabilitationManageService.calendarPlanDetail(executeStartTime, executeEndTime, planId, searchTask, status, doctorCode, taskExecutor);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
            return ObjEnvelop.getError("获取失败");
        }
    }
@ -136,10 +200,10 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
    @GetMapping(value = SpecialistMapping.rehabilitation.calendarPlanDetailList)
    @ApiOperation(value = "康复管理-康复计划按列表展示")
    public ObjEnvelop calendarPlanDetailList(
            @ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)") @RequestParam(value = "executeStartTime", required = false) String executeStartTime,
            @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)") @RequestParam(value = "executeEndTime", required = false) String executeEndTime,
            @ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd)") @RequestParam(value = "executeStartTime", required = false) String executeStartTime,
            @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd)") @RequestParam(value = "executeEndTime", required = false) String executeEndTime,
            @ApiParam(name = "planId", value = "计划id,多个计划逗号隔开", required = true) @RequestParam(value = "planId", required = true) String planId,
            @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)") @RequestParam(value = "searchTask", required = false) Integer searchTask,
            @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊 8所有)") @RequestParam(value = "searchTask", required = false) Integer searchTask,
            @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)") @RequestParam(value = "doctorCode", required = false) String doctorCode,
            @ApiParam(name = "taskExecutor", value = "任务执行人:0全部;1我的任务:2他人任务", required = false) @RequestParam(value = "taskExecutor", required = false, defaultValue = "0") String taskExecutor
@ -206,18 +270,18 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
    @ApiOperation(value = "康复管理-保存指导留言")
    public Envelop saveGuidanceMessage(
            @ApiParam(name = "messageId", value = "消息id", required = true) @RequestParam(value = "messageId", required = true) String messageId,
            @ApiParam(name = "patientCode", value = "居民code", required = false) @RequestParam(value = "patientCode", required = false) String patientCode,
            @ApiParam(name = "imgs", value = "附件", required = false) @RequestParam(value = "imgs", required = false) String imgs,
            @ApiParam(name = "doctorCode", value = "医生code", required = true) @RequestParam(value = "doctorCode", required = true) String doctorCode,
            @ApiParam(name = "doctorType", value = "医生类型(1、专科医生,2、家庭医生)", required = true) @RequestParam(value = "doctorType", required = true) Integer doctorType,
            @ApiParam(name = "doctorType", value = "医生类型(1、专科医生)", required = true) @RequestParam(value = "doctorType", required = true) Integer doctorType,
            @ApiParam(name = "content", value = "聊天内容", required = true) @RequestParam(value = "content", required = true) String content,
            @ApiParam(name = "planDetailId", value = "服务项目id", required = true) @RequestParam(value = "planDetailId", required = true) String planDetailId,
            @ApiParam(name = "itemPlanId", value = "服务项目执行计划id", required = true) @RequestParam(value = "itemPlanId", required = true) String itemPlanId,
            @ApiParam(name = "contentType", value = "内容类型(1,6,8 - 文本, 2,9- 图片, 3 - 语音, 4-文章, 5,7系统消息。12-语音 18-居民名片, 19-聊天记录)", required = true)
            @RequestParam(value = "contentType", required = true) Integer contentType) {
        try {
            return rehabilitationManageService.saveGuidanceMessage(messageId, doctorCode, doctorType, content, planDetailId, contentType);
            return rehabilitationManageService.saveGuidanceMessage(messageId, doctorCode, doctorType, content,imgs, itemPlanId, contentType);
        } catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError(e.getMessage());
            return Envelop.getError("操作失败");
        }
    }
@ -416,7 +480,7 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.planSchedule)
    @GetMapping(value = "planSchedule")
    @ApiOperation(value = "康复管理-计划总进度")
    public ObjEnvelop planSchedule(
            @ApiParam(name = "planId", value = "计划id", required = true) @RequestParam(value = "planId", required = true) String planId
@ -425,8 +489,7 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
            return rehabilitationManageService.planSchedule(planId);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
            return ObjEnvelop.getError("查询失败");
        }
    }
@ -438,7 +501,7 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
            return rehabilitationManageService.planListByPatient(patientCode);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
            return ObjEnvelop.getError("查询失败");
        }
    }

+ 15 - 21
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/RehabilitationPlanController.java

@ -56,7 +56,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
        try {
            return write(200, "获取成功", "data", rehabilitationPlanService.getRehabilitationPlanLog(planId));
        } catch (Exception e) {
            return error(-1, e.getMessage());
            return error(-1, "查询失败");
        }
    }
@ -88,7 +88,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return rehabilitationPlanService.saveRehabilitationPlanTemplateData(templateDO, details);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
            return ObjEnvelop.getError("操作失败");
        }
    }
@ -112,7 +112,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return MixEnvelop.getSuccess(SpecialistMapping.api_success, map);
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
            return MixEnvelop.getError("查询失败");
        }
    }
@ -131,7 +131,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return MixEnvelop.getSuccess(SpecialistMapping.api_success, list);
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
            return MixEnvelop.getError("查询失败");
        }
    }
@ -154,7 +154,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return MixEnvelop.getSuccess(SpecialistMapping.api_success, list);
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
            return MixEnvelop.getError("查询失败");
        }
    }
@ -169,7 +169,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return MixEnvelop.getSuccess(SpecialistMapping.api_success, list);
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
            return MixEnvelop.getError("查询失败");
        }
    }
@ -188,8 +188,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return rehabilitationPlanService.deleteRehabilitationPlanTemplate(id);
        } catch (Exception e) {
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return ObjEnvelop.getError(e.getMessage());
            return ObjEnvelop.getError("操作失败");
        }
    }
@ -229,8 +228,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return envelop;
        } catch (Exception e) {
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return ListEnvelop.getError(e.getMessage());
            return ListEnvelop.getError("查询失败");
        }
    }
@ -243,7 +241,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return envelop;
        } catch (Exception e) {
            e.printStackTrace();
            return ListEnvelop.getError(e.getMessage());
            return ListEnvelop.getError("查询失败");
        }
    }
@ -265,7 +263,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return MixEnvelop.getSuccess(SpecialistMapping.api_success, entity);
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
            return MixEnvelop.getError("操作失败");
        }
    }
@ -284,7 +282,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return MixEnvelop.getSuccess(SpecialistMapping.api_success, list);
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
            return MixEnvelop.getError("查询失败");
        }
    }
@ -302,8 +300,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return rehabilitationPlanService.findRehabilitationPlanTemplate(adminTeamCode, doctor, patient);
        } catch (Exception e) {
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
            return MixEnvelop.getError("查询失败");
        }
    }
@ -317,8 +314,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return rehabilitationPlanService.createRehabilitationTemplate(templateDO);
        } catch (Exception e) {
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return ObjEnvelop.getError(e.getMessage());
            return ObjEnvelop.getError("操作失败");
        }
    }
@ -332,8 +328,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return rehabilitationPlanService.createRehabilitationTemplateDetail(details);
        } catch (Exception e) {
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return ObjEnvelop.getError(e.getMessage());
            return ObjEnvelop.getError("操作失败");
        }
    }
@ -348,8 +343,7 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
            return rehabilitationPlanService.updateRehabilitationTemplateDetail(details);
        } catch (Exception e) {
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return ObjEnvelop.getError(e.getMessage());
            return ObjEnvelop.getError("操作失败");
        }
    }

+ 2 - 2
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationDetailDao.java

@ -27,8 +27,8 @@ public interface RehabilitationDetailDao extends PagingAndSortingRepository<Reha
    @Query("select count(1) from RehabilitationDetailDO where status =?1 and planId=?2 and executeTime>=?3 and executeTime<=?4 ")
    Integer completenessCount(Integer status, String planId, Date executeStartTime, Date executeEndTime);
    @Query("select d from RehabilitationDetailDO d where d.planId=?1 order by d.executeTime desc")
    List<RehabilitationDetailDO> getAllRehabilitationDetail(String programId);
    @Query("select d from RehabilitationDetailDO d where d.planId=?1 order by d.hospitalServiceItemId")
    List<RehabilitationDetailDO> getAllRehabilitationDetail(String planId);
    @Query("select d from RehabilitationDetailDO d where d.executeTime<=?1 and d.executeTime>=?2 and d.planId=?3")
    List<RehabilitationDetailDO> findByPlanId(Date executeStartTime, Date executeEndTime, String planId);

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

@ -847,6 +847,7 @@ public class RehabilitationInfoService {
        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());
@ -949,15 +950,15 @@ public class RehabilitationInfoService {
        return list;
    }
    public JSONObject getRehabilitationPatientListNew(String idcard, String doctorId, String status, Integer page, Integer pagesize) {
    public JSONObject getRehabilitationPatientListNew(String downPatientId, String idcard, String doctorId, String status, Integer page, Integer pagesize) {
        JSONObject object = new JSONObject();
        List<Map<String, Object>> list = null;
        String detailSql = "SELECT \n" +
                " 	p.idcard, q.id 'planId',	p.id 'patientId', p.phone,	p.`name` 'patientName',	p.sex,	p.address, \n" +
                "  d.code 'patientInfoCode',	d.ssc , d.mobile, d.age,	d.diagnosis_name 'diagnosisName',	d.sign_status,	d.dept 'deptCode', \n" +
                "   d.code 'patientInfoCode',	d.ssc , d.mobile, d.age,	d.diagnosis_name 'diagnosisName',	d.sign_status,	d.dept 'deptCode', \n" +
                " 	d.dept_name 'deptName',	d.create_user 'createUserId', \n" +
                " 	d.create_user_name 'createUserName',DATE_FORMAT(d.create_time, '%Y-%m-%d %H:%i:%s') 'createTime',\n" +
                "	q.`status` 'planStaus',q.plan_doctor 'planDoctor', q.plan_doctor_name 'planDoctorName' ,\n" +
                "	q.`status` 'planStaus',q.plan_doctor 'planDoctor', q.plan_doctor_name 'planDoctorName' , q.advice_content 'adviceContent', \n" +
                "	DATE_FORMAT(q.create_time, '%Y-%m-%d %H:%i:%s') 'planCreateTime'," +
                "   d.from_source," +
                "       CASE  \n" +
@ -981,6 +982,10 @@ public class RehabilitationInfoService {
        if (StringUtils.isNotBlank(idcard)) {
            filterSql += " and d.idcard='" + idcard + "' ";
        }
        if (StringUtils.isNotBlank(downPatientId)) {
            //wlyy_rehabilitation_patient_info的id
            filterSql += " and d.id='" + downPatientId + "' ";
        }
        if (StringUtils.isBlank(status)) {
            //看全部数据
            filterSql += "	AND (d.create_user = '" + doctorId + "'  OR ISNULL(  d.create_user  ) )\n" +
@ -1097,41 +1102,51 @@ public class RehabilitationInfoService {
        String limitSql = " LIMIT " + (page - 1) * pagesize + "," + pagesize;
        String sql = "SELECT * FROM ( " +
                "SELECT DISTINCT \n" +
                "	 a.idcard,a.id,a.`name`,a.birthday,a.phone,a.sex,a.mobile,c.age,\n" +
                "	  (\n" +
                "		SELECT GROUP_CONCAT(q.`name`) FROM base_disease_hospital q  INNER JOIN wlyy_patient_rehabilitation_plan w ON q.id = w.disease \n" +
                "	 a.idcard,a.id,a.`name`,a.birthday,a.phone,a.sex,a.mobile,TIMESTAMPDIFF(YEAR,a.birthday,NOW()) 'age',\n" +
                "	   (\n" +
                "		SELECT GROUP_CONCAT(q.`name`) FROM base_disease_hospital q \n" +
                "        INNER JOIN wlyy_patient_rehabilitation_plan w ON q.id = w.disease \n" +
                "		 WHERE 1 = 1 AND w.patient=a.id  GROUP BY w.patient\n" +
                "	  ) 'diseaseListName',\n" +
                "	   ) 'diseaseListName',\n" +
                "      (\n" +
                "        SELECT GROUP_CONCAT(DISTINCT w.plan_doctor_name) FROM wlyy_patient_rehabilitation_plan w WHERE a.id = w.patient \n" +
                "      ) 'planDoctorListName',\n" +
                "	   (\n" +
                "			SELECT count(1) FROM wlyy_patient_rehabilitation_plan w \n" +
                "			INNER JOIN wlyy_rehabilitation_plan_detail q ON w.id = q.plan_id \n" +
                "           INNER JOIN base_service_item_plan e ON e.plan_detail_id = q.id \n" +
                "			WHERE 1 = 1 AND w.patient = a.id \n" +
                "		)'itemAllCount',\n" +
                "		(\n" +
                "			SELECT count(1) FROM wlyy_patient_rehabilitation_plan w \n" +
                "			INNER JOIN wlyy_rehabilitation_plan_detail q ON w.id = q.plan_id \n" +
                "			WHERE	1 = 1 	AND q.`status`='0'	AND w.patient = a.id \n" +
                "           INNER JOIN base_service_item_plan e ON e.plan_detail_id = q.id \n" +
                "			WHERE	1 = 1 	AND e.`status`='0'	AND w.patient = a.id \n" +
                "		)'unFinishCount',\n" +
                "		(\n" +
                "			SELECT count(1) 	FROM wlyy_patient_rehabilitation_plan w \n" +
                "			INNER JOIN wlyy_rehabilitation_plan_detail q ON w.id = q.plan_id \n" +
                "			WHERE	1 = 1 	AND q.`status`='1'	AND w.patient = a.id \n" +
                "           INNER JOIN base_service_item_plan e ON e.plan_detail_id = q.id \n" +
                "			WHERE	1 = 1 	AND e.`status`='1'	AND w.patient = a.id \n" +
                "		)'finishCount',\n" +
                "		0 'totayTask'\n" +
                "		(\n" +
                "			SELECT count(1) FROM wlyy_patient_rehabilitation_plan w \n" +
                "			INNER JOIN wlyy_rehabilitation_plan_detail q ON w.id = q.plan_id \n" +
                "           INNER JOIN base_service_item_plan e ON e.plan_detail_id = q.id \n" +
                "			WHERE	1 = 1 	AND e.plan_time=DATE_FORMAT(NOW(),'%Y-%m-%d') AND e.`status`='0'	AND w.patient = a.id \n" +
                "		)'totayTask'\n" +
                "FROM\n" +
                "	base_patient a\n" +
                "	INNER JOIN wlyy_patient_rehabilitation_plan b ON a.id = b.patient\n" +
                "	INNER JOIN wlyy_rehabilitation_patient_info c ON c.patient = b.patient \n" +
                "	left JOIN wlyy_patient_rehabilitation_plan b ON a.id = b.patient\n" +
                "   LEFT JOIN wlyy_rehabilitation_plan_detail d on b.id = d.plan_id "+
                "	INNER JOIN wlyy_rehabilitation_patient_info c ON c.patient = a.id \n" +
                "WHERE\n" +
                "	1 = 1 \n" +
                "	AND a.del = '1'\n";
        if (StringUtils.isNotBlank(doctorId) && StringUtils.isBlank(patientId)) {
            //计划负责人或者任务执行人-执行人不为空
            sql += "	AND (b.plan_doctor='" + doctorId + "' OR c.doctor='" + doctorId + "' )";
            sql += "	AND (b.plan_doctor='" + doctorId + "' OR c.doctor='" + doctorId + "' or d.doctor='"+doctorId+"')";
            sql += " and  c.doctor is not null  ";
        }
@ -1169,19 +1184,21 @@ public class RehabilitationInfoService {
    public HashMap<String, Object> getRehabilitationPatientPlanCount(String doctorId) {
        String sql =
                "SELECT DISTINCT \n" +
                        "	 a.id,a.`name`,a.birthday,a.phone,a.sex,a.mobile,c.age,\n" +
                        "	 a.id,a.`name`,a.birthday,a.phone,a.sex,a.mobile,TIMESTAMPDIFF(YEAR,a.birthday,NOW()) 'age',\n" +
                        "	  (\n" +
                        "		SELECT GROUP_CONCAT(q.`name`) FROM base_disease_hospital q  INNER JOIN wlyy_patient_rehabilitation_plan w ON q.id = w.disease \n" +
                        "		 WHERE 1 = 1 AND w.patient=a.id  GROUP BY w.patient\n" +
                        "	  ) 'diseaseListName',\n" +
                        "		(\n" +
                        "			SELECT count(1) 	FROM wlyy_patient_rehabilitation_plan w \n" +
                        "			INNER JOIN wlyy_rehabilitation_plan_detail q ON w.id = q.plan_id \n" +
                        "			WHERE		1 = 1 	AND q.`status`='0'		AND w.patient = a.id \n" +
                        "		)'unFinishCount'\n" +
                        "	  (\n" +
                        "	  	SELECT count(1)  FROM wlyy_patient_rehabilitation_plan w \n" +
                        "	  	INNER JOIN wlyy_rehabilitation_plan_detail q ON w.id = q.plan_id \n" +
                        "       INNER JOIN base_service_item_plan e ON e.plan_detail_id = q.id \n" +
                        "	  	WHERE 1 = 1  AND e.`status`='0'	 AND w.patient = a.id \n" +
                        "	  )'unFinishCount'\n" +
                        "FROM\n" +
                        "	base_patient a\n" +
                        "	INNER JOIN wlyy_patient_rehabilitation_plan b ON a.id = b.patient\n" +
                        "   LEFT JOIN wlyy_rehabilitation_plan_detail d on b.id = d.plan_id "+
                        "	INNER JOIN wlyy_rehabilitation_patient_info c ON c.patient = b.patient \n" +
                        "WHERE\n" +
                        "	1 = 1 \n" +
@ -1189,7 +1206,7 @@ public class RehabilitationInfoService {
        if (StringUtils.isNotBlank(doctorId)) {
            //计划负责人或者任务执行人-执行人不为空
            sql += "	AND (b.plan_doctor='" + doctorId + "' OR c.doctor='" + doctorId + "' )";
            sql += "	AND (b.plan_doctor='" + doctorId + "' OR c.doctor='" + doctorId + "' or d.doctor='"+doctorId+"')";
            sql += " and  c.doctor is not null  ";
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
@ -1215,11 +1232,12 @@ public class RehabilitationInfoService {
    /**
     * todo 还需要代办项目还需要重新join一张新表 todayTaskCount 今日任务项,等后面在整
     */
    public List<Map<String, Object>> getPatientRehabilitationByPatientId(String patientId,String planId) {
    public List<Map<String, Object>> getPatientRehabilitationByPatientId(String patientId, String planId) {
        String sql = "SELECT DISTINCT \n" +
                "	 a.id,a.`name`,a.birthday,a.phone,a.sex,a.mobile,c.age,a.idcard,\n" +
                "	 b.id 'planId',b.title 'planTitle',b.plan_doctor_name 'planDoctorName',d. `name` 'diseaseName',c.dept_name 'deptName',\n" +
                "	 b.`status` 'planStatus', c.hospital_name 'hospitalName'," +
                "	 a.id,a.`name`,a.birthday,a.phone,a.sex,a.mobile,TIMESTAMPDIFF(YEAR,a.birthday,NOW()) 'age',a.idcard,\n" +
                "	 b.id 'planId',b.title 'planTitle',b.plan_doctor 'planDoctor',b.plan_doctor_name 'planDoctorName'" +
                ",d. `name` 'diseaseName',c.dept_name 'deptName',\n" +
                "	 b.`status` 'planStatus', c.hospital_name 'hospitalName',b.medical_records_code medicalRecordsCode," +
                "    c.from_source, " +
                "       CASE  \n" +
                "        WHEN c.from_source='1' THEN '手动添加'\n" +
@ -1228,13 +1246,14 @@ public class RehabilitationInfoService {
                "      END 'fromSourceName',\n" +
                "     c.ijk_id, c.status,'patientStatus'," +
                "     b.advice_content 'adviceContent',\n" +
                "	 (SELECT count(1) FROM wlyy_rehabilitation_plan_detail q WHERE	1 = 1 AND q.plan_id = b.id )'itemAllCount',\n" +
                "	 (SELECT count(1) FROM wlyy_rehabilitation_plan_detail q WHERE	1 = 1 AND q.`status`='1' AND q.plan_id = b.id )'finishCount',\n" +
                "	 0 'todayTaskCount'\n" +
                "	 (SELECT count(1) FROM wlyy_rehabilitation_plan_detail q INNER JOIN base_service_item_plan w ON w.plan_detail_id = q.id WHERE 1 = 1 AND q.plan_id = b.id )'itemAllCount',\n" +
                "	 (SELECT count(1) FROM wlyy_rehabilitation_plan_detail q INNER JOIN base_service_item_plan w ON w.plan_detail_id = q.id WHERE 1 = 1 AND w.`status`='1' AND q.plan_id = b.id )'finishCount',\n" +
                "	 (SELECT count(1) FROM wlyy_rehabilitation_plan_detail q INNER JOIN base_service_item_plan w ON w.plan_detail_id = q.id WHERE 1 = 1 AND w.`status`='0' AND q.plan_id = b.id )'unFinishCount',\n" +
                "	 (SELECT count(1) FROM wlyy_rehabilitation_plan_detail q INNER JOIN base_service_item_plan w ON w.plan_detail_id = q.id WHERE 1 = 1 AND w.`status`='0' AND w.plan_time=DATE_FORMAT(NOW(),'%Y-%m-%d') AND q.plan_id = b.id )'todayTaskCount' \n" +
                "FROM\n" +
                "	base_patient a\n" +
                "	LEFT JOIN wlyy_patient_rehabilitation_plan b ON a.id = b.patient\n" +
                "	LEFT JOIN wlyy_rehabilitation_patient_info c ON c.patient = b.patient \n" +
                "	INNER JOIN wlyy_rehabilitation_patient_info c ON c.code = b.patient_info_code \n" +
                "	LEFT JOIN base_disease_hospital d ON  d.id=b.disease\n" +
                "WHERE\n" +
                "	1 = 1 \n" +
@ -1255,9 +1274,9 @@ public class RehabilitationInfoService {
                "	CASE \n" +
                "		WHEN d.`status`='0' THEN '未下转'\n" +
                "		WHEN d.`status`='1' THEN '待分配'\n" +
                "		WHEN d.`status`='2' THEN '创建计划过程失败'\n" +
                "		WHEN d.`status`='3' THEN '患者无住院病历信息'\n" +
                "		WHEN d.`status`='5' THEN '同步居民失败'\n" +
//                "		WHEN d.`status`='2' THEN '创建计划过程失败'\n" +
//                "		WHEN d.`status`='3' THEN '患者无住院病历信息'\n" +
//                "		WHEN d.`status`='5' THEN '同步居民失败'\n" +
                "		WHEN d.`status`='7' THEN '已管理'\n" +
                "  END 'statusName',\n" +
                "  d.`status`,count(1) 'count' \n" +
@ -1311,7 +1330,7 @@ public class RehabilitationInfoService {
            sql += " and b.id= '" + itemId + "'";
        }
        if (StringUtils.isNotBlank(status)) {
            sql += " and a.status =" + status + "'";
            sql += " and a.status =" + status;
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;

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

@ -2,13 +2,20 @@ package com.yihu.jw.hospital.module.rehabilitation.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.cron.CronUtils;
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.SignFamily;
import com.yihu.jw.entity.followup.Followup;
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.module.door.dao.ServiceItemPlanDao;
import com.yihu.jw.hospital.module.followup.dao.FollowUpDao;
import com.yihu.jw.hospital.module.followup.service.FollowUpService;
import com.yihu.jw.hospital.module.rehabilitation.dao.*;
import com.yihu.jw.hospital.module.specialist.dao.PatientDiseaseServerDao;
import com.yihu.jw.hospital.module.specialist.dao.PatientMedicalRecordsRehabilitationDao;
@ -19,6 +26,7 @@ import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
@ -36,6 +44,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
@ -46,8 +55,6 @@ import java.util.stream.Collectors;
@Transactional
public class RehabilitationManageService {
    @Value("${basedb.name}")
    private String basedb;
    @Value("${im.data_base_name}")
    private String imDBName;
@ -56,6 +63,8 @@ public class RehabilitationManageService {
    @Autowired
    private RehabilitationDetailDao rehabilitationDetailDao;
    @Autowired
    private RehabilitationServiceItemDao serviceItemDao;
    @Autowired
    private PatientRehabilitationPlanDao patientRehabilitationPlanDao;
    @Autowired
    private GuidanceMessageLogDao guidanceMessageLogDao;
@ -73,13 +82,31 @@ public class RehabilitationManageService {
    private BasePatientDao patientDao;
    @Autowired
    private PatientMedicalRecordsRehabilitationDao medicalRecordsRehabilitationDao;
    @Autowired
    private RehabilitationPatientInfoDao rehabilitationPatientInfoDao;
    @Autowired
    private PatientDiseaseServerDao patientDiseaseServerDao;
    @Autowired
    private SystemDictService systemDictService;
    @Autowired
    private PatientRehabilitationPlanLogDao patientRehabilitationPlanLogDao;
    @Autowired
    private ServiceItemPlanDao serviceItemPlanDao;
    @Autowired
    private FollowUpService followUpService;
    @Autowired
    private FollowUpDao followupDao;
    //近期康复记录
    public Envelop recentServiceItemPlanRecords(String patient,Integer page,Integer size){
        String sql = "select p.* ";
        String countSql = "select count(p.id) ";
        String filter = " from base_service_item_plan p where p.patient='"+patient+"' and p.plan_time<='"+DateUtil.getStringDateShort()+" 23:59:59' ";
        String ordereBy = " order by p.plan_time desc limit "+(page-1)*size+","+size;
        List<ServiceItemPlanDO> planDOList = jdbcTemplate.query(sql+filter+ordereBy,new BeanPropertyRowMapper<>(ServiceItemPlanDO.class));
        long count = jdbcTemplate.queryForObject(countSql+filter,Long.class);
        return PageEnvelop.getSuccessListWithPage("获取成功",planDOList,page,size,count);
    }
    //添加康复计划日志
    public void addPlanLog(String planId,String doctorCode,String doctorName){
@ -117,6 +144,9 @@ public class RehabilitationManageService {
        List<RehabilitationDetailDO> detailDOList = planDO.getDetailDOList();
        Map<String,RehabilitationDetailDO> map = detailDOList.stream().collect(Collectors.toMap
                (RehabilitationDetailDO::getHospitalServiceItemId, log->log,(oldLog, newLog)->oldLog));
        List<ServiceItemPlanDO> planDOList = new ArrayList<>();
        List<RehabilitationServiceItemDO> itemDOList = serviceItemDao.findList();
        Map<String, String> serviceItemMap = itemDOList.stream().collect(Collectors.toMap(RehabilitationServiceItemDO::getCode, RehabilitationServiceItemDO::getName));
        for (RehabilitationDetailDO detailDO : detailDOS){
            String serviceItemId = detailDO.getHospitalServiceItemId();
            if(map.containsKey(serviceItemId)){
@ -125,12 +155,63 @@ public class RehabilitationManageService {
                detailDO.setDoctorName(newDetail.getDoctorName());
                detailDO.setDept(newDetail.getDept());
                detailDO.setDeptName(newDetail.getDeptName());
                //生成执行计划列表
                planDOList = addServicePlan(serviceItemMap,planDO1,detailDO,planDOList);
            }
        }
        rehabilitationDetailDao.saveAll(detailDOS);
        if(planDOList.size()>0){
            serviceItemPlanDao.saveAll(planDOList);
        }
        planDO1.setStatus(1);
        patientRehabilitationPlanDao.save(planDO1);
        addPlanLog(planDO.getId(),uid,null);
        //更新状态
        if(StringUtils.isNotBlank(planDO1.getPatientInfoCode())){
            RehabilitationPatientInfoDO infoDO = rehabilitationPatientInfoDao.findByCode(planDO1.getPatientInfoCode());
            infoDO.setStatus(7);
            rehabilitationPatientInfoDao.save(infoDO);
        }
    }
    public List<ServiceItemPlanDO> addServicePlan(Map<String, String> serviceItemMap,PatientRehabilitationPlanDO planDO,
                                                  RehabilitationDetailDO detailDO,List<ServiceItemPlanDO> planDOList){
        String planId = planDO.getId();
        String pateint = planDO.getPatient();
        String relationType = detailDO.getHospitalServiceItemId();
        Integer plan_start_time_type = detailDO.getTimeType();//计划开始时间类型
        String server_count = detailDO.getServerCount();//服务次数
        if(StringUtils.isBlank(server_count)){
            return planDOList;
        }
        String planDetailId = detailDO.getId();
        String doctor = detailDO.getDoctor();
        String doctorName = detailDO.getDoctorName();
        String frequency_code = detailDO.getFrequencyCode();
        LocalDateTime localDateTime = LocalDateTime.now();
        int addNum = 0;
        localDateTime = localDateTime.plusDays(addNum);
        List<String>  timeList = CronUtils.getExecutionTimeByNum(frequency_code,Integer.parseInt(server_count),localDateTime);
        for (String time :timeList){
            ServiceItemPlanDO itemPlanDO = new ServiceItemPlanDO();
            itemPlanDO.setPlanTime(time);
            itemPlanDO.setPatient(pateint);
            itemPlanDO.setName(serviceItemMap.get(relationType));
            itemPlanDO.setStatus("0");
            itemPlanDO.setRelationType(relationType);
            itemPlanDO.setPlanId(planId);
            itemPlanDO.setPlanDetailId(planDetailId);
            itemPlanDO.setDoctor(doctor);
            itemPlanDO.setDoctorName(doctorName);
            if("6".equals(relationType)){
                Followup followup = followUpService.addRehabilatationFollowup(itemPlanDO);
                if(followup!=null){
                    itemPlanDO.setRelationCode(followup.getId()+"");
                }
            }
            planDOList.add(itemPlanDO);
        }
        return planDOList;
    }
    public List<Map<String, Object>> selectPlanByPatient(String patient, Integer status, String planId, String doctor) {
@ -309,7 +390,7 @@ public class RehabilitationManageService {
                resultMap.put("id", one.get("id"));
                resultMap.put("status", one.get("status"));//康复计划状态
                //健康情况
                String healthyConditionSql = " select  label_name,label from " + basedb + ".wlyy_sign_patient_label_info where status=1 and patient='" + one.get("patient") + "' and label_type=8";
                String healthyConditionSql = " select  label_name,label from wlyy_sign_patient_label_info where status=1 and patient='" + one.get("patient") + "' and label_type=8";
                List<Map<String, Object>> healthyConditionList = jdbcTemplate.queryForList(healthyConditionSql);
                String healthyCondition = healthyConditionList.size() > 0 ? healthyConditionList.get(0).get("label_name") + "" : "";
                String healthyConditionType = healthyConditionList.size() > 0 ? healthyConditionList.get(0).get("label") + "" : "";
@ -376,14 +457,16 @@ public class RehabilitationManageService {
            Map<String, Object> resultMap = new HashMap<>();
            Integer isOperator = 0;
            resultMap.put("patientCode", patientCode);//居民code
            String healthyConditionSql = " select  label_name,label from " + basedb + ".wlyy_sign_patient_label_info where status=1 and patient='" + patientCode + "' and label_type=8";
            String healthyConditionSql = " select  label_name,label from wlyy_sign_patient_label_info where status=1 and patient='" + patientCode + "' and label_type=8";
            List<Map<String, Object>> healthyConditionList = jdbcTemplate.queryForList(healthyConditionSql);
            String healthyCondition = healthyConditionList.size() > 0 ? healthyConditionList.get(0).get("label_name") + "" : "";
            String healthyConditionType = healthyConditionList.size() > 0 ? healthyConditionList.get(0).get("label") + "" : "";
            resultMap.put("healthyCondition", healthyCondition);
            resultMap.put("healthyConditionType", healthyConditionType);
            //专科医生
            String specialistRelationSql = "select r.*,t.name as teamName,h.name as specialistHospitalName from wlyy_specialist_patient_relation r left join " + basedb + ".wlyy_admin_team t on r.team_code=t.id left join " + basedb + ".dm_hospital h on t.org_code=h.code where r.sign_status ='1' and r.status in('0','1') and r.patient='" + patientCode + "' and r.doctor='" + doctorCode + "'";
            String specialistRelationSql = "select r.*,t.name as teamName,h.name as specialistHospitalName " +
                    "from wlyy_specialist_patient_relation r left join wlyy_admin_team t on r.team_code=t.id left join " +
                    "dm_hospital h on t.org_code=h.code where r.sign_status ='1' and r.status in('0','1') and r.patient='" + patientCode + "' and r.doctor='" + doctorCode + "'";
            specialistRelationSql = TransforSqlUtl.specialistPatientRelationAll2(specialistRelationSql);
            List<Map<String, Object>> specialistRelationList = jdbcTemplate.queryForList(specialistRelationSql);
            Map<String, Object> specialistMap = specialistRelationList.get(0);
@ -401,7 +484,8 @@ public class RehabilitationManageService {
            resultMap.put("specialistFinishItemCount", specialistFinishCount1 - specialistUnfinishCount1 + specialistFinishCount2 - specialistUnfinishCount2);//完成项目
            resultMap.put("specialistServiceRecordCount", specialistServiceCount1 + specialistServiceCount2);//服务次数
            //家庭医生(包括全科医生、健管师)
            String signFamilySql = "SELECT f.*,t.name as teamName FROM " + basedb + ".wlyy_sign_family f LEFT JOIN " + basedb + ".wlyy_admin_team t on f.admin_team_code=t.id where f.status =1 and f.expenses_status='1' and f.patient='" + patientCode + "'";
            String signFamilySql = "SELECT f.*,t.name as teamName FROM wlyy_sign_family f LEFT JOIN " +
                    "wlyy_admin_team t on f.admin_team_code=t.id where f.status =1 and f.expenses_status='1' and f.patient='" + patientCode + "'";
            List<Map<String, Object>> signFamilyList = jdbcTemplate.queryForList(signFamilySql);
            if (signFamilyList != null && signFamilyList.size() > 0) {
                Map<String, Object> signFamilyMap = signFamilyList.get(0);
@ -432,7 +516,7 @@ public class RehabilitationManageService {
                resultMap.put("patientName", signFamilyMap.get("patientName"));
            }
            //疾病类型
            String diseaseSql = " select s.* from " + basedb + ".wlyy_patient_disease_server s where s.del=1 and s.patient='" + patientCode + "' and s.specialist_relation_code='" + specialistMap.get("id") + "' ";
            String diseaseSql = " select s.* from wlyy_patient_disease_server s where s.del=1 and s.patient='" + patientCode + "' and s.specialist_relation_code='" + specialistMap.get("id") + "' ";
            List<Map<String, Object>> diseaseList = jdbcTemplate.queryForList(diseaseSql);
            List<String> disease = new ArrayList<>();
            for (Map<String, Object> one2 : diseaseList) {
@ -504,27 +588,26 @@ public class RehabilitationManageService {
     * @param doctorCode   登陆医生
     * @param taskExecutor 任务执行者 0全部;1我的任务 2他人任务
     */
    public ObjEnvelop calendarPlanDetail(String executeStartTime, String executeEndTime, String planId, Integer searchTask, Integer status, String doctorCode, String taskExecutor) throws Exception {
    public ObjEnvelop calendarPlanDetail(String executeStartTime, String executeEndTime, String planId, Integer searchTask,
                                         Integer status, String doctorCode, String taskExecutor) throws Exception {
        String[] planIdlist = planId.split(",");
        StringBuilder planCondition = new StringBuilder();
        planCondition.append("'" + planIdlist[0] + "'");
        for (int i = 1; i < planIdlist.length; i++) {
            planCondition.append(",'" + planIdlist[i] + "'");
        }
        String sql = " select d.* from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id " +
                " where  d.plan_id in (" + planCondition + ") ";
        String sql = " select d.* from base_service_item_plan d  where d.plan_id in (" + planCondition + " ) ";
        if (StringUtils.isNotBlank(executeStartTime)) {
            sql += " and d.execute_time>='" + executeStartTime + "' ";
            sql += " and d.plan_time>='" + executeStartTime + "' ";
        }
        if (StringUtils.isNotBlank(executeEndTime)) {
            sql += " and d.execute_time<='" + executeEndTime + "' ";
            sql += " and d.plan_time<='" + executeEndTime + " 23:59:59' ";
        }
        if (searchTask != null) {
            if (searchTask == 8) {
                sql += " and d.doctor='" + doctorCode + "' ";
            } else {
                sql += " and i.code=" + searchTask + " ";
                sql += " and d.relation_type=" + searchTask + " ";
            }
        }
        if (taskExecutor.equals("1")) { //我的任务
@ -534,80 +617,42 @@ public class RehabilitationManageService {
            sql += "and d.doctor <>'" + doctorCode + "' ";
        }
        if (status != null) {
            sql += " and d.status=" + status;
            sql += " and d.status='" + status+"' ";
        }
        sql += " ORDER BY d.execute_time ";
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll2(sql);
        sql += " ORDER BY d.plan_time ";
        List<Map<String, Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
        Map<String, Map<String, Object>> map = new LinkedHashMap<>();
        for (Map<String, Object> one : rehabilitationDetailList) {
            String executeTime = DateUtil.dateToStr((Date) one.get("execute_time"), DateUtil.YYYY_MM_DD);
            Map<String, Object> m = null;
            String executeTime = (one.get("plan_time")+"").substring(0,10);
            Map<String, Object> m = new HashMap<>();
            if (map.containsKey(executeTime)) {
                m = map.get(executeTime);
                Map<String, Integer> family = null;
                Map<String, Integer> specialist = null;
                if (one.get("type") != null) {
                    if ((Integer) one.get("type") == 1) {//家庭医生
                        if (m.containsKey("family")) {
                            family = (Map<String, Integer>) m.get("family");
                        } else {
                            family = new HashMap<>();
                            family.put("all", 0);
                            family.put("finish", 0);
                        }
                        if ((Integer) one.get("status") == 1) {
                            family.put("finish", family.get("finish") + 1);
                        }
                        family.put("all", family.get("all") + 1);
                        m.put("family", family);
                    } else if ((Integer) one.get("type") == 2) {//专科医生
                        if (m.containsKey("specialist")) {
                            specialist = (Map<String, Integer>) m.get("specialist");
                        } else {
                            specialist = new HashMap<>();
                            specialist.put("all", 0);
                            specialist.put("finish", 0);
                        }
                        if ((Integer) one.get("status") == 1) {
                            specialist.put("finish", (specialist.get("finish")) + 1);
                        }
                        specialist.put("all", (specialist.get("all")) + 1);
                        m.put("specialist", specialist);
                    }
                if (m.containsKey("doctor")) {
                    specialist = (Map<String, Integer>) m.get("doctor");
                } else {
                    specialist = new HashMap<>();
                    specialist.put("all", 0);
                    specialist.put("finish", 0);
                }
            } else {
                m = new HashMap<>();
//                m.put("specialist",new HashMap<String,Object>());
                if (one.get("type") != null) {
                    if ((Integer) one.get("type") == 1) {//家庭医生
                        Map<String, Integer> family = new HashMap<>();
                        family.put("all", 0);
                        family.put("finish", 0);
                        if ((Integer) one.get("status") == 1) {
                            family.put("finish", family.get("finish") + 1);
                        }
                        family.put("all", family.get("all") + 1);
                        m.put("family", family);
                    } else if ((Integer) one.get("type") == 2) {//专科医生
                        Map<String, Integer> specialist = new HashMap<>();
                        specialist.put("all", 0);
                        specialist.put("finish", 0);
                        if ((Integer) one.get("status") == 1) {
                            specialist.put("finish", specialist.get("finish") + 1);
                        }
                        specialist.put("all", specialist.get("all") + 1);
                        m.put("specialist", specialist);
                    }
                if ("1".equals(one.get("status")+"")) {
                    specialist.put("finish", (specialist.get("finish")) + 1);
                }
                specialist.put("all", (specialist.get("all")) + 1);
                m.put("doctor", specialist);
            }else{
                Map<String, Integer> specialist = new HashMap<>();
                specialist.put("all", 0);
                specialist.put("finish", 0);
                if ("1".equals(one.get("status")+"")) {
                    specialist.put("finish", specialist.get("finish") + 1);
                }
                specialist.put("all", specialist.get("all") + 1);
                m.put("doctor", specialist);
            }
            //myTaskFlag,1:有自己任务,0:没有自己任务
            if (StringUtils.isNotEmpty(doctorCode)) {
                if (m.containsKey("myTaskFlag")) {
                    if ((Integer) m.get("myTaskFlag") == 0) {
                        if (doctorCode.equals(one.get("doctor").toString())) {
@ -625,9 +670,9 @@ public class RehabilitationManageService {
                }
            }
            if (m.containsKey("planDetailIds")) {
                m.put("planDetailIds", m.get("planDetailIds") + "," + one.get("id"));
                m.put("serviceItemIds", m.get("serviceItemIds") + "," + one.get("id"));
            } else {
                m.put("planDetailIds", one.get("id") + "");
                m.put("serviceItemIds", one.get("id") + "");
            }
            map.put(executeTime, m);
        }
@ -640,111 +685,70 @@ public class RehabilitationManageService {
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, map);
    }
    /**
     * 康复管理-康复计划按列表展示
     *
     * @param executeStartTime
     * @param executeEndTime
     * @param planId
     * @param searchTask
     * @param status
     * @param doctorCode
     * @return
     * @throws Exception
     */
    public JSONArray calendarPlanDetailList(String executeStartTime, String executeEndTime, String planId, Integer searchTask, Integer status, String doctorCode) throws Exception {
        Map<String, Object> param = new HashedMap();
        param.put("executeStartTime", executeStartTime);
        param.put("executeEndTime", executeEndTime);
        param.put("planId", planId);
        param.put("searchTask", searchTask);
        param.put("status", status);
        param.put("doctorCode", doctorCode);
        ObjEnvelop objEnvelop = calendarPlanDetailList(planId, searchTask, status, doctorCode, executeStartTime, executeEndTime, "0");
        org.json.JSONObject result = new org.json.JSONObject(objEnvelop);
        if (result.getInt("status") == 200) {
            return result.getJSONArray("obj");
        }
        throw new Exception("请求失败!");
    }
    /**
     * 日历列表
     *
     * @param planId       计划id
     * @param searchTask   快速查找任务(1、我的任务,2、随访,3、复诊,4、健康教育)
     * @param searchTask   快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)
     * @param status       任务状态(0未完成,1已完成,2已预约)
     * @param doctorCode   登陆医生
     * @param taskExecutor 任务执行者 0全部;1我的任务 2他人任务
     */
    public ObjEnvelop calendarPlanDetailList(String planId, Integer searchTask, Integer status, String doctorCode, String executeStartTime, String executeEndTime, String taskExecutor) {
    public ObjEnvelop calendarPlanDetailList(String planId, Integer searchTask, Integer status, String doctorCode,
                                             String executeStartTime, String executeEndTime, String taskExecutor) {
        String[] planIdlist = planId.split(",");
        StringBuilder planCondition = new StringBuilder();
        planCondition.append("'" + planIdlist[0] + "'");
        for (int i = 1; i < planIdlist.length; i++) {
            planCondition.append(",'" + planIdlist[i] + "'");
        }
        String sql = " select d.*,DATE_FORMAT(d.execute_time,'%Y/%m/%d %H:%i') as executeTime ,i.code,IF(d.followup_detail_type=1,'社区随访(厦心)',i.name) name,1 as flag from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id  " +
                " where  d.plan_id in (" + planCondition + " )AND  d.execute_time IS NOT NULL  and d.execute_time <>'' ";
        String sql = " select d.* from base_service_item_plan d  where d.plan_id in (" + planCondition + " ) ";
        if (searchTask != null) {
            if (searchTask == 8) {//
                if (StringUtils.isNotBlank(doctorCode)) {
                    sql += " and d.doctor='" + doctorCode + "' ";
                }
                //sql+=" and i.code="+searchTask+" " ;
            } else {
                sql += " and i.code=" + searchTask + " ";
            }/*else if(searchTask==5){
                sql+=" and i.reserve=1 " ;
            }*/
                sql += " and d.relation_type='" + searchTask + "' ";
            }
        }
        if (taskExecutor.equals("1")) { //我的任务
        if ("1".equals(taskExecutor)) { //我的任务
            sql += "and d.doctor='" + doctorCode + "' ";
        }
        if (taskExecutor.equals("2")) {//他人任务
        if ("2".equals(taskExecutor)) {//他人任务
            sql += "and d.doctor <>'" + doctorCode + "' ";
        }
        if (StringUtils.isNoneBlank(executeEndTime) && StringUtils.isNoneBlank(executeStartTime)) {
            sql += "and d.execute_time>='" + executeStartTime + "' and d.execute_time<='" + executeEndTime + "' ";
            sql += "and d.plan_time>='" + executeStartTime + "' and d.plan_time<='" + executeEndTime + " 23:59:59' ";
        }
        if (status != null) {
            sql += "and d.status=" + status;
        }
        sql += "  order by d.execute_time desc ";
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll2(sql);
        List<Map<String, Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
        String planPatientSql = " SELECT p.patient FROM wlyy_patient_rehabilitation_plan p " +
                "INNER JOIN wlyy.wlyy_sign_family f ON p.patient = f.patient  WHERE p.id in (" + planCondition + " ) " +
                "AND f.`status` = 1 AND f.expenses_status = 1 AND  f.doctor = '" + doctorCode + "' ";
        List<Map<String, Object>> patientCodeList = jdbcTemplate.queryForList(planPatientSql);
        List<Map<String, Object>> list = null;
        if (patientCodeList.size() > 0 && null != searchTask) {
            String patient = patientCodeList.get(0).get("patient").toString();
            if (7 == searchTask) { //处方续方 flag 用于判断 1.7.0.5 新增
                String cfxfSql = "SELECT LEFT ( pr.create_time, 19 ) AS executeTime ,LEFT ( pr.pres_create_time, 19 ) AS buildCreateTime , pr.doctor AS doctorCode, pr.doctor_name AS doctorNmae,pr.`status`," +
                        " pr.hospital_name, pr.hospital, p.`name` AS patientName,p.code AS patientCode,pr.`code` AS id,7 as code, 2 as flag " +
                        " FROM  wlyy.wlyy_prescription pr  LEFT JOIN wlyy.wlyy_patient p ON pr.patient = p.`code` WHERE " +
                        "  1 = 1  AND pr.STATUS = '100' AND p.code= '" + patient + "' GROUP BY  pr.CODE ";
                list = jdbcTemplate.queryForList(cfxfSql);
            }
            if (6 == searchTask) { //随访
                String sfSql = "SELECT DISTINCT DATE_FORMAT(wf.followup_date,'%Y/%m/%d %H:%i') followupDate,DATE_FORMAT(wf.followup_plan_date,'%Y/%m/%d %H:%i') executeTime,wf.doctor_code doctorCode,wf.followup_class followupClass, " +
                        " wf.patient_code AS patientCode,wf.patient_name AS patientName,wf.doctor_name doctorName,wf.`status` AS `status`,wf.org_name orgName," +
                        " wf.org_code orgCode,sd.value AS `value`, wf.followup_type  followupType,wf.id AS id, 6 AS code,2 as flag FROM  wlyy.wlyy_followup wf " +
                        " LEFT JOIN wlyy.system_dict sd ON wf.followup_type = sd.CODE " +
                        " AND sd.dict_name = 'FOLLOWUP_WAY_DICT' WHERE wf.status !=0  AND wf.patient_code = '" + patient + "' order by wf.followup_plan_date desc  ";
                list = jdbcTemplate.queryForList(sfSql);
            }
            if (list != null && list.size() > 0) {
                rehabilitationDetailList.addAll(list);
            }
        }
            sql += "and d.status='" + status+"' ";
        }
        sql += "  order by d.plan_time desc ";
        List<ServiceItemPlanDO> rehabilitationDetailList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(ServiceItemPlanDO.class));
//        if (rehabilitationDetailList.size() > 0 && null != searchTask) {
//            String patient = rehabilitationDetailList.get(0).getPatient();
//            if (7 == searchTask) { //处方续方 flag 用于判断 1.7.0.5 新增
//                String cfxfSql = "SELECT LEFT ( pr.create_time, 19 ) AS executeTime ,LEFT ( pr.pres_create_time, 19 ) AS buildCreateTime , pr.doctor AS doctorCode, pr.doctor_name AS doctorNmae,pr.`status`," +
//                        " pr.hospital_name, pr.hospital, p.`name` AS patientName,p.code AS patientCode,pr.`code` AS id,7 as code, 2 as flag " +
//                        " FROM  wlyy_prescription pr  LEFT JOIN base_patient p ON pr.patient = p.id WHERE " +
//                        "  1 = 1  AND pr.STATUS = '100' AND p.id= '" + patient + "' GROUP BY  pr.CODE ";
//
////                list = jdbcTemplate.queryForList(cfxfSql);
//            }
//            if (6 == searchTask) { //随访
//                String sfSql = "SELECT DISTINCT DATE_FORMAT(wf.followup_date,'%Y/%m/%d %H:%i') followupDate,DATE_FORMAT(wf.followup_plan_date,'%Y/%m/%d %H:%i') executeTime,wf.doctor_code doctorCode,wf.followup_class followupClass, " +
//                        " wf.patient_code AS patientCode,wf.patient_name AS patientName,wf.doctor_name doctorName,wf.`status` AS `status`,wf.org_name orgName," +
//                        " wf.org_code orgCode,sd.dict_value AS `value`, wf.followup_type  followupType,wf.id AS id, 6 AS code,2 as flag FROM  wlyy_followup wf " +
//                        " LEFT JOIN wlyy_hospital_sys_dict sd ON wf.followup_type = sd.dict_code " +
//                        " AND sd.dict_name = 'FOLLOWUP_WAY_DICT' WHERE wf.status !=0  AND wf.patient_code = '" + patient + "' order by wf.followup_plan_date desc  ";
//                list = jdbcTemplate.queryForList(sfSql);
//            }
//            if (list != null && list.size() > 0) {
//                rehabilitationDetailList.addAll(list);
//            }
//        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, rehabilitationDetailList);
    }
@ -1318,48 +1322,165 @@ public class RehabilitationManageService {
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, resultMap);
    }
    //康复计划服务项列表
    public List<RehabilitationDetailDO> rehabilitationDetailInfo(String planId,String status,String searchTask){
        String sql = "select * from wlyy_rehabilitation_plan_detail where plan_id='"+planId+"' ";
        if(StringUtils.isNotBlank(status)){
            sql += " and status="+status;
        }
        if(StringUtils.isNotBlank(searchTask)){
            sql += " and hospital_service_item_id='"+searchTask+"' ";
        }
        sql += " order by hospital_service_item_id";
        List<RehabilitationDetailDO> detailDOList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(RehabilitationDetailDO.class));
        List<RehabilitationServiceItemDO> itemDOList = serviceItemDao.findList();
        Map<String, String> serviceItemMap = itemDOList.stream().collect(Collectors.toMap(RehabilitationServiceItemDO::getCode, RehabilitationServiceItemDO::getName));
        List<ServiceItemPlanDO> planDOList = serviceItemPlanDao.findByPlanId(planId);
        Map<String,List<ServiceItemPlanDO>> planListMap = planDOList.stream().collect(Collectors.groupingBy(ServiceItemPlanDO::getRelationType));
        for (RehabilitationDetailDO detailDO:detailDOList){
            String key = detailDO.getHospitalServiceItemId();
            List<ServiceItemPlanDO> planDOS = planListMap.get(key);
            String completeTime = "";
            String planTime = "";
            int total = planDOS.size();
            int complete = 0;
            for (ServiceItemPlanDO planDO:planDOS){
                if("1".equals(planDO.getStatus())){
                    complete++;
                    if(completeTime.compareTo(planDO.getCompleteTime())<0){
                        completeTime = planDO.getCompleteTime();
                    }
                }else {
                    if("".equals(planTime)){
                        planTime = planDO.getPlanTime();
                    }else if(planTime.compareTo(planDO.getPlanTime())>0){
                        planTime = planDO.getPlanTime();
                    }
                }
            }
            detailDO.setTotalNum(total);
            detailDO.setFinishNum(complete);
            detailDO.setCompleteTime(completeTime);
            detailDO.setPlanTime(planTime);
            detailDO.setName(serviceItemMap.get(key));
        }
        return detailDOList;
    }
    //确认完成服务,填写服务笔记
    public ServiceItemPlanDO completePlan(String id,String content,String appendixs,String doctor){
        ServiceItemPlanDO planDO = serviceItemPlanDao.findById(id).orElse(null);
        if(!planDO.getDoctor().equals(doctor)){
            throw new ServiceException("不是您的任务,无法完成");
        }
        if("1".equals(planDO.getStatus())){
            throw new ServiceException("请勿重复填写");
        }
        planDO.setAppendixs(appendixs);
        planDO.setContent(content);
        planDO = completePlan(planDO);
        return planDO;
    }
    public ServiceItemPlanDO completePlan(ServiceItemPlanDO planDO){
        planDO.setStatus("1");
        planDO.setCompleteTime(DateUtil.getStringDate());
        serviceItemPlanDao.save(planDO);
        updPlanStatus(planDO.getPlanId(),planDO.getPlanDetailId());
        return planDO;
    }
    //完成随访
    public ServiceItemPlanDO completePlanFollowup(Long followupId){
        ServiceItemPlanDO serviceItemPlanDO = serviceItemPlanDao.findByRelationCodeAndRelationType(followupId+"","6");
        if(serviceItemPlanDO!=null&&"0".equals(serviceItemPlanDO.getStatus())){
            serviceItemPlanDO = completePlan(serviceItemPlanDO);
        }
        return serviceItemPlanDO;
    }
    //康复计划状态更新
    public void updPlanStatus(String planId,String planDetailId){
        List<ServiceItemPlanDO> itemPlanDOS =  serviceItemPlanDao.findByPlanDetailId(planDetailId,"0");
        if(itemPlanDOS.size()>0){
            //服务项计划都完成了
            jdbcTemplate.update("update wlyy_rehabilitation_plan_detail set status=1 where id='"+planDetailId+"'");
            String sql = "SELECT COUNT(*) total,COUNT(if(`status`=1,1,null)) num from wlyy_rehabilitation_plan_detail  " +
                    "WHERE plan_id='"+planId+"'";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            String total = list.get(0).get("total")+"";
            String num = list.get(0).get("num")+"";
            if(total.equals(num)){
                jdbcTemplate.update("update wlyy_patient_rehabilitation_plan set status=2 where id='"+planId+"'");
            }
        }
    }
    //执行计划详情
    public ServiceItemPlanDO findServiceItemPlanDetail(String id){
        ServiceItemPlanDO planDO = serviceItemPlanDao.findById(id).orElse(null);
        if(planDO!=null){
            String sql = "SELECT content from wlyy_guidance_message_log WHERE plan_detail_id ='"+id+"' LIMIT 1";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            if(list.size()>0){
                planDO.setGuidanceMessage(list.get(0).get("content")+"");
            }
        }
        String relationCode = planDO.getRelationCode();
        if("6".equals(planDO.getRelationType())&&StringUtils.isNotBlank(relationCode)){
            Followup followup = followupDao.findById(Long.parseLong(relationCode)).orElse(null);
            if(followup!=null){
                planDO.setFollowupStatus(followup.getStatus());
            }
        }
        return planDO;
    }
    //查询指导留言详情
    public GuidanceMessageLogDO findGuidanceMessageDetail(String itemPlanId){
        String sql = "SELECT * from wlyy_guidance_message_log WHERE plan_detail_id ='"+itemPlanId+"' LIMIT 1";
        List<GuidanceMessageLogDO> logDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(GuidanceMessageLogDO.class));
        if(logDOS.size()>0){
            return logDOS.get(0);
        }
        return null;
    }
    /**
     * 保存康复管理指导留言信息
     *
     * @param messageId
     * @param doctor
     * @param doctorType 1、专科医生,2、家庭医生
     * @param doctorType 1、专科医生,2、计划负责人
     */
    @Transactional
    public Envelop saveGuidanceMessage(String messageId, String doctor, Integer doctorType, String content, String planDetailId, Integer contentType) throws Exception {
        List<String> patientList = rehabilitationDetailDao.findPatientById(planDetailId);
        String patient = patientList.size() > 0 ? patientList.get(0) : "";
        GuidanceMessageLogDO guidanceMessageLogDO = new GuidanceMessageLogDO();
    public Envelop saveGuidanceMessage(String messageId, String doctor, Integer doctorType, String content,String imgs,
                                       String planDetailId, Integer contentType) {
        GuidanceMessageLogDO guidanceMessageLogDO = null;
        List<GuidanceMessageLogDO> logDOS =  guidanceMessageLogDao.findByPlanDetailId(planDetailId);
        if(logDOS.size()>0){
            guidanceMessageLogDO = logDOS.get(0);
            guidanceMessageLogDO.setUpdateTime(new Date());
        }else {
            guidanceMessageLogDO = new GuidanceMessageLogDO();
            guidanceMessageLogDO.setCreateTime(new Date());
            guidanceMessageLogDO.setUpdateTime(new Date());
        }
        guidanceMessageLogDO.setMessageId(messageId);
        guidanceMessageLogDO.setPlanDetailId(planDetailId);
        guidanceMessageLogDO.setContent(content);
        guidanceMessageLogDO.setDoctor(doctor);
        guidanceMessageLogDO.setContentType(contentType);
        guidanceMessageLogDO.setDoctorType(doctorType);
        Integer adminTeamCode = null;
        String doctorName = null;
        if (doctorType == 1) {
            SpecialistPatientRelationDO specialistPatientRelationDO = specialistPatientRelationDao.findByPatientAndDoctor(doctor, patient);
            adminTeamCode = specialistPatientRelationDO.getTeamCode();
            doctorName = specialistPatientRelationDO.getDoctorName();
        } else if (doctorType == 2) {
            String signFamilySql = " select f.* from " + basedb + ".wlyy_sign_family f where f.status=1 and f.expenses_status='1' and f.patient='" + patient + "'";
            List<Map<String, Object>> signFamily = jdbcTemplate.queryForList(signFamilySql);
            adminTeamCode = (Integer) signFamily.get(0).get("admin_team_code");
            doctorName = signFamily.get(0).get("doctor_name").toString();
        }
        String adminTeamSql = " select t.* from " + basedb + ".wlyy_admin_team t where t.available=1 and t.id=" + adminTeamCode;
        List<Map<String, Object>> adminTeam = jdbcTemplate.queryForList(adminTeamSql);
        String adminTeamName = adminTeam.get(0).get("name").toString();
        guidanceMessageLogDO.setAdminTeamCode(adminTeamCode);
        guidanceMessageLogDO.setAdminTeamName(adminTeamName);
        guidanceMessageLogDO.setDoctorName(doctorName);
        guidanceMessageLogDO.setCreateTime(new Date());
        guidanceMessageLogDO.setUpdateTime(new Date());
        guidanceMessageLogDao.save(guidanceMessageLogDO);
        return Envelop.getSuccess(SpecialistMapping.api_success);
        guidanceMessageLogDO.setImgs(imgs);
        BaseDoctorDO doctorDO = doctorDao.findByIdAndDel(doctor);
//        guidanceMessageLogDO.setAdminTeamCode(adminTeamCode);
//        guidanceMessageLogDO.setAdminTeamName(adminTeamName);
        guidanceMessageLogDO.setDoctorName(doctorDO.getName());
        guidanceMessageLogDO = guidanceMessageLogDao.save(guidanceMessageLogDO);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,guidanceMessageLogDO);
    }
    /**

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

@ -1,6 +1,5 @@
package com.yihu.jw.hospital.module.rehabilitation.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.fastdfs.FastDFSUtil;
@ -307,7 +306,7 @@ public class RehabilitationPlanService extends BaseJpaService<RehabilitationPlan
            planDO.setPlanDoctor(list.get(0).get("plan_doctor") + "");
            planDO.setPlanDoctorName(list.get(0).get("plan_doctor_name") + "");
        }
        System.out.println("111=>" + JSON.toJSONString(list));
        PatientMedicalRecordsDO recordsDO = planDO.getMedicalRecordsDO();
        String medicalRecordsCode = UUID.randomUUID().toString().replaceAll("-", "");
        recordsDO.setCode(medicalRecordsCode);
@ -319,7 +318,7 @@ public class RehabilitationPlanService extends BaseJpaService<RehabilitationPlan
        recordsDO.setDiseaseName(planDO.getDiseaseName());
        recordsDO.setCreateTime(new Date());
        patientMedicalRecordsDao.save(recordsDO);
        System.out.println("recordsDO==>" + JSON.toJSONString(recordsDO));
        planDO.setMedicalRecordsCode(medicalRecordsCode);
        String patientInfoCode = planDO.getPatientInfoCode();
        planDO.setStatus(3);//待分配 执行医生和科室
@ -330,14 +329,14 @@ public class RehabilitationPlanService extends BaseJpaService<RehabilitationPlan
        planDO.setCreateTime(new Date());
        planDO.setUpdateTime(new Date());
        planDO = patientRehabilitationPlanDao.save(planDO);
        System.out.println("planDO==>" + JSON.toJSONString(planDO));
        System.out.println("-------------------");
        List<RehabilitationDetailDO> detailDOList = new ArrayList<>();
        System.out.println("details==>" + JSON.toJSONString(details));
        for (RehabilitationDetailDO detailDO : details) {
            RehabilitationTemplateDetailDO templateDetailDO = templateDetailDao.findById(detailDO.getId()).orElse(null);
            System.out.println("templateDetailDO==>" + templateDetailDO);
            String frequency_code = templateDetailDO.getFrequencyCode();//频次
            String serverCount = templateDetailDO.getServerCount();
            RehabilitationDetailDO detail = new RehabilitationDetailDO();
            detail.setHospitalServiceItemId(templateDetailDO.getHospitalServiceItemId());
            detail.setCreateTime(new Date());
@ -346,6 +345,11 @@ public class RehabilitationPlanService extends BaseJpaService<RehabilitationPlan
            detail.setUpdateTime(new Date());
            detail.setPlanId(planDO.getId());
            detail.setFrequencyCode(frequency_code);
            detail.setServerCount(serverCount);
            if(StringUtils.isNotBlank(templateDetailDO.getPlanStartTimeType())){
                detail.setTimeType(Integer.parseInt(templateDetailDO.getPlanStartTimeType()));
            }
            detail.setServerTimeType(templateDetailDO.getServerTimeType());
//            //补充的科室和医生--有单独的分配接口
//            detail.setDoctor(detailDO.getDoctor());
//            detail.setDoctorName(detailDO.getDoctorName());
@ -357,7 +361,6 @@ public class RehabilitationPlanService extends BaseJpaService<RehabilitationPlan
        rehabilitationManageService.addPlanLog(planDO.getId(), planDO.getPlanDoctor(), planDO.getPlanDoctorName());
        if (StringUtils.isNotBlank(patientInfoCode)) {
            RehabilitationPatientInfoDO infoDO = rehabilitationPatientInfoDao.findByCode(patientInfoCode);
            System.out.println("infoDO==>" + infoDO);
            if (StringUtils.isBlank(infoDO.getDiagnosis())) {
                infoDO.setDept(recordsDO.getDept());
                infoDO.setDeptName(recordsDO.getDeptName());
@ -371,7 +374,6 @@ public class RehabilitationPlanService extends BaseJpaService<RehabilitationPlan
            rehabilitationPatientInfoDao.save(infoDO);
        }
        planDO.setDetailDOList(detailDOList);
        System.out.println("创建完成");
        return planDO;
    }
@ -663,9 +665,16 @@ public class RehabilitationPlanService extends BaseJpaService<RehabilitationPlan
    }
    public List<Map<String, Object>> findRehabilitationServiceItem(String itemName) {
        String sql = " SELECT * FROM base.wlyy_rehabilitation_service_item WHERE 1=1 ";
        String sql = "SELECT\n" +
                "	a.* \n" +
                "FROM\n" +
                "	wlyy_rehabilitation_service_item a\n" +
                "	INNER JOIN base_service_package_item b ON a.id = b.dict_id \n" +
                "WHERE\n" +
                "	1 = 1 \n" +
                "	AND b.del = '1' ";
        if (StringUtils.isNotBlank(itemName)) {
            sql += " and `name` LIKE '%" + itemName + "%'";
            sql += " and a.`name` LIKE '%" + itemName + "%'";
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;