Browse Source

代码修改

liubing 3 years ago
parent
commit
f89c7f50ff
15 changed files with 854 additions and 1379 deletions
  1. 28 0
      business/base-service/src/main/java/com/yihu/jw/patient/service/BasePatientService.java
  2. 1 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/web/PageEnvelop.java
  3. 21 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/patient/BasePatientEndpoint.java
  4. 85 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doorCoach/DoctorDoorCoachOrderController.java
  5. 141 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doorCoach/PatientDoorCoachOrderController.java
  6. 1 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/assistance/EmergencyAssistanceService.java
  7. 0 146
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/HospitalService.java
  8. 0 165
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/ServerPackageService.java
  9. 0 46
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/WlyySystemDictService.java
  10. 40 2
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/consult/ConsultTeamService.java
  11. 272 35
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/DoctorDoorCoachOrderService.java
  12. 265 2
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/PatientDoorCoachOrderService.java
  13. 0 272
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/prescription/PresModeAdapter.java
  14. 0 667
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/StatisticsUtilService.java
  15. 0 42
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/StreamUtil.java

+ 28 - 0
business/base-service/src/main/java/com/yihu/jw/patient/service/BasePatientService.java

@ -20,6 +20,7 @@ import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientGroupDao;
import com.yihu.jw.patient.dao.BasePatientGroupDictDao;
import com.yihu.jw.patient.util.ConstantUtils;
import com.yihu.jw.restmodel.base.patient.BasePatientVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyInspectionVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionInfoVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionVO;
@ -37,6 +38,7 @@ import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.CrudRepository;
@ -643,4 +645,30 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
        return null;
    }
    public PageEnvelop pageByCondition(String name, Integer archiveType, Integer archiveStatus,int page,int size){
        List<BasePatientVO> list = new ArrayList<>();
        if (page>0){
            page--;
        }else{
            page=0;
        }
        String sqlCount = "select count(*) from base_patient where 1=1 ";
        String sql = "select * from base_patient where 1=1 ";
        String sqlCondition = "";
        if (StringUtils.isNotBlank(name)){
            sqlCondition += " and (name like '%"+name+"%' or idcard like '%"+name+"%' or mobile like '%"+name+"%') ";
        }
        if (archiveType!=null){
            sqlCondition += " and archive_type ="+archiveType;
        }
        if (archiveStatus!=null){
            sqlCondition += " and archive_status ="+archiveStatus;
        }
        Long count = jdbcTemplate.queryForObject(sqlCount+sqlCondition,Long.class);
        sqlCondition +=" limit "+page*size+","+size;
        list = jdbcTemplate.query(sql+sqlCondition,new BeanPropertyRowMapper<>(BasePatientVO.class));
        return PageEnvelop.getSuccessListWithPage("success",list,page,size,count);
    }
}

+ 1 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/web/PageEnvelop.java

@ -43,6 +43,7 @@ public class PageEnvelop<T> extends Envelop implements Serializable {
    @ApiModelProperty(value = "列表内容")
    private List<T> detailModelList = new ArrayList<>(0);
    public int getCurrPage() {
        return currPage;
    }

+ 21 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/patient/BasePatientEndpoint.java

@ -102,6 +102,27 @@ public class BasePatientEndpoint extends EnvelopRestEndpoint {
        return success(basePatients, count, page, size, BasePatientVO.class);
    }
    @GetMapping(value = "pageByCondition")
    @ApiOperation(value = "获取分页")
    public PageEnvelop<BasePatientVO> pageByCondition(
            @ApiParam(name = "name", value = "手机号/姓名/身份证")
            @RequestParam(value = "name", required = false) String name,
            @ApiParam(name = "archiveStatus", value = "档案状态")
            @RequestParam(value = "archiveStatus", required = false) Integer archiveStatus,
            @ApiParam(name = "archiveType", value = "档案类型")
            @RequestParam(value = "archiveType", required = false) Integer archiveType,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
        try {
            return basePatientService.pageByCondition(name, archiveType , archiveStatus, page, size);
        }catch (Exception e){
            return PageEnvelop.getError(e.getMessage(),-1);
        }
    }
    @GetMapping(value = BaseRequestMapping.BasePatient.LIST)
    @ApiOperation(value = "获取列表")
    public ListEnvelop<BasePatientVO> list(

+ 85 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doorCoach/DoctorDoorCoachOrderController.java

@ -333,7 +333,7 @@ public class DoctorDoorCoachOrderController extends BaseController {
            @ApiParam(value = "角色0、医生,1、管理员", name = "isManage",required = false)
            @RequestParam(value = "isManage", required = false) String isManage,
            @ApiParam(value = "发起类型(1本人发起 2家人待预约 3医生代预约)", name = "type")
            @RequestParam(value = "type", required = false) Integer type,
            @RequestParam(value = "type", required = false,defaultValue = "1") Integer type,
            @ApiParam(value = "页码", name = "page",defaultValue = "1",required = true)
            @RequestParam(value = "page", required = true) Integer page,
            @ApiParam(value = "每页数目", name = "pageSize",defaultValue = "10",required = true)
@ -384,6 +384,68 @@ public class DoctorDoorCoachOrderController extends BaseController {
        }
    }
    @GetMapping(value = "queryBriefList")
    @ApiOperation(value = "调度员查询工单列表")
    public String queryBriefList(
            @ApiParam(name = "dispatcher", value = "调度员code") @RequestParam(value = "dispatcher", required = true) String dispatcher,
            @ApiParam(name = "hospital", value = "调度员所在机构code") @RequestParam(value = "hospital", required = true) String hospital,
            @ApiParam(name = "orderNumber", value = "工单号") @RequestParam(value = "orderNumber", required = false) String orderNumber,
            @ApiParam(name = "patientName", value = "工单服务对象姓名") @RequestParam(value = "patientName", required = false) String patientName,
            @ApiParam(name = "phone", value = "发起工单的居民的联系方式") @RequestParam(value = "phone", required = false) String phone,
            @ApiParam(name = "status", value = "工单状态") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(name = "patientType", value = "居民类型") @RequestParam(value = "patientType", required = false) String patientType,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) {
        try{
            JSONObject result = doctorDoorCoachOrderService.queryBriefList(dispatcher,hospital, orderNumber, patientName, phone, status,patientType, page, size);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1,result.getString(ResponseContant.resultMsg));
            }
            int count = result.getIntValue(ResponseContant.count);
            JSONObject object = new JSONObject();
            object.put("total",count);
            object.put("detailModelList",result.get(ResponseContant.resultMsg));
            object.put("currPage",page);
            object.put("pageSize",size);
            return write(200,"查询成功","data",object);
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"查询失败");
    }
    @GetMapping(value = "queryDoctorList")
    @ApiOperation(value = "服务人员列表(医生列表)")
    public String queryDoctorList(
            @ApiParam(name = "town", value = "调度员所在的机构code") @RequestParam(value = "town", required = false) String town,
            @ApiParam(name = "doctorName", value = "医生姓名") @RequestParam(value = "doctorName", required = false) String doctorName,
            @ApiParam(name = "status", value = "医生接单状态,状态为全部时不传") @RequestParam(value = "status", required = false) String status,
            @ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = false) String patient,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) {
        try{
            JSONObject result = doctorDoorCoachOrderService.queryDoctorList(patient,town, doctorName, status, page, size);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1,result.getString(ResponseContant.resultMsg));
            }
            int count = result.getIntValue(ResponseContant.count);
            JSONObject object = new JSONObject();
            object.put("total",count);
            if (count > 0){
                object.put("detailModelList",result.get(ResponseContant.resultMsg));
            }else {
                List list = new ArrayList();
                object.put("detailModelList",list);
            }
            object.put("currPage",page);
            object.put("pageSize",size);
            return write(200,"查询成功","data",object);
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"查询失败");
    }
    @GetMapping("getByOrderId")
    @ApiOperation(value = "根据工单id获取相应的工单,如果为空,则获取该医生当前最新一条的工单")
    public String getByOrderId(
@ -409,6 +471,28 @@ public class DoctorDoorCoachOrderController extends BaseController {
        }
    }
    /**
     * 获取服务项目
     *
     * @param hospital
     * @return
     */
    @GetMapping("selectItemsByHospital")
    @ApiOperation(value = "获取服务项目")
    public String selectItemsByHospital(
            @ApiParam(value = "机构code", name = "hospital")
            @RequestParam(value = "hospital", required = false) String hospital,
            @ApiParam(value = "服务项目名称", name = "serverItemName")
            @RequestParam(value = "serverItemName", required = false) String serverItemName) {
        try {
            return write(200, "获取成功","dara",patientDoorCoachOrderService.selectItemsByHospital(hospital,serverItemName));
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @PostMapping("/initDoorStatus")
    @ApiOperation(value = "初始化医生分派订单开关状态")
    public String initDoorStatus() {

+ 141 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doorCoach/PatientDoorCoachOrderController.java

@ -1,16 +1,24 @@
package com.yihu.jw.care.endpoint.doorCoach;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.service.doorCoach.DoctorDoorCoachOrderService;
import com.yihu.jw.care.service.doorCoach.PatientDoorCoachOrderService;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachOrderDO;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
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.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
 * 上门辅导服务工单控制器
 *
@ -22,6 +30,8 @@ public class PatientDoorCoachOrderController extends EnvelopRestEndpoint {
    @Autowired
    private PatientDoorCoachOrderService patientDoorCoachOrderService;
    @Autowired
    private DoctorDoorCoachOrderService doctorDoorCoachOrderService;
    @PostMapping(value = "qucikSendIM")
    @ApiOperation(value = "通过IM向客户端推送消息")
@ -74,6 +84,26 @@ public class PatientDoorCoachOrderController extends EnvelopRestEndpoint {
        return success(result.get(ResponseContant.resultMsg));
    }
    @PostMapping(value = "cancelOrder")
    @ApiOperation(value = "取消工单")
    public Envelop cancelOrder(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "reason", value = "取消理由") @RequestParam(value = "reason", required = true) String reason) {
        JSONObject result = new JSONObject();
        try{
            result = patientDoorCoachOrderService.cancelOrder(orderId, 2, reason,null,null);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return failed(result.getString(ResponseContant.resultMsg));
            }
        }catch (Exception e){
            e.printStackTrace();
            return failed(e.getMessage());
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "queryDispatcherInfoByPatient")
    @ApiOperation(value = "获取居民所签约的机构的调度员信息")
    public Envelop queryDispatcherInfoByPatient(
@ -86,4 +116,115 @@ public class PatientDoorCoachOrderController extends EnvelopRestEndpoint {
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping("/topStatusBarNum")
    @ApiOperation(value = "顶部状态栏订单分类tab")
    public ObjEnvelop topStatusBarNum(
            @ApiParam(name = "patient", value = "患者ID")
            @RequestParam(value = "patient", required = true) String patient) {
        try {
            Map<String, Integer> map = patientDoorCoachOrderService.getNumGroupByStatus(patient);
            return ObjEnvelop.getSuccess( "获取成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError( "获取失败!" );
        }
    }
    @GetMapping("/getDoorOrderList")
    @ApiOperation(value = "服务工单列表")
    public ObjEnvelop getDoorOrderList(
            @ApiParam(value = "工单服务编号", name = "orderId",required = false)
            @RequestParam(value = "orderId", required = false) String orderId,
            @ApiParam(value = "居民姓名", name = "patientName",required = false)
            @RequestParam(value = "patientName", required = false) String patientName,
            @ApiParam(value = "联系方式", name = "patientPhone",required = false)
            @RequestParam(value = "patientPhone", required = false) String patientPhone,
            @ApiParam(value = "服务机构", name = "hospitalCode",required = false)
            @RequestParam(value = "hospitalCode", required = false) String hospitalCode,
            @ApiParam(value = "工单状态", name = "status",required = false)
            @RequestParam(value = "status", required = false) Integer[] status,
            @ApiParam(value = "创建时间开始,格式(yyyy-MM-dd mm:dd:ss)", name = "createTimeStart",required = false)
            @RequestParam(value = "createTimeStart", required = false) String createTimeStart,
            @ApiParam(value = "创建时间结束,格式(yyyy-MM-dd mm:dd:ss)", name = "createTimeEnd",required = false)
            @RequestParam(value = "createTimeEnd", required = false) String createTimeEnd,
            @ApiParam(value = "服务医生的名称", name = "serverDoctorName",required = false)
            @RequestParam(value = "serverDoctorName", required = false) String serverDoctorName,
            @ApiParam(value = "居民ID", name = "patient",required = false)
            @RequestParam(value = "patient", required = false) String patient,
            @ApiParam(value = "发起类型(1本人发起 2家人待预约 3医生代预约)", name = "type")
            @RequestParam(value = "type", required = false,defaultValue = "1") Integer type,
            @ApiParam(value = "页码", name = "page",defaultValue = "1",required = true)
            @RequestParam(value = "page", required = true) Integer page,
            @ApiParam(value = "每页数目", name = "pageSize",defaultValue = "10",required = true)
            @RequestParam(value = "pageSize", required = true) Integer pageSize) {
        try {
            StringBuffer ss = new StringBuffer();
            if (status != null && status.length > 0){
                int statusLength = status.length;
                for (int i =0 ; i < statusLength ; i++){
                    ss .append(status[i]);
                    if (i<statusLength-1){
                        ss.append(",");
                    }
                }
            }else {
                ss = null;
            }
            JSONObject result = patientDoorCoachOrderService.getDoorOrderList(orderId,patientName,patientPhone,hospitalCode,
                    ss,createTimeStart,createTimeEnd,serverDoctorName,patient,page,pageSize, type);
            return ObjEnvelop.getSuccess( "获取成功",result);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError( "获取失败!" + e.getMessage());
        }
    }
    @GetMapping("getByOrderId")
    @ApiOperation(value = "根据工单id获取相应的工单,如果为空,则获取该患者当前最新一条的工单")
    public ObjEnvelop getByOrderId(
            @ApiParam(value = "patientCode", name = "patientCode")
            @RequestParam(value = "patientCode", required = true) String patientCode,
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = false) String orderId) {
        try {
            // 没有提供工单id的情况下,则获取该医生当前最新一条的工单
            if (StringUtils.isEmpty(orderId)) {
                // 根据接单医生code获取最近一次服务orderId
                orderId = patientDoorCoachOrderService.getOrderIdByPatient(patientCode);
                if (StringUtils.isEmpty(orderId)) {
                    return ObjEnvelop.getError( "获取失败, 该医生暂无工单" );
                }
            }
            // 根据orderId获取工单信息
            BaseDoorCoachOrderDO baseDoorCoachOrderDO = doctorDoorCoachOrderService.getDoorServiceOrderById(orderId);
            return ObjEnvelop.getSuccess( "获取成功",  baseDoorCoachOrderDO);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError("获取失败, 该医生暂无工单!" + e.getMessage());
        }
    }
    /**
     * 获取服务项目
     *
     * @param hospital
     * @return
     */
    @GetMapping("selectItemsByHospital")
    @ApiOperation(value = "获取服务项目")
    public ListEnvelop selectItemsByHospital(
            @ApiParam(value = "机构code", name = "hospital")
            @RequestParam(value = "hospital", required = false) String hospital,
            @ApiParam(value = "服务项目名称", name = "serverItemName")
            @RequestParam(value = "serverItemName", required = false) String serverItemName) {
        try {
            return ListEnvelop.getSuccess( "获取成功",patientDoorCoachOrderService.selectItemsByHospital(hospital,serverItemName));
        } catch (Exception e) {
            e.printStackTrace();
            return ListEnvelop.getError( "获取失败!");
        }
    }
}

+ 1 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/assistance/EmergencyAssistanceService.java

@ -494,7 +494,7 @@ public class EmergencyAssistanceService extends BaseJpaService<EmergencyAssistan
        assistanceDO.setUpdateTime(new Date());
        //结束救助咨询
        if (!consultTeamService.finishEmergencyConsult(assistanceDO,patient,1)){
            String failMsg = "咨询结束失败 无法完成工单";
            String failMsg = "咨询结束失败 无法取消工单";
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg,failMsg);
            return result;

+ 0 - 146
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/HospitalService.java

@ -1,146 +0,0 @@
package com.yihu.jw.care.service.common;
import com.yihu.jw.entity.base.system.SystemDictEntryDO;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * Created by yeshijie on 2020/12/25.
 */
@Service
public class HospitalService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseOrgDao baseOrgDao;
    @Autowired
    private WlyySystemDictService systemDictService;
    public List<Map<String, Object>> getDoctorsByhospitalNoPage(String hospital, String name, Integer type, Integer times) throws Exception {
/*        BaseOrgDO h = baseOrgDao.findByCode(hospital);
        Integer level = 1;
        if(h != null && h.getOrgLevel()!=null) {
            level = h.getOrgLevel();
        }else {
            throw new Exception("未获取到机构等级");
        }*/
//        String sql = "";
        //服务次数是否大于12
/*        if (times != null && times <= 12) {
            sql = "select d.*,j.fee_level_" + level + " - j.subsidy as fee  from wlyy_doctor d LEFT JOIN dm_job j on d.job = j.`code` and j.del = 1 " +
                    "where d.del=1  and d.status=1 ";
        }else {
            sql = "select d.*,j.fee_level_" + level + " as fee  from wlyy_doctor d LEFT JOIN dm_job j on d.job = j.`code` and j.del = 1 " +
                    "where d.del=1  and d.status=1 ";
        }*/
        String sql = "SELECT d.id," +
                " d.id name,d.name,h.org_code hospital,h.org_name hospital_name, " +
                " h.dept_name,d.job_title_code job,d.job_title_name job_name,d.photo,d.expertise,d.introduce " +
                "FROM base_doctor d, base_doctor_hospital h " +
                "WHERE d.id = h.doctor_code AND h.del = 1 AND d.del = 1";
        List<Object> params = new ArrayList<Object>();
        if (StringUtils.isNoneEmpty(hospital)) {
            sql += " and h.org_code =? ";
            params.add(hospital);
        }
        if (StringUtils.isNoneEmpty(name)) {
            sql += " and d.name like ? ";
            params.add("%" + name + "%");
        }
/*        if (type != null && type > 0) {
            sql += " and level =? ";
            params.add(type);
        }*/
        return jdbcTemplate.queryForList(sql, params.toArray());
    }
    /**
     * 获取机构上班时间
     * @param code
     * @return
     */
    public List<String> getWorkingTimeByPatient(String code) throws Exception {
        List<String> result = new ArrayList<>();
        String startWorkingTimeAm = null ;
        String stopWorkingTimeAm = null ;
        String startWorkingTimePm = null ;
        String stopWorkingTimePm = null;
                List<SystemDictEntryDO> systemDictEntryDOList = systemDictService.getDictByDictName("350211A1002_org_work_time");
        for (SystemDictEntryDO dictEntryDO:systemDictEntryDOList){
            if("startAm".equals(dictEntryDO.getCode())){
                startWorkingTimeAm = dictEntryDO.getValue();
            }else  if("stopAm".equals(dictEntryDO.getCode())){
                stopWorkingTimeAm = dictEntryDO.getValue();
            }else  if("startPm".equals(dictEntryDO.getCode())){
                startWorkingTimePm = dictEntryDO.getValue();
            }else  if("stopPm".equals(dictEntryDO.getCode())){
                stopWorkingTimePm = dictEntryDO.getValue();
            }
        }
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        int amCount = 0;
        //获取机构早上上班时间
        if(StringUtils.isNotBlank(startWorkingTimeAm) && StringUtils.isNotBlank(stopWorkingTimeAm)) {
            String startWorkTime = startWorkingTimeAm;
            String stopWokingTime = stopWorkingTimeAm;
            Date startWokingTimeAm = DateUtil.strToDate(startWorkingTimeAm, "HH:mm");
            Date stopWokingTimeAm = DateUtil.strToDate(stopWorkingTimeAm, "HH:mm");
            long diff = stopWokingTimeAm.getTime() - startWokingTimeAm.getTime();
            // 计算差多少分钟
            long min = diff / nm;
            amCount = (int) (min % 30 == 0 ? min / 30 : min / 30 + 1);
            for (int i = 0; i < amCount; i++) {
                //判断是否是最后一段时间
                if(amCount - i > 1) {
                    result.add(startWorkTime + "-" + DateUtil.getNextMin(startWorkTime, 30));
                    startWorkTime = DateUtil.getNextMin(startWorkTime, 30);
                }else {
                    result.add(startWorkTime + "-" + stopWokingTime);
                }
            }
        }
        //获取机构下午上班时间
        if(StringUtils.isNotBlank(startWorkingTimePm) && StringUtils.isNotBlank(stopWorkingTimePm)) {
            String startWorkTime = startWorkingTimePm;
            String stopWokingTime = stopWorkingTimePm;
            Date startWokingTimePm = DateUtil.strToDate(startWorkingTimePm, "HH:mm");
            Date stopWokingTimePm = DateUtil.strToDate(stopWorkingTimePm, "HH:mm");
            long diff = stopWokingTimePm.getTime() - startWokingTimePm.getTime();
            // 计算差多少分钟
            long min = diff  / nm;
            int pmCount = (int) (min % 30 == 0 ? min / 30 : min / 30 + 1);
            for (int i = amCount; i < amCount + pmCount; i++) {
                //判断是否是最后一段时间
                if(amCount + pmCount - i > 1) {
                    result.add(startWorkTime + "-" + DateUtil.getNextMin(startWorkTime, 30));
                    startWorkTime = DateUtil.getNextMin(startWorkTime, 30);
                }else {
                    result.add(startWorkTime + "-" + stopWokingTime);
                }
            }
        }
        return result;
    }
}

+ 0 - 165
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/ServerPackageService.java

@ -1,165 +0,0 @@
package com.yihu.jw.care.service.common;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Created by wzn54 on 2019/3/19.
 */
@Service
@Transactional
public class ServerPackageService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${wechat.id}")
    private String wxId;
    /**
     * 根据机构code获取服务项目
     *
     * @param hospital
     * @return
     */
    public List<Map<String,Object>> selectByHospital(String hospital){
        String sql = "SELECT  *  FROM  wlyy.wlyy_server_item si  " +
                "WHERE  si.CODE IN (SELECT service_item_code FROM wlyy.wlyy_hospital_service_item hsi " +
                "WHERE (hsi.hospital IN ( SELECT hp.hospital_partner FROM wlyy.wlyy_hospital_partner hp " +
                "WHERE  hp.hospital ='"+hospital+"' AND hp.del = 1 ) OR hsi.hospital = '"+hospital+"') " +
                "AND hsi.del = 1 )";
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }
    /**
     *
     * 根据机构code获取本机构服务项目
     *
     * @param hospital
     * @return
     */
    public JSONArray selectByHospital1(String hospital){
        String sql = "select * from wlyy.wlyy_server_item si JOIN wlyy.wlyy_hospital_service_item hsi ON hsi.service_item_code = si.`code` AND hsi.del=1\n" +
                "and hsi.hospital = '"+hospital+"'";
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        JSONArray  array= new JSONArray();
        JSONObject object = new JSONObject();
        object.put("type","1");
        List<Map<String,Object>> maps = new ArrayList<>();
        JSONObject object1 = new JSONObject();
        object1.put("type","2");
        List<Map<String,Object>> maps1 = new ArrayList<>();
        for (Map<String,Object> map:mapList){
            if (map.get("item_type").toString().equalsIgnoreCase("1")){
                maps.add(map);
            }else if (map.get("item_type").toString().equalsIgnoreCase("2")){
                maps1.add(map);
            }
        }
        object.put("items",maps);
        object1.put("items",maps1);
        array.add(object);
        array.add(object1);
        return array;
    }
    public List<Map<String,Object>> selectServiceByHospital(String hospital,String serverItemName,String type,String patient,String doctor){
        StringBuffer buffer = new StringBuffer();
        if(StringUtils.isNoneBlank(hospital)){
//            HospitalMapping hospitalMapping = hospitalMappingDao.findByCode(hospital);
//            buffer.append(" and ziocad.org_code = '"+hospitalMapping.getMappingCode()+"'");
        }
        String sql = "";
        if("sd_tnzyy_wx".equals(wxId)){
            if("door".equals(type)){
                //上门护理
                sql = "SELECT code,value title,'' unit,0 expense   from base_system_dict_entry WHERE dict_code = 'door_service_door_dict' ORDER BY sort";
            }else{
                sql = "SELECT DISTINCT a.FYXH code,a.FYMC title,a.FYDW unit,a.FYDJ expense from gy_ylsf a ";
                if("used".equals(type)){
                    sql += " JOIN wlyy_door_order_item i on i.code = a.FYXH and (i.patient = '"+patient+"' or i.doctor='"+doctor+"') ";
                }else if("other".equals(type)){
                    sql += " where a.FYGB not in (SELECT code from base_system_dict_entry WHERE dict_code = 'door_service_subject_class_dict')";
                }else{
                    sql += " WHERE a.FYGB ="+type;
                }
            }
        }else {
            sql ="SELECT " +
                    "ziocad.org_code AS hospital," +
                    "zicd.clinic_code AS diagnosis_code," +
                    "zicd.clinic_code AS code," +
                    "zicd.clinic_name AS title," +
                    "zicd.clinic_spec AS spec," +
                    "zicd.clinic_unit AS unit," +
                    "ziccad.allot_quantity AS quantity," +
                    "zicd.subject_class AS subjectClass," +
                    "ziccad.item_code AS itemCode," +
                    " SUBSTR(zicd.subject_class, 1, 4) AS subjectCatagory," +
                    " (CASE WHEN ISNULL(ziocd.price) THEN 0 ELSE ziocd.price END) as expense " +
                    " FROM zy_iv_org_clinic_allot_dict ziocad " +
                    " LEFT JOIN zy_iv_clinic_charge_allot_dict ziccad ON ziccad.clinic_code = ziocad.clinic_code AND ziccad.org_code = ziocad.org_code" +
                    " LEFT JOIN zy_iv_clinic_dict zicd ON zicd.clinic_code = ziocad.clinic_code" +
                    " LEFT JOIN zy_iv_org_charge_allot_dict ziocd ON ziocd.charge_code = ziccad.item_code and ziocd.org_code = ziccad.org_code  " ;
            if("used".equals(type)){
                sql += " LEFT JOIN wlyy_door_order_item i on i.code = zicd.clinic_code and (i.patient = '"+patient+"' or i.doctor='"+doctor+"') ";
                sql += " WHERE SUBSTR(zicd.subject_class, 1, 4) = '"+type+"' ";
            }else{
                sql += " WHERE SUBSTR(zicd.subject_class, 1, 4) = '"+type+"' ";
            }
            sql += buffer;
        }
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }
    /**
     * 居民端服务项类型
     * @return
     */
    public List<Map<String,Object>> selectPatientTypes(){
        String sql = "SELECT code,value type from base_system_dict_entry WHERE dict_code = 'door_service_subject_class_dict' and code = 'door'";
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }
    /**
     * 医生端服务项类型
     * @return
     */
    public List<Map<String,Object>> selectTypes(){
        String sql = "SELECT code,value type from base_system_dict_entry WHERE dict_code = 'door_service_subject_class_dict' ORDER BY sort";
        List<Map<String,Object>> mapList1 = jdbcTemplate.queryForList(sql);
        Map<String,Object> map1 = new HashedMap();
        map1.put("code","used");
        map1.put("type","常用");
        mapList1.add(map1);
        Map<String,Object> map2 = new HashedMap();
        map2.put("code","other");
        map2.put("type","其他");
        mapList1.add(map2);
        return mapList1;
    }
}

+ 0 - 46
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/WlyySystemDictService.java

@ -1,46 +0,0 @@
package com.yihu.jw.care.service.common;
import com.yihu.jw.entity.base.system.SystemDictEntryDO;
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 org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * Created by yeshijie on 2021/1/9.
 */
@Service
@Transactional
public class WlyySystemDictService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<SystemDictEntryDO> getDictByDictName(String dictCode) {
        String sql = "select d.* from base_system_dict_entry d where d.dict_code = '"+dictCode+"'";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SystemDictEntryDO.class));
    }
    /**
     * 查找字典项
     * @param dictCode
     * @param code
     * @return
     */
    public String getDictValue(String dictCode, String code) {
        String re = null;
        try {
            String sql = "select d.value from base_system_dict_entry d where d.dict_code = '"+dictCode+"' and d.code = '"+code+"'";
            re = jdbcTemplate.queryForObject(sql,String.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        return re;
    }
}

+ 40 - 2
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/consult/ConsultTeamService.java

@ -274,8 +274,8 @@ public class ConsultTeamService {
        }
        //咨询记录
        String title = patientDO.getName() + "-发起了服务咨询";
        ConsultDo consult = addConsult(patient,title,doorServiceOrderDO.getServeDesc(),patientDO.getPhone(),11);
        String title = patientDO.getName() + "-发起了上门辅导咨询";
        ConsultDo consult = addConsult(patient,title,doorServiceOrderDO.getServeDesc(),patientDO.getPhone(),21);
        //咨询详细信息
        ConsultTeamDo consultTeam = new ConsultTeamDo();
@ -326,4 +326,42 @@ public class ConsultTeamService {
        result.put(ResponseContant.resultMsg, consultTeam);
        return result;
    }
    /**
     *
     * @param assistanceDO
     * @param endOperator 操作者ID
     * @param endType 1居民 2医生
     * @return
     */
    public boolean finishDoorCoachConsult(BaseDoorCoachOrderDO assistanceDO, String endOperator, int endType){
        ConsultTeamDo consultTeam = consultTeamDao.queryByRelationCode(assistanceDO.getId());
        ConsultDo consult = consultDao.findOne(consultTeam.getConsult());
        String sessionId = assistanceDO.getPatient() + "_" + consultTeam.getConsult() + "_" + consultTeam.getType();
        String operatorId = endOperator;
        String operatorName=null;
        if (endType==1){
            BasePatientDO patientDO = patientDao.findById(endOperator);
            operatorName = patientDO.getName();
        }else {
            BaseDoctorDO doctorDO = doctorDao.findById(endOperator);
            operatorName = doctorDO.getName();
        }
        try {
            JSONObject obj =  imUtill.endTopics(sessionId,operatorId,operatorName,consultTeam.getConsult());
            if (obj == null||obj.getInteger("status") == -1) {
                return false;
            }
            consultTeam.setEndMsgId(obj.getString("id"));
            consult.setEndTime(new Date());
            consultTeam.setEndTime(new Date());
            consultTeam.setStatus(1);
            consultDao.save(consult);
            consultTeamDao.save(consultTeam);
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }
}

+ 272 - 35
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/DoctorDoorCoachOrderService.java

@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.doorCoach.*;
import com.yihu.jw.care.service.consult.ConsultTeamService;
import com.yihu.jw.care.util.MessageUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
@ -12,6 +13,7 @@ import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.BasePatientWechatDo;
import com.yihu.jw.entity.care.doorCoach.*;
@ -23,7 +25,9 @@ import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
@ -54,6 +58,8 @@ public class DoctorDoorCoachOrderService {
    @Value("${fastDFS.fastdfs_file_url}")
    private String imgUrlDomain;
    @Value("${systemSetting.isApplication}")
    private String isApplication;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
@ -84,6 +90,10 @@ public class DoctorDoorCoachOrderService {
    private ConsultDao consultDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private BaseOrgDao hospitalDao;
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private MessageDao messageDao;
@ -181,7 +191,7 @@ public class DoctorDoorCoachOrderService {
                ;
        String sqlCount = " select count(DISTINCT o.id) as total ";
        String sql = " from base_door_coach_order o LEFT JOIN base_org h on h.code=o.hospital and h.del=1 where 1=1 where 1=1";
        String sql = " from base_door_coach_order o LEFT JOIN base_org h on h.code=o.hospital and h.del=1 where 1=1 ";
        if(!StringUtils.isEmpty(orderId)){
            sql+=" and o.number = '"+orderId+"'";
@ -205,7 +215,7 @@ public class DoctorDoorCoachOrderService {
            sql+=" and o.create_time <='"+createTimeEnd+"'";
        }
        if(!StringUtils.isEmpty(serverDoctorName)){
            sql+=" and d.doctor_name like '%"+serverDoctorName+"%'";
            sql+=" and o.doctor_name like '%"+serverDoctorName+"%'";
        }
        //获取医生代预约记录
        if(type != null && type == 3 ){
@ -524,6 +534,7 @@ public class DoctorDoorCoachOrderService {
        }
        one.setPatientConfirmFinishWay(finishWay);
        one.setPatientConfirmFinishImg(finishImg);
        one.setCompleteTime(new Date());
        one.setStatus(BaseDoorCoachOrderDO.Status.complete.getType());
        one.setPatientConfirmFinishTime(new Date());
        // 更新记录
@ -552,6 +563,10 @@ public class DoctorDoorCoachOrderService {
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        //如果是调度员取消,推送IM取消工单json消息,
        if (!consultTeamService.finishDoorCoachConsult(one,one.getPatient(),1)){
            throw new Exception("咨询结束失败 无法取消工单");
        }
        return doorServiceOrderDO;
    }
@ -676,39 +691,261 @@ public class DoctorDoorCoachOrderService {
       return map;
    }
    private String exchangeKeyName(String status) {
        String key;
        switch (status) {
            case "-1":
                key = "cancelOrder";
                break;
            case "1":
                key = "sendOrder";
                break;
            case "2" :
                key = "waitingOrder";
                break;
            case "3" :
                key = "serviceOrder";
                break;
            case "4" :
                key = "payment";
                break;
            case "5" :
                key = "supplement";
                break;
            case "6" :
                key = "completed";
                break;
            case "7" :
                key = "exampaperstatus";
                break;
            default:
                key = status;
                break;
        }
        return key;
    /**
     * 调度员-查询-工单列表
     *
     * @return
     */
    public JSONObject queryBriefList(String dispatcher,String hospital,String orderNumber,String patientName,String phone,Integer status, String patientType,int page, int size) {
        JSONObject result = new JSONObject();
        orderNumber = null == orderNumber ? "" : orderNumber;
        patientName = null == patientName ? "" : patientName;
        phone = null == phone ? "" : phone;
        status = null == status ? -100 : status;
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        StringBuffer buffer = new StringBuffer();
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(orderNumber)){
            buffer.append(" AND ( o.`number` like '%"+orderNumber+"%' ) ");
        }else if (org.apache.commons.lang3.StringUtils.isNoneBlank(patientName)){
            buffer.append(" AND o.`patient_name` like '%"+patientName+"%' ");
        }else if (org.apache.commons.lang3.StringUtils.isNoneBlank(phone)){
            buffer.append(" AND o.`proxy_patient_phone` like '%"+phone+"%'");
        }
        String applicationSql = "";
        String patientTypeTemp = "";
        if("1".equals(isApplication)){
            applicationSql +=                 " JOIN ( " +
                    "         select a.patient, group_concat(v.type) as type " +
                    "         from wlyy_door_service_voucher v " +
                    "                  JOIN (select t.id, t.patient, max(t.create_time) " +
                    "                        from wlyy_door_service_application t " +
                    "                        where t.status in (2, 3) " +
                    "                        group by t.patient) as a " +
                    "                       on a.id = v.service_id " +
                    "         where v.status = 1 " +
                    "         group by a.patient " +
                    "        ) as t1 on o.patient = t1.patient" ;
            patientTypeTemp = " ,t1.`type` as patientType ";
        }
        String sql = "SELECT " +
                "  p.name AS patientName, " +
                "  p.photo AS photo, " +
                "  case p.sex  " +
                "  when 1 then '男'  " +
                "  when 2 then '女' " +
                "  end AS sex, " +
                "  TIMESTAMPDIFF(year,p.birthday,NOW()) AS age," +
                "  o.id as orderId, " +
                "  o.patient_phone as phone, " +
                "  o.proxy_patient as proxyPatient, " +
                "  o.patient as patient, " +
                "  o.number as number, " +
                "  o.patient_expected_serve_time as serveTime, o.doctor, o.doctor_name as doctorName, " +
                "  o.serve_address as address, " +
                "  o.serve_lon as lon, " +
                "  o.serve_lat as lat, " +
                "  o.`status` as status, " +
                "  o.`dispatcher_name` as dispatcherName, " +
                "  concat( o.patient,'_' ,c.id, '_',o.`number`,'_11' ) as sessionId " +
                patientTypeTemp +
                " FROM " +
                " ( wlyy_door_service_order o " +
                " LEFT JOIN base_patient p ON o.patient = p.id ) LEFT JOIN wlyy_consult c on o.id = c.relation_code"+
                applicationSql+" WHERE " +
                "  o.hospital = '{hospital}' and o.type != 3 " +buffer+
                " AND ( o.`status` = {status} OR -100 = {status} ) " +
                " ORDER BY o.create_time desc " +
                " LIMIT {start},{end};";
        String finalSql = sql.replace("{hospital}", hospital)
                .replace("{status}", String.valueOf(status))
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "SELECT  " +
                "   count(o.id)  " +
                " FROM  " +
                "   wlyy_door_service_order o  " +
                " LEFT JOIN base_patient p ON o.patient = p.id " +
                applicationSql +
                " WHERE  " +
                "  o.hospital = '{hospital}' " +buffer+
                " AND (o.`status` = {status} or -100 = {status})";
        String finqlCountSql = countSql.replace("{hospital}", hospital)
                .replace("{status}", String.valueOf(status));
        List<Map<String,Object>> sqlResultlist = new ArrayList<>();
        try {
            sqlResultlist = jdbcTemplate.queryForList(finalSql);
            logger.info(finalSql);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库查询【调度员】上门服务工单列表信息失败:" + e.getMessage());
            return result;
        }
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库统计【调度员】上门服务工单数量失败:" + e.getMessage());
            return result;
        }
        List filteredResult = new ArrayList();
        String[] types = null;
        if(!org.apache.commons.lang3.StringUtils.isEmpty(patientType)){
            types = patientType.split(",");
        }else{
            types = new String[]{"1","2","3","4","5","6"};
        }
        String serviceSql = "SELECT count(d.id) times FROM wlyy_door_doctor d where d.order_id in(SELECT id from wlyy_door_service_order WHERE DATE_FORMAT(doctor_sign_time, '%Y') = DATE_FORMAT(NOW(), '%Y') AND patient=?)";
        sqlResultlist.forEach(
                oneMap -> {
                    // 获取服务次数
                    Integer serviceCount = jdbcTemplate.queryForObject(serviceSql, Integer.class, oneMap.get("patient")+"");
                    oneMap.put("serviceCount", serviceCount);
                    oneMap.put("isInSession",false);
                    String sessionId = String.valueOf(oneMap.get("sessionId"));
                    JSONArray parArray = imUtill.getParticipants(sessionId);
                    parArray.forEach(
                            oneParObj -> {
                                JSONObject oneParJson = (com.alibaba.fastjson.JSONObject)oneParObj;
                                if(org.apache.commons.lang3.StringUtils.equalsIgnoreCase(oneParJson.getString("id"),dispatcher)){
                                    oneMap.put("isInSession",true);
                                }
                            }
                    );
                });
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, sqlResultlist);
        JSONObject countItem = new JSONObject();
        countItem.put("count", count);
        result.putAll(countItem);
        return result;
    }
    /**
     * 调度员-查询-服务人员列表(医生)
     *
     * @return
     */
    public JSONObject queryDoctorList(String patient,String hospital,String doctorName,String status, int page, int size) {
        JSONObject result = new JSONObject();
        doctorName = null == doctorName ? "" : doctorName;
        if(org.apache.commons.lang3.StringUtils.isBlank(status)) {
            status = "-100";
        }
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : size;
        if(org.apache.commons.lang3.StringUtils.isEmpty(hospital)){
            hospital = "350211A1002";
        }
        //
        String sql = "SELECT " +
                "  d.id as doctor, " +
                "  d.photo as photo, " +
                "  d.name as name," +
                "  case d.sex  " +
                "  when 0 then '无' " +
                "  when 1 then '男' " +
                "  when 2 then '女' " +
                "  end as sex, " +
                "  d.job_title_name AS jobName, " +
                "  d.mobile as phone, " +
                "  IFNULL(ds.`status`,5) as status," +
                "  1 as sortFlag ,count(o.id) as count" +
                " FROM " +
                " base_doctor d " +
                " LEFT JOIN wlyy_door_doctor_status ds ON d.id = ds.doctor " +
                " LEFT JOIN wlyy_door_service_order o on o.doctor = d.id and o.`status` in (2,3,4) " +
                " LEFT JOIN base_doctor_hospital dh on dh.doctor_code = d.id " +
                " WHERE d.enabled = 1" +
                " AND dh.org_code = '{hospital}' "+
                " AND d.`name` like '%{doctorName}%' " +
                " AND (ds.`status` in ({status}) or '-100' = '{status}')" +
                " AND d.del=1  " +
                " GROUP BY d.id ORDER BY ds.create_time DESC " +
                " LIMIT {start},{end}";
        String finalSql = sql.replace("{hospital}", hospital)
                .replace("{doctorName}", doctorName)
                .replace("{status}", String.valueOf(status))
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "SELECT  " +
                "   count(d.id)  " +
                " FROM  " +
                "   base_doctor d  " +
                " LEFT JOIN wlyy_door_doctor_status ds ON d.id = ds.doctor " +
                " LEFT JOIN base_doctor_hospital dh on dh.doctor_code = d.id " +
                " WHERE d.enabled = 1" +
                " AND dh.org_code = '{hospital}' "+
                " AND d.`name` like '%{doctorName}%' " +
                " AND d.del=1 " +
                " AND (ds.`status` in ({status}) or '-100' = '{status}')";
        String finalCountSql = countSql.replace("{hospital}", hospital)
                .replace("{doctorName}", doctorName)
                .replace("{status}", String.valueOf(status));
        List<Map<String,Object>> sqlResultlist = new ArrayList<>();
        try {
            sqlResultlist = jdbcTemplate.queryForList(finalSql);
            if (sqlResultlist!=null&&sqlResultlist.size()!=0){
                for (Map<String,Object> map:sqlResultlist){
                    BaseOrgDO hospital1 = hospitalDao.findByCode(hospital);
                    map.put("position",hospital1.getLongitude()+","+hospital1.getLatitude());
                }
            }
            logger.info("服务医生人员sql:"+finalSql);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库查询 服务医生人员 列表信息失败:" + e.getMessage());
            return result;
        }
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(finalCountSql, Integer.class);
        } catch (Exception e) {
            e.printStackTrace();
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库统计  服务医生人员 数量失败:" + e.getMessage());
            return result;
        }
        //添加未完成服务工单列表
        for(Map<String,Object> map : sqlResultlist){
            String doctor = map.get("doctor") + "";
            Long notFinish = (Long) map.get("count");
            if(notFinish > 0 && org.apache.commons.lang3.StringUtils.isNotBlank(doctor)){
                String notFinishSql ="select o.id,o.number,o.patient,o.patient_name,o.patient_phone,o.patient_expected_serve_time,o.`status`, CASE p.sex when 1 then '男' when 2 THEN '女' END as sex,p.idcard, " +
                        "year(now()) - ((CASE LENGTH(p.idcard) WHEN 18 THEN substring(p.idcard, 7, 4) WHEN 15 THEN CONCAT('19',substring(p.idcard, 7, 2)) END )) as age , p.photo,o.serve_lat AS lat,o.serve_lon AS lon,o.id AS orderId " +
                        "from wlyy_door_service_order o LEFT JOIN base_patient p on o.patient = p.id and p.patient_status=1  " +
                        "where o.doctor ='"+doctor + "' and o.status in (2,3,4)";
                List<Map<String, Object>> notFinishList = jdbcTemplate.queryForList(notFinishSql);
                map.put("notFinishList", notFinishList);
            }
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, sqlResultlist);
        JSONObject countItem = new JSONObject();
        countItem.put("count", count);
        result.putAll(countItem);
        return result;
    }
    /**

+ 265 - 2
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/PatientDoorCoachOrderService.java

@ -12,6 +12,8 @@ import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.BasePatientWechatDo;
import com.yihu.jw.entity.care.doorCoach.*;
import com.yihu.jw.entity.door.WlyyDoorFeeDetailDO;
import com.yihu.jw.entity.door.WlyyDoorOrderItemDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.im.dao.ConsultDao;
@ -23,6 +25,8 @@ import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.jw.wechat.dao.BasePatientWechatDao;
import com.yihu.mysql.query.BaseJpaService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@ -32,6 +36,8 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.math.BigDecimal;
import java.util.*;
@ -57,6 +63,8 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BaseDoorCoachFeeDetailDao doorFeeDetailDao;
    @Autowired
    private BaseDoorCoachDoctorStatusDao baseDoorCoachDoctorStatusDao;
    @Autowired
    private BaseDoorCoachProcessLogDao baseDoorCoachProcessLogDao;
@ -68,6 +76,10 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
    private BasePatientWechatDao basePatientWechatDao;
    @Autowired
    private BaseDoorCoachPatientConfirmLogDao patientConfirmLogDao;
    @Autowired
    private DoctorDoorCoachOrderService doctorDoorCoachOrderService;
    @Autowired
    private BasePatientDao patientInfoService;
    @Autowired
    private MessageUtil messageUtil;
@ -122,6 +134,7 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
        orderDO.setCreateUser(orderDO.getProxyPatient());
        orderDO.setCreateUserName(orderDO.getProxyPatientName());
        orderDO.setOrderInfo("0");
        orderDO.setStatus(1);
//        orderDO.setConclusionStatus(1);
        if(StringUtils.isEmpty(orderDO.getPatient())){
@ -331,6 +344,28 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
        return result;
    }
    /**
     * 根据接单医生code获取最近一次服务orderId
     * @return
     */
    public String getOrderIdByPatient(String patient) {
        String sql = "SELECT id as orderId from base_door_coach_order where patient=? and status in(1,2,3,4,5,6) ORDER BY patient_expected_serve_time desc,update_time desc,create_time desc, status ASC limit 1";
        String orderId = jdbcTemplate.queryForObject(sql, String.class, new Object[]{patient});
        return orderId;
    }
    public List<Map<String,Object>> selectItemsByHospital(String hospital,String serverItemName){
        String sql ="select dict_code code,dict_value name,ext1 fee from base_business_sys_dict where 1=1 ";
        if (StringUtils.isNotBlank(hospital)){
            sql +=" and org_code='"+hospital+"' ";
        }
        if (StringUtils.isNotBlank(serverItemName)){
            sql += " and dict_value like '%"+serverItemName+"%' ";
        }
        List<Map<String,Object>> result = jdbcTemplate.queryForList(sql);
        return result;
    }
    /**
     * 调度员-查询-服务人员列表(医生-可接单状态的)
     *
@ -758,6 +793,12 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
            orderDO.setDispatcherName(dispatcherName);
        }
        //如果是调度员取消,推送IM取消工单json消息,
        if (!consultTeamService.finishDoorCoachConsult(orderDO,orderDO.getPatient(),1)){
            String failMsg = "咨询结束失败 无法取消工单";
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg,failMsg);
            return result;
        }
        orderDO.setStatus(BaseDoorCoachOrderDO.Status.cancel.getType());
        this.save(orderDO);
        if(type == BaseDoorCoachOrderDO.CancelType.dispatcher.getType()){
@ -798,8 +839,11 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
            json.put("id", orderDO.getId());
        }
        List<BasePatientWechatDo> basePatientWechatDos = basePatientWechatDao.findByWechatIdAndPatientId(wxId,patient.getId());
        String openId = basePatientWechatDos.get(0).getOpenid();
        messageUtil.putTemplateWxMessage(wxId,"template_process_feedback","smyyyqx",openId,first,null,null,30,json, DateUtil.dateToChineseDate(new Date()),"上门预约已取消");
        if (basePatientWechatDos.size()>0){
            String openId = basePatientWechatDos.get(0).getOpenid();
            messageUtil.putTemplateWxMessage(wxId,"template_process_feedback","smyyyqx",openId,first,null,null,30,json, DateUtil.dateToChineseDate(new Date()),"上门预约已取消");
        }
        // 工单状态变更记录
@ -956,6 +1000,20 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
            for (Object one : packageItemArray) {
                BaseDoorCoachFeeDetailDO feeDetailDO = null;
                JSONObject oneJson = (JSONObject)one;
                try {
                    feeDetailDO = EntityUtils.jsonToEntity(one.toString(), BaseDoorCoachFeeDetailDO.class);
                    WlyyDoorOrderItemDO orderItemDO = new WlyyDoorOrderItemDO();
                    orderItemDO.setDoctor(order.getDoctor());
                    orderItemDO.setCode(feeDetailDO.getCode());
                    orderItemDO.setCreateTime(new Date());
                    orderItemDO.setPatient(order.getPatient());
                } catch (Exception e) {
                    result.put(ResponseContant.resultFlag, ResponseContant.fail);
                    String failMsg = "工单与服务费用关联关系时," + e.getMessage();
                    result.put(ResponseContant.resultMsg, failMsg);
                    logger.error(failMsg);
                    return true;
                }
                try {
                    //工单主表中记录总费用
                    totalFee = totalFee.add(feeDetailDO.getFee().multiply(BigDecimal.valueOf(feeDetailDO.getNumber())));
@ -1042,6 +1100,211 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
        return result;
    }
    /**
     * 顶部状态栏订单各分类总条数
     * @param patient
     * @return
     */
    public Map<String, Integer> getNumGroupByStatus(String patient) throws Exception {
        String sql = "SELECT a.status, COUNT(DISTINCT a.id) as num FROM base_door_coach_order a  where a.patient = '"+patient+"' group BY a.status " ;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        Map<String, Integer> map = new HashMap<>();
        Integer all = list.size();
        Integer waitForServe = 0;
        Integer served = 0;
        Integer cancel = 0;
        // -1已取消 [1,4]待服务 [5,6]已服务
        for (Map<String, Object> tmp:list){
            switch (String.valueOf(tmp.get("status"))){
                case "-1":
                    cancel += Integer.valueOf(tmp.get("num").toString()) ;
                    break;
                case "1":
                    waitForServe += Integer.valueOf(tmp.get("num").toString()) ;
                    break;
                case "2":
                    waitForServe += Integer.valueOf(tmp.get("num").toString()) ;
                    break;
                case "3":
                    waitForServe += Integer.valueOf(tmp.get("num").toString()) ;
                    break;
                case "4":
                    waitForServe += Integer.valueOf(tmp.get("num").toString()) ;
                    break;
                case "5":
                    served += Integer.valueOf(tmp.get("num").toString()) ;
                    break;
                case "6":
                    served += Integer.valueOf(tmp.get("num").toString()) ;
                    break;
                default: {
                    throw new Exception("类型错误!"+String.valueOf(tmp.get("status")));
                }
            }
        }
        map.put("all",all);
        map.put("waitForServe",waitForServe);
        map.put("served",served);
        map.put("cancel",cancel);
        return map;
    }
    /**
     *
     * @param orderId
     * @param patientName
     * @param patientPhone
     * @param hospitalCode
     * @param status
     * @param createTimeStart
     * @param createTimeEnd
     * @param serverDoctorName
     * @param patientId
     * @param page
     * @param pageSize
     * @param type
     * @return
     * @throws Exception
     */
    public JSONObject getDoorOrderList(String orderId, String patientName, String patientPhone, String hospitalCode,
                                       StringBuffer status, String createTimeStart, String createTimeEnd, String serverDoctorName,
                                       String patientId, Integer page, Integer pageSize, Integer type)throws Exception{
        String sqlList = "select DISTINCT o.id as orderId,o.status,h.code orgCode,h.name as orgName,o.is_trans_other_org," +
                "o.transed_org_code, o.patient_name, o.patient_phone,o.remark,o.serve_desc,o.create_time,o.patient as patientCode," +
                "o.exam_paper_status as examPaperStatus,o.number as serverCode,o.total_fee,h.org_level as hosLevel, o.doctor," +
                "o.doctor_name as doctorName, o.doctor_type as doctorType"
                ;
        String sqlCount = " select count(DISTINCT o.id) as total ";
        String sql = " from base_door_coach_order o LEFT JOIN base_org h on h.code=o.hospital and h.del=1 where 1=1";
        if(!org.apache.commons.lang.StringUtils.isEmpty(orderId)){
            sql+=" and o.number = '"+orderId+"'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(patientName)){
            sql+=" and o.patient_name like '%"+patientName+"%'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(patientPhone)){
            sql+=" and o.patient_phone ='"+patientPhone+"'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(hospitalCode)&&!"350200%".equals(hospitalCode)){
            sql+=" and (o.hospital like '"+hospitalCode+"' or o.transed_org_code like '"+hospitalCode+"') ";
        }
        if(status!=null){
            sql+=" and o.status in ("+status+")";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(createTimeStart)){
            sql+=" and o.create_time >='"+createTimeStart+"'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(createTimeEnd)){
            sql+=" and o.create_time <='"+createTimeEnd+"'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(serverDoctorName)){
            sql+=" and o.doctor_name like '%"+serverDoctorName+"%'";
        }
        //获取医生代预约记录
        sql += " and o.type = " + type +" ";
        if(org.apache.commons.lang.StringUtils.isNotBlank(patientId)){
            sql += " and o.patient= '"+patientId+"' ";
        }
        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sqlCount+sql);
        sql+=" order by o.create_time desc LIMIT "+(page-1)*pageSize+","+pageSize;
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sqlList+sql);
        Long count = 0L;
        if(rstotal!=null&&rstotal.size()>0){
            count = (Long) rstotal.get(0).get("total");
        }
        JSONArray jsonArray = new JSONArray();
        for(Map<String,Object> one:list){
            JSONObject object = new JSONObject();
            object.put("id",one.get("orderId"));
            object.put("serverCode",one.get("serverCode"));
            Integer statustemp = Integer.valueOf(one.get("status")+"");
            String statusName = "";
            switch (statustemp){
                case -1:statusName="已取消";break;
                case 1:statusName="待服务";break;
                case 2:statusName="待服务";break;
                case 3:statusName="待服务";break;
                case 4:statusName="待服务";break;
                case 5:statusName="已完成";break;
                case 6:statusName="已完成";break;
            }
            object.put("status",statustemp);
            object.put("statusName",statusName);
            //工单是否转给其他机构,0-不转,1-已转
            String transOtherOrg = one.get("is_trans_other_org")+"";
            Object hospitalName = null;
            Object hospital = null;
            hospital = one.get("orgCode");
            hospitalName = one.get("orgName");//签约表中的机构
            object.put("hospital",hospital);
            object.put("hospitalName",hospitalName);
            object.put("patient",one.get("patientCode"));
            object.put("patientName",one.get("patient_name"));
            object.put("patientPhone",one.get("patient_phone"));
            object.put("remark",one.get("remark"));
            object.put("serveDesc",one.get("serve_desc"));
            object.put("hosLevel",one.get("hosLevel"));
            Date date = (Date)one.get("create_time");
            object.put("createTime",DateUtil.dateToStr(date,"yyyy-MM-dd HH:mm:ss"));
            object.put("examPaperStatus",one.get("examPaperStatus"));
            object.put("totalFee",one.get("total_fee"));
            List<BaseDoorCoachFeeDetailDO> feeDetailDOs = doorFeeDetailDao.findByOrderIdAndType(one.get("orderId")+"", 1);
            List<Map<String,Object>> feeDetailResultList = new ArrayList();
            for(BaseDoorCoachFeeDetailDO d:feeDetailDOs){
                Map<String,Object> map = new HashMap<>();
                map.put("code",d.getCode());
                map.put("name",d.getName());
                map.put("fee",d.getFee());
                map.put("number",d.getNumber());
                feeDetailResultList.add(map);
            }
            object.put("feeDetailResultList",feeDetailResultList);
            // 获取或者基本信息
            BasePatientDO patient = patientInfoService.findById(String.valueOf(one.get("patientCode")));
            if (patient != null) {
                object.put("sex", IdCardUtil.getSexForIdcard(patient.getIdcard()));
                object.put("age", IdCardUtil.getAgeByIdcardOrBirthday(patient.getIdcard(),patient.getBirthday()));
                object.put("photo", patient.getPhoto());
//                object.put("typeValue", "儿童");
            }
            String id = one.get("orderId").toString();
            BaseDoorCoachOrderDO doorServiceOrder = this.baseDoorCoachOrderDao.findOne(id);
            //获取咨询
            ConsultDo consult = consultDao.queryByRelationCode(id);
            if (null != consult) {
                doorServiceOrder.setSessionId(doorServiceOrder.getPatient() + "_" + consult.getId() + "_"  + doorServiceOrder.getNumber() +  "_" +  consult.getType());
            }
            object.put("sessionId",doorServiceOrder.getSessionId());
            // 获取服务次数
            Integer serviceCount = doctorDoorCoachOrderService.serviceCount(doorServiceOrder.getPatient());
            object.put("serviceCount", serviceCount);
            //添加服务医生
            object.put("doctorName", doorServiceOrder.getDoctorName());
            object.put("doctorType", doorServiceOrder.getDoctorType());
            object.put("type", doorServiceOrder.getType());
            jsonArray.add(object);
        }
        JSONObject object = new JSONObject();
        object.put("total",count);
        object.put("detailModelList",jsonArray);
        object.put("currPage",page);
        object.put("pageSize",pageSize);
        return object;
    }
    /**
     * 添加【工单派单,转单】等系统消息

+ 0 - 272
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/prescription/PresModeAdapter.java

@ -1,272 +0,0 @@
package com.yihu.jw.care.service.prescription;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Iterator;
/**
 * Created by Trick on 2017/8/10.
 */
@Component
public class PresModeAdapter {
    private static Logger logger = LoggerFactory.getLogger(PresModeAdapter.class);
/*    @Autowired
    private ZyDictService zyDictService;
    @Autowired
    private DictIcd10Se icd10DictServcie;*/
    /**
     * 处方详情转换
     * @param json
     * @return
     */
    public JSONObject modelToSinglePrescription(String json){
        try{
            JSONObject oldJson = JSONObject.parseObject(json);
            if(oldJson.getInteger("status")!=200){
                throw new RuntimeException("智业接口失败:"+oldJson.getString("msg"));
            }
            JSONObject data = JSONObject.parseObject(oldJson.getString("data"));
            JSONArray returnData = data.getJSONArray("returnData");
            String code = data.getString("CODE");
            if(StringUtils.isNotBlank(code)&&"1".equals(code)&&returnData.size()>0){
                JSONArray modeArray = returnData.getJSONArray(0);
                JSONObject mode = (JSONObject) modeArray.get(0);
                JSONObject p  = new JSONObject();
                p.put("code",mode.getInteger("RECIPE_NO")+"");
                p.put("createTime",mode.getString("APPLY_TIME"));
/*                Doctor doctor =  zyDictService.getDoctByJw(mode.getString("APPLY_OPERATOR"),mode.getString("HEALTH_ORG_CODE"));
                // "APPLY_OPERATOR_NAME": 开单医生姓名","HEALTH_ORG_CODE": "开单机构编码",
                if(doctor!=null){
                    p.put("doctor",doctor.getCode());
                    p.put("doctorName",doctor.getName());
                    p.put("hospitalName",doctor.getHospitalName());
                    p.put("hospital",doctor.getHospital());
                    p.put("jwHospital",mode.getString("HEALTH_ORG_CODE"));
                }else{
                    p.put("doctor",mode.getString("APPLY_OPERATOR"));
                    p.put("doctorName",mode.getString("APPLY_OPERATOR_NAME"));
                    p.put("hospitalName",mode.getString("HEALTH_ORG_CODE"));
                    p.put("jwHospital",mode.getString("HEALTH_ORG_CODE"));
                }*/
                JSONObject diagnosis = new JSONObject();
                String diagnoseCode = mode.getString("DIAGNOSE_CODE");
                String diagnoseName = mode.getString("DIAGNOSE_NAME");
//                String diagnoseCode = "E10.100";
//                String diagnoseName = "1型糖尿病性酮症";
                diagnosis.put("code",diagnoseCode);//诊断代码
                diagnosis.put("name",diagnoseName);//诊断名称
/*                String icd10 = icd10DictServcie.getHealthProblemsByIcd10Code(diagnoseCode);
                if(!StringUtils.isEmpty(icd10)){
                    JSONObject icd = JSONObject.parseObject(icd10);
                    diagnosis.put("healthProblemName",icd.getString("value"));//诊断名称
                    diagnosis.put("healthProblem",icd.getString("key"));//诊断代码
                }else{
                    diagnosis.put("healthProblemName",diagnoseName);//诊断名称
                    diagnosis.put("healthProblem",diagnoseCode);//诊断代码
                }*/
                JSONArray jsonArrayDt = new JSONArray();
                jsonArrayDt.add(diagnosis);
    
                if(mode.getString("DIAGNOSE_SUB_CODE")!=null){
                    JSONObject diagnosisSub = new JSONObject();
                    String diagnoseCodeSub = mode.getString("DIAGNOSE_SUB_CODE");
                    String diagnoseNameSub = mode.getString("DIAGNOSE_SUB_NAME");
                    diagnosisSub.put("code",diagnoseCodeSub);//诊断代码
                    diagnosisSub.put("name",diagnoseNameSub);//诊断名称
/*                    String icd10Sub = icd10DictServcie.getHealthProblemsByIcd10Code(diagnoseCodeSub);
                    if(!StringUtils.isEmpty(icd10Sub)){
                        JSONObject icdSub = JSONObject.parseObject(icd10Sub);
                        diagnosisSub.put("healthProblemName",icdSub.getString("value"));//诊断名称
                        diagnosisSub.put("healthProblem",icdSub.getString("key"));//诊断代码
                    }else{
                        diagnosisSub.put("healthProblemName",diagnoseNameSub);//诊断名称
                        diagnosisSub.put("healthProblem",diagnoseCodeSub);//诊断代码
                    }*/
                    jsonArrayDt.add(diagnosisSub);
                }
                
                p.put("prescriptionDt",jsonArrayDt);
                JSONArray infos = mode.getJSONArray("RECIPE_DETAIL");
                Iterator infoIt = infos.iterator();
                JSONArray prescriptionInfos = new JSONArray();
                while (infoIt.hasNext()){
                    JSONObject info = (JSONObject) infoIt.next();
                    JSONObject prescriptionInfo = new JSONObject();
                    prescriptionInfo.put("Remark",info.getString("REMARK"));
                    prescriptionInfo.put("BindFlag",info.getString("BIND_FLAG"));
                    prescriptionInfo.put("direction",info.getString("USAGE_NAME"));//药品用法
                    prescriptionInfo.put("drugCode",info.getString("ITEM_CODE"));//药品code
                    prescriptionInfo.put("drugName",info.getString("ITEM_NAME"));//药品名称
                    prescriptionInfo.put("drugRate",info.getString("FREQUENCY"));//吃药频率 FREQUENCY
                    prescriptionInfo.put("drugRateName",info.getString("FREQUENCY_NAME"));
                    prescriptionInfo.put("drugFormat",info.getString("ITEM_SPEC"));//药品规格
                    prescriptionInfo.put("price",info.getDouble("ITEM_PRICE"));//药品单价
                    prescriptionInfo.put("num",info.getInteger("ITEM_QUANTITY"));//药品数目
                    prescriptionInfo.put("jwSubCode",info.getString("RECIPE_SUB_NO"));//智业子处方号
                    prescriptionInfo.put("drugNumUnit",info.getString("ITEM_UNIT"));//数量单位编码
                    prescriptionInfo.put("drugNumUnitName",info.getString("ITEM_UNIT_NAME"));//数量单位名称
                    prescriptionInfo.put("cost",info.getDouble("COST"));//金额
                    prescriptionInfo.put("charge",info.getDouble("CHARGE"));//自付
                    prescriptionInfo.put("bindFlag",info.getString("BIND_FLAG"));//成组标志, 0.非成组,1.成组
                    prescriptionInfo.put("dayCount",info.getInteger("DAY_COUNT"));//用药天数
                    prescriptionInfo.put("drugUsage",info.getString("USAGE"));//用药方法编码
                    prescriptionInfo.put("usageName",info.getString("USAGE_NAME"));//用药方法名称
                    prescriptionInfo.put("physicDose",info.getString("PHYSIC_DOSE"));//用药剂量
                    prescriptionInfo.put("physicDoseUnit",info.getString("PHYSIC_DOSE_UNIT"));//剂量单位编码
                    prescriptionInfo.put("physicDoseUnitName",info.getString("PHYSIC_DOSE_UNIT_NAME"));//剂量单位名称
                    prescriptionInfo.put("physicAmount",info.getString("PHYSIC_AMOUNT"));//用药总量
                    prescriptionInfo.put("physicAmountUnit",info.getString("PHYSIC_AMOUNT_UNIT"));//总量单位编码
                    prescriptionInfo.put("physicAmountUnitName",info.getString("PHYSIC_AMOUNT_UNIT_NAME"));//总量单位名称
                    prescriptionInfo.put("physicInjectPlace",info.getString("PHYSIC_INJECT_PLACE"));//注射地点编码
                    prescriptionInfo.put("physicInjectPlaceName",info.getString("PHYSIC_INJECT_PLACE_NAME"));//注射地点名称
                    prescriptionInfo.put("physicSkinTest",info.getString("PHYSIC_SKIN_TEST"));//皮试类型名称
                    prescriptionInfo.put("physicSkinTestName",info.getString("PHYSIC_SKIN_TEST_NAME"));//皮试类型名称
                    prescriptionInfo.put("subjectClass",info.getString("SUBJECT_CLASS"));//科目类型
                    prescriptionInfos.add(prescriptionInfo);
                }
                p.put("prescriptionInfo",prescriptionInfos);
                return p;
            }
        }catch (Exception e){
            logger.info("PresModeAdapter:modelToSinglePrescription:Json:"+json);
            throw e;
        }
        return new JSONObject();
    }
    /**
     * 思明上门处方详情转换
     * @param json
     * @return
     */
    public JSONArray modelToDoorPrescription(String json){
        try{
            JSONArray res = new JSONArray();
            JSONObject oldJson = JSONObject.parseObject(json);
            if(oldJson.getInteger("status")!=200){
                throw new RuntimeException("智业接口失败:"+oldJson.getString("msg"));
            }
            JSONObject data = JSONObject.parseObject(oldJson.getString("data"));
            JSONArray returnData = data.getJSONArray("returnData").getJSONArray(0);
            String code = data.getString("CODE");
            if(StringUtils.isNotBlank(code)&&"1".equals(code)&&returnData.size()>0){
                for(Object o : returnData) {
//                    JSONArray modeArray = returnData.getJSONArray(0);
                    JSONObject mode = (JSONObject) o;
                    JSONObject p = new JSONObject();
                    p.put("code", mode.getInteger("RECIPE_NO") + "");
                    p.put("createTime", mode.getString("APPLY_TIME"));
/*                    Doctor doctor = zyDictService.getDoctByJw(mode.getString("APPLY_OPERATOR"), mode.getString("HEALTH_ORG_CODE"));
                    // "APPLY_OPERATOR_NAME": 开单医生姓名","HEALTH_ORG_CODE": "开单机构编码",
                    if (doctor != null) {
                        p.put("doctor", doctor.getCode());
                        p.put("doctorName", doctor.getName());
                        p.put("hospitalName", doctor.getHospitalName());
                        p.put("hospital", doctor.getHospital());
                        p.put("jwHospital", mode.getString("HEALTH_ORG_CODE"));
                    } else {
                        p.put("doctor", mode.getString("APPLY_OPERATOR"));
                        p.put("doctorName", mode.getString("APPLY_OPERATOR_NAME"));
                        p.put("hospitalName", mode.getString("HEALTH_ORG_CODE"));
                        p.put("jwHospital", mode.getString("HEALTH_ORG_CODE"));
                    }*/
                    JSONObject diagnosis = new JSONObject();
                    String diagnoseCode = mode.getString("DIAGNOSE_CODE");
                    String diagnoseName = mode.getString("DIAGNOSE_NAME");
//                String diagnoseCode = "E10.100";
//                String diagnoseName = "1型糖尿病性酮症";
                    diagnosis.put("code", diagnoseCode);//诊断代码
                    diagnosis.put("name", diagnoseName);//诊断名称
/*                    String icd10 = icd10DictServcie.getHealthProblemsByIcd10Code(diagnoseCode);
                    if (!StringUtils.isEmpty(icd10)) {
                        JSONObject icd = JSONObject.parseObject(icd10);
                        diagnosis.put("healthProblemName", icd.getString("value"));//诊断名称
                        diagnosis.put("healthProblem", icd.getString("key"));//诊断代码
                    } else {
                        diagnosis.put("healthProblemName", diagnoseName);//诊断名称
                        diagnosis.put("healthProblem", diagnoseCode);//诊断代码
                    }*/
                    JSONArray jsonArrayDt = new JSONArray();
                    jsonArrayDt.add(diagnosis);
                    if (mode.getString("DIAGNOSE_SUB_CODE") != null) {
                        JSONObject diagnosisSub = new JSONObject();
                        String diagnoseCodeSub = mode.getString("DIAGNOSE_SUB_CODE");
                        String diagnoseNameSub = mode.getString("DIAGNOSE_SUB_NAME");
                        diagnosisSub.put("code", diagnoseCodeSub);//诊断代码
                        diagnosisSub.put("name", diagnoseNameSub);//诊断名称
/*                        String icd10Sub = icd10DictServcie.getHealthProblemsByIcd10Code(diagnoseCodeSub);
                        if (!StringUtils.isEmpty(icd10Sub)) {
                            JSONObject icdSub = JSONObject.parseObject(icd10Sub);
                            diagnosisSub.put("healthProblemName", icdSub.getString("value"));//诊断名称
                            diagnosisSub.put("healthProblem", icdSub.getString("key"));//诊断代码
                        } else {
                            diagnosisSub.put("healthProblemName", diagnoseNameSub);//诊断名称
                            diagnosisSub.put("healthProblem", diagnoseCodeSub);//诊断代码
                        }*/
                        jsonArrayDt.add(diagnosisSub);
                    }
//                    p.put("prescriptionDt", jsonArrayDt);
                    JSONArray infos = mode.getJSONArray("RECIPE_DETAIL");
                    Iterator infoIt = infos.iterator();
                    JSONArray prescriptionInfos = new JSONArray();
                    while (infoIt.hasNext()) {
                        JSONObject info = (JSONObject) infoIt.next();
                        JSONObject prescriptionInfo = new JSONObject();
                        prescriptionInfo.put("Remark", info.getString("REMARK"));
                        prescriptionInfo.put("BindFlag", info.getString("BIND_FLAG"));
                        prescriptionInfo.put("direction", info.getString("USAGE_NAME"));//药品用法
                        prescriptionInfo.put("drugCode", info.getString("ITEM_CODE"));//药品code
                        prescriptionInfo.put("drugName", info.getString("ITEM_NAME"));//药品名称
                        prescriptionInfo.put("drugRate", info.getString("FREQUENCY"));//吃药频率 FREQUENCY
                        prescriptionInfo.put("drugRateName", info.getString("FREQUENCY_NAME"));
                        prescriptionInfo.put("drugFormat", info.getString("ITEM_SPEC"));//药品规格
                        prescriptionInfo.put("price", info.getDouble("ITEM_PRICE"));//药品单价
                        prescriptionInfo.put("num", info.getInteger("ITEM_QUANTITY"));//药品数目
                        prescriptionInfo.put("jwSubCode", info.getString("RECIPE_SUB_NO"));//智业子处方号
                        prescriptionInfo.put("drugNumUnit", info.getString("ITEM_UNIT"));//数量单位编码
                        prescriptionInfo.put("drugNumUnitName", info.getString("ITEM_UNIT_NAME"));//数量单位名称
                        prescriptionInfo.put("cost", info.getDouble("COST"));//金额
                        prescriptionInfo.put("charge", info.getDouble("CHARGE"));//自付
                        prescriptionInfo.put("bindFlag", info.getString("BIND_FLAG"));//成组标志, 0.非成组,1.成组
                        prescriptionInfo.put("dayCount", info.getInteger("DAY_COUNT"));//用药天数
                        prescriptionInfo.put("drugUsage", info.getString("USAGE"));//用药方法编码
                        prescriptionInfo.put("usageName", info.getString("USAGE_NAME"));//用药方法名称
                        prescriptionInfo.put("physicDose", info.getString("PHYSIC_DOSE"));//用药剂量
                        prescriptionInfo.put("physicDoseUnit", info.getString("PHYSIC_DOSE_UNIT"));//剂量单位编码
                        prescriptionInfo.put("physicDoseUnitName", info.getString("PHYSIC_DOSE_UNIT_NAME"));//剂量单位名称
                        prescriptionInfo.put("physicAmount", info.getString("PHYSIC_AMOUNT"));//用药总量
                        prescriptionInfo.put("physicAmountUnit", info.getString("PHYSIC_AMOUNT_UNIT"));//总量单位编码
                        prescriptionInfo.put("physicAmountUnitName", info.getString("PHYSIC_AMOUNT_UNIT_NAME"));//总量单位名称
                        prescriptionInfo.put("physicInjectPlace", info.getString("PHYSIC_INJECT_PLACE"));//注射地点编码
                        prescriptionInfo.put("physicInjectPlaceName", info.getString("PHYSIC_INJECT_PLACE_NAME"));//注射地点名称
                        prescriptionInfo.put("physicSkinTest", info.getString("PHYSIC_SKIN_TEST"));//皮试类型名称
                        prescriptionInfo.put("physicSkinTestName", info.getString("PHYSIC_SKIN_TEST_NAME"));//皮试类型名称
                        prescriptionInfo.put("subjectClass", info.getString("SUBJECT_CLASS"));//科目类型
                        prescriptionInfos.add(prescriptionInfo);
                    }
                    p.put("prescriptionInfo", prescriptionInfos);
                    res.add(p);
                }
                return res;
            }
        }catch (Exception e){
            logger.info("PresModeAdapter:modelToSinglePrescription:Json:"+json);
            throw e;
        }
        return new JSONArray();
    }
}

+ 0 - 667
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/StatisticsUtilService.java

@ -1,667 +0,0 @@
package com.yihu.jw.care.service.statistics;
import com.yihu.jw.es.service.StatisticsEsService;
import com.yihu.jw.es.util.ElasticsearchUtil;
import com.yihu.jw.es.util.SaveModel;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.text.DecimalFormat;
import java.util.*;
/**
 * 统计工具类
 * Created by yeshijie on 2020/12/14.
 */
@Service
public class StatisticsUtilService {
    @Value("${es.type.Statistics}")
    private String esType;
    @Value("${es.index.Statistics}")
    private String esIndex;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private StatisticsEsService statisticsESService;
    public final String commonParams = "xmijk_quota";
    /**
     * 根据开始时间 结束时间判断查询增量还是到达量
     * @param startDate
     * @param endDate
     * @return
     */
    public String getDDLOrZL(String startDate,String endDate){
        String ddlOrZl = "1";
        if(endDate.equals(startDate)){
            ddlOrZl = SaveModel.timeLevel_DDL;
        }
        return ddlOrZl;
    }
    /**
     * 获取签约开始时间,7月1号
     * @return
     */
    public String getSignStartDay(){
        return DateUtil.getSignYear()+"-07-01";
    }
    /**
     * 如果开始时间是7月1号 就设置为结束时间
     * @param startDate
     * @param endDate
     * @return
     */
    public String getStartDate(String startDate,String endDate){
        if(startDate.equals(getSignStartDay())){
            return endDate;
        }
        return startDate;
    }
    /**
     * 是否是专科
     * @param level
     * @param area
     * @return
     */
    public boolean isSpecialist(int level,String area){
        if(level == 4 && area.length() != 10){
            return true;
        }
        return false;
    }
    /**
     * 获取下转的map
     * @param saveModel
     * @param lowLevel
     * @param result2Name
     * @return
     */
    public Map<String, Object> getMapTurnDownResult2(SaveModel saveModel,String lowLevel,String result2Name){
        Map<String, Object> map = getMapTurnDown(saveModel, lowLevel);
        map.put(result2Name, saveModel.getResult2().longValue());
        return map;
    }
    public Map<String, Object> getMapTurnDownResult12(SaveModel saveModel,String lowLevel,String result1Name,String result2Name){
        Map<String, Object> map = getMapTurnDown(saveModel, lowLevel);
        map.put(result1Name, saveModel.getResult1());
        map.put(result2Name, saveModel.getResult2().longValue());
        return map;
    }
    public Map<String, Object> getMapTurnDown(SaveModel saveModel,String lowLevel){
        Map<String, Object> map = new HashMap<>(16);
        if (SaveModel.OrgLevel.equals(lowLevel)) {
            map.put("code", saveModel.getHospital());
            map.put("name", saveModel.getHospitalName());
        } else if (SaveModel.townLevel.equals(lowLevel)) {
            map.put("code", saveModel.getTown());
            map.put("name", saveModel.getTownName());
        } else if (SaveModel.cityLevel.equals(lowLevel)) {
            map.put("code", saveModel.getCity());
            map.put("name", saveModel.getCityName());
        } else if (SaveModel.deptLevel.equals(lowLevel)) {
            map.put("code", saveModel.getDept());
            map.put("name", saveModel.getDeptName());
        }else if (SaveModel.doctorLevel.equals(lowLevel)) {
            map.put("code", saveModel.getDoctor());
            map.put("name", saveModel.getDoctorName());
        }
        return map;
    }
    public boolean compareSaveModel(SaveModel saveModel1,SaveModel saveModel2,String lowLevel){
        if (SaveModel.OrgLevel.equals(lowLevel) && saveModel1.getHospital() != null && saveModel2.getHospital() != null) {
            return saveModel1.getHospital().equals(saveModel2.getHospital());
        } else if (SaveModel.townLevel.equals(lowLevel) && saveModel1.getTown() != null && saveModel2.getTown() != null) {
            return saveModel1.getTown().equals(saveModel2.getTown());
        } else if (SaveModel.cityLevel.equals(lowLevel) && saveModel1.getCity() != null && saveModel2.getCity() != null) {
            return saveModel1.getCity().equals(saveModel2.getCity());
        } else if (SaveModel.deptLevel.equals(lowLevel) && saveModel1.getDept() != null && saveModel2.getDept() != null) {
            return saveModel1.getDept().equals(saveModel2.getDept());
        }else if (SaveModel.doctorLevel.equals(lowLevel) && saveModel1.getDoctor() != null && saveModel2.getDoctor() != null) {
            return saveModel1.getDoctor().equals(saveModel2.getDoctor());
        }
        return false;
    }
    /**
     * 获取到达量或者增量
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param level2_type
     * @return
     * @throws Exception
     */
    public long getTotalAmountDDLOrZL(String startDate, String endDate, String area, int level, String index, String level2_type) throws Exception{
        if(endDate.equals(startDate)){
            return getTotalAmount3DDL(startDate, endDate, area, level, index, level2_type);
        }
        return getTotalAmount3ZL(startDate, endDate, area, level, index, level2_type);
    }
    public long getTotalAmount3ZL(String startDate, String endDate, String area, int level, String index, String level2_type) throws Exception {
        SaveModel saveModel = null;
        if (StringUtils.isNotEmpty(level2_type)) {
            saveModel = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, level2_type);
        } else {
            saveModel = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL);
        }
        return saveModel.getResult2().longValue();
    }
    public long getTotalAmount3DDL(String startDate, String endDate, String area, int level, String index, String level2_type) throws Exception {
        SaveModel saveModel = null;
        if (StringUtils.isNotEmpty(level2_type)) {
            saveModel = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, index, SaveModel.timeLevel_DDL, level2_type);
        } else {
            saveModel = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_DDL);
        }
        return saveModel.getResult2().longValue();
    }
    public Map<String, Object> saveModelToMap(SaveModel saveModel){
        Map<String, Object> map = new HashMap<>(16);
        map.put("range", DateUtil.dateToStr(saveModel.getQuotaDate(), "yyyy-MM-dd"));
        map.put("amount", saveModel.getResult2());
        return map;
    }
    public Map<String, Object> slaveKay1ToMapLong(SaveModel saveModel){
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", saveModel.getSlaveKey1());
        map.put("name", saveModel.getSlaveKey1Name());
        map.put("num", saveModel.getResult2().longValue());
        return map;
    }
    public Map<String, Object> slaveKay1ToMapLong2(SaveModel saveModel){
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", saveModel.getSlaveKey1());
        map.put("name", saveModel.getSlaveKey1Name());
        map.put("num", saveModel.getResult2().longValue());
        map.put("price", saveModel.getResult1());
        return map;
    }
    public Map<String, Object> slaveKay2ToMapLong(SaveModel saveModel){
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", saveModel.getSlaveKey2());
        map.put("name", saveModel.getSlaveKey2Name());
        map.put("num", saveModel.getResult2().longValue());
        return map;
    }
    /**
     * 计算开始时间
     * @param endDate
     * @param type 1周,2月
     * @return
     */
    public String calStart(String endDate,String type){
        if(StringUtils.isEmpty(endDate)){
            return endDate;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(DateUtil.strToDate(endDate));
        if("1".equals(type)){
            if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
                cal.add(Calendar.DAY_OF_WEEK,-1);
            }
            cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
        }else{
            cal.set(Calendar.DAY_OF_MONTH,1);
        }
        return DateUtil.dateToStrShort(cal.getTime());
    }
    public String getSaveModelCode(int level,SaveModel saveModel){
        if(level == 4){
            return saveModel.getDept();
        }else if(level == 3){
            return saveModel.getHospital();
        }else if(level == 2){
            return saveModel.getTown();
        }
        return null;
    }
    /**
     * 按sortName排序 降序
     * @param resultList
     */
    public void sortDoubleList(List<Map<String,Object>> resultList, String sortName){
        resultList.sort((x,y)->{
            if ( (Long) x.get(sortName) > (Long) y.get(sortName)) {
                return 1;
            } else if ((Long) x.get(sortName) < (Long) y.get(sortName)) {
                return -1;
            } else {
                return 0;
            }
        });
    }
    /**
     *  降序
     * @param resultList
     * @param sortName
     */
    public void sortLongList(List<Map<String,Object>> resultList,String sortName){
        resultList.sort((x,y)->{
            if ( (Long) x.get(sortName) > (Long) y.get(sortName)) {
                return -1;
            } else if ((Long) x.get(sortName) < (Long) y.get(sortName)) {
                return 1;
            } else {
                return 0;
            }
        });
    }
    /**************************************************封装的方法 start ********************************************/
    /**
     * 查询总量
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timelevel
     * @param slaveKey1
     * @return
     * @throws Exception
     */
    public long getTotalAmount(String startDate, String endDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception{
        if(SaveModel.timeLevel_DDL.equals(timelevel)){
            return getTotalAmount3DDL(startDate,endDate,area,level,index,slaveKey1);
        }else {
            return getTotalAmount3ZL(startDate,endDate,area,level,index,slaveKey1);
        }
    }
    /**
     * 查一级指标
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param interval
     * @param slaveKey1
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel0BySlaveKey1(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String slaveKey1) throws Exception {
        if(StringUtils.isEmpty(slaveKey1)){
            return elasticsearchUtil.findDateQuotaLevel0(startDate, endDate, area, level, index, timeLevel, interval, null);
        }else {
            return findDateQuotaLevel0BySlaveKey1(startDate,endDate,area,level,index,timeLevel,interval,null,slaveKey1);
        }
    }
    public long getTotalAmountLevel2BySlaveKey1(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String slaveKey2 ) throws Exception{
        SaveModel saveModel = findOneDateQuotaLevel2BySlaveKey1(startDate, endDate, area, level, index, timeLevel, slaveKey1, slaveKey2);
        return saveModel.getResult1().longValue();
    }
    public SaveModel findOneDateQuotaLevel2BySlaveKey1(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String slaveKey2) throws Exception {
        if(StringUtils.isEmpty(slaveKey2)){
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2BySlaveKey1(startDate, endDate, area, level, index, timeLevel, slaveKey1, slaveKey2,null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 查找一级或二级维度
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param slaveKey1
     * @param slaveKey2
     * @param interval
     * @param lowLevel
     * @return
     */
    public List findDateQuotaLevel2BySlaveKey1(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String slaveKey2, String interval, String lowLevel) {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        startDate = changeDateTime(startDate);
        endDate = changeDateTime(endDate);
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        sqlGroupBySlaveKey(sql,groupBy,low_level,slaveKey2,"slaveKey2","slaveKey2Name");
        sqlArea(sql,area,level,index,timeLevel,startDate,endDate);
        sqlSlaveKey(slaveKey1,"slaveKey1",sql);
        sqlSlaveKey(slaveKey2,"slaveKey2",sql);
        //根据时间维度分组
        groupByInterval(interval,groupBy);
        sql.append(groupBy);
        return elasticsearchUtil.excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
     * @param dateTime
     * @return
     */
    public String changeDateTime(String dateTime){
        if (StringUtils.isNotEmpty(dateTime)) {
            if (dateTime.length() > 10) {
                return elasticsearchUtil.changeTime(dateTime);
            } else {
                return elasticsearchUtil.changeDate(dateTime);
            }
        }
        return dateTime;
    }
    public void groupByInterval(String interval,StringBuffer groupBy){
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
    }
    public void sqlArea(StringBuffer sql,String area,int level,boolean isAnd){
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" team='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            if(isAnd){
                sql.append(" and ");
            }
        }
    }
    public void sqlArea(StringBuffer sql,String area,int level,String index,String timeLevel,String startDate,String endDate){
        sqlArea(sql,area,level,true);
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='5'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
    }
    public void sqlSlaveKey(String slaveKey,String slaveKeyName,StringBuffer sql){
        if (StringUtils.isNotBlank(slaveKey)&&!commonParams.equals(slaveKey)) {
            String[] str = slaveKey.split(",");
            StringBuffer buffer = new StringBuffer();
            for (int i=0;i<str.length;i++){
                buffer.append("'"+str[i]+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            sql.append(" and "+slaveKeyName+" in (" + buffer + ")");
        }
    }
    public void groupBySlaveKey(StringBuffer groupBy,String slaveKeyValue,String slaveKey,String slaveKeyName){
        if (StringUtils.isNotEmpty(slaveKeyValue)||commonParams.equals(slaveKeyValue)) {
            groupBy.append(","+slaveKey+","+slaveKeyName);
        }
    }
    public void sqlGroupBySlaveKey(StringBuffer sql,StringBuffer groupBy,String low_level,String slaveKeyValue,String slaveKey,String slaveKeyName){
        String tmp = "";
        if(StringUtils.isNotBlank(slaveKeyValue)){
            tmp = slaveKey +","+slaveKeyName+",";
        }
        if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select team,teamName,"+tmp+"sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by team,teamName");
            groupBySlaveKey(groupBy,slaveKeyValue,slaveKey,slaveKeyName);
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital,hospitalName,"+tmp+"sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
            groupBySlaveKey(groupBy,slaveKeyValue,slaveKey,slaveKeyName);
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town,townName,"+tmp+"sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
            groupBySlaveKey(groupBy,slaveKeyValue,slaveKey,slaveKeyName);
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,"+tmp+"sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
            groupBySlaveKey(groupBy,slaveKeyValue,slaveKey,slaveKeyName);
        }
    }
    public List findDateQuotaLevel3BySlaveKey13(String startDate, String endDate, String area, int level, String index,
           String timeLevel, String slaveKey1, String slaveKey2,String slaveKey3, String interval, String lowLevel) {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        startDate = changeDateTime(startDate);
        endDate = changeDateTime(endDate);
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        sqlGroupBySlaveKey(sql,groupBy,low_level,slaveKey1,"slaveKey1","slaveKey1Name");
        sqlArea(sql,area,level,index,timeLevel,startDate,endDate);
        sqlSlaveKey(slaveKey1,"slaveKey1",sql);
        sqlSlaveKey(slaveKey2,"slaveKey2",sql);
        sqlSlaveKey(slaveKey3,"slaveKey3",sql);
        //根据时间维度分组
        groupByInterval(interval,groupBy);
        sql.append(groupBy);
        return elasticsearchUtil.excute(sql.toString(), SaveModel.class, "", "");
    }
    public String returnSlaveKey(String slaveKey){
        if(StringUtils.isEmpty(slaveKey)){
            return commonParams;
        }
        return slaveKey;
    }
    /**
     * 0级指标查询列表
     * 获取所有指标的增量、到达量
     * 备注:原来接口的一级指标对应现在的
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param interval  1日 2周 3月
     * @param lowLevel  下一级区域等级
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel0BySlaveKey1(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel, String slaveKey1) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        startDate = changeDateTime(startDate);
        endDate = changeDateTime(endDate);
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        sqlGroupBySlaveKey(sql,groupBy,low_level,slaveKey1,"slaveKey1","slaveKey1Name");
        sqlArea(sql,area,level,index,timeLevel,startDate,endDate);
        sqlSlaveKey(slaveKey1,"slaveKey1",sql);
        //根据时间维度分组
        groupByInterval(interval,groupBy);
        sql.append(groupBy);
        return elasticsearchUtil.excute(sql.toString(), SaveModel.class, "", "");
    }
    public List<SaveModel> findDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String interval, String lowLevel) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        startDate = changeDateTime(startDate);
        endDate = changeDateTime(endDate);
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        sqlGroupBySlaveKey(sql,groupBy,low_level,slaveKey1,"slaveKey1","slaveKey1Name");
        sqlArea(sql,area,level,index,timeLevel,startDate,endDate);
        sqlSlaveKey(slaveKey1,"slaveKey1",sql);
        //根据时间维度分组
        groupByInterval(interval,groupBy);
        sql.append(groupBy);
        return elasticsearchUtil.excute(sql.toString(), SaveModel.class, "", "");
    }
    public List<Map<String, Object>> getDataList(int level,String area,String startDate,String endDate,String quota){
        startDate = getStartDate(startDate, endDate);
        StringBuffer initalStr = new StringBuffer(" where quotaDate >= '" + startDate + "T00:00:00+0800'" + " and quotaDate <= '" + endDate + "T23:59:59+0800'");
        sqlArea(initalStr,area,level,false);
        String ddlOrZl = getDDLOrZL(startDate, endDate);
        String quotaCodeAndWhere = quota.substring(quota.indexOf("quotaCode="));
        String filter = "";
        String quotaCode = "";
        if(quotaCodeAndWhere.contains("-")){
            quotaCode = quotaCodeAndWhere.split("-")[0];
            filter = " and " + quotaCodeAndWhere.split("-")[1];
        }else {
            quotaCode = quotaCodeAndWhere;
        }
        filter += " and " + quotaCode +" and timeLevel = '"+ddlOrZl+"'  and areaLevel='5'";
        String sql="";
        if(level == 3){
            sql = "select sum(result1) result,hospital,hospitalName from  " + esIndex + initalStr.toString() + filter + " group by hospital,hospitalName";
        }else if(level == 2){
            sql = "select sum(result1) result,town,townName from  " + esIndex + initalStr.toString() + filter + " group by town,townName";
        }else{
            sql = "select sum(result1) result,team,teamName from  " + esIndex + initalStr.toString() + filter + " group by team,teamName";
        }
        List<Map<String, Object>> dataList = elasticsearchUtil.excuteDataModel(sql);
        return dataList;
//        teamList = dataListIntegration(totalMap,teamList,dataList,quotaName,range);
    }
    public  List<Map<String, Object>> dataListIntegration( Map<String, Object> totalMap,List<Map<String, Object>>  teamList
            ,List<Map<String, Object>>  dataList,String quotaName,int level){
        DecimalFormat df = new DecimalFormat("###");
        Double total=0.00;
        List<Map<String, Object>>  resultList=new ArrayList<>();
        String teamCloumn = "";
        for(Map<String, Object> teamMap : teamList){
            String teamId;
            if(level == 3){
                teamId = teamMap.get("code").toString();
                teamCloumn = "hospital";
            }else if(level == 2) {
                teamId = teamMap.get("town").toString();
                teamCloumn = "town";
            }else{
                teamId = teamMap.get("id").toString();
                teamCloumn = "team";
            }
            boolean exit = false;
            if(dataList != null && dataList.size() > 0){
                for(Map<String, Object> dataMap : dataList){
                    if(dataMap.get(teamCloumn)!= null && dataMap.get(teamCloumn).toString().equals(teamId)){
                        if(dataMap.get("result") != null){
                            String result = df.format(Double.valueOf(dataMap.get("result").toString()));
                            total=total+Double.valueOf(dataMap.get("result").toString());
                            teamMap.put(quotaName,result);
                            exit = true;
                            break;
                        }else if(dataMap.get("count") != null){
                            String result = df.format(Double.valueOf(dataMap.get("count").toString()));
                            total=total+Double.valueOf(dataMap.get("count").toString());
                            teamMap.put(quotaName,result);
                            exit = true;
                            break;
                        }
                    }
                }
            }
            if( !exit){
                teamMap.put(quotaName,0);
            }
            resultList.add(teamMap);
        }
        totalMap.put(quotaName,df.format(total));
        return resultList;
    }
    /**************************************************封装的方法 end ********************************************/
}

+ 0 - 42
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/StreamUtil.java

@ -1,42 +0,0 @@
package com.yihu.jw.care.util;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
import java.io.InputStream;
/***
 * @ClassName: StreamUtil
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/1/5 19:40
 */
public class StreamUtil {
    /**
     *   jar包,读取resources配置
     *   /conclusion.mht    :resources下文件路径以及文件名
     * @return
     * @throws IOException
     */
    public static String readResources() throws IOException {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("/conclusion.mht");
        Resource resource = resources[0];
//获得文件流,因为在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流
        InputStream stream = resource.getInputStream();
        StringBuilder buffer = new StringBuilder();
        byte[] bytes = new byte[1024];
        try {
            for (int n; (n = stream.read(bytes)) != -1; ) {
                buffer.append(new String(bytes, 0, n));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
}