Browse Source

代码修改

LAPTOP-KB9HII50\70708 1 year ago
parent
commit
8632b8a516
15 changed files with 1113 additions and 22 deletions
  1. 2 0
      business/base-service/src/main/java/com/yihu/jw/article/service/BaseMenuManageService.java
  2. 9 3
      business/base-service/src/main/java/com/yihu/jw/article/service/KnowledgeArticleDictService.java
  3. 4 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/PatientDeviceDao.java
  4. 6 4
      business/base-service/src/main/java/com/yihu/jw/knowledge/service/BaseKnowledgeQuestionService.java
  5. 11 0
      common/common-entity/src/db/2024.sql
  6. 11 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceDetail.java
  7. 19 0
      common/common-entity/src/main/java/com/yihu/jw/entity/knowledge/BaseKnowledgeQuestion.java
  8. 8 6
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/article/ArticleDictEndpoint.java
  9. 25 2
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java
  10. 33 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/common/BaseController.java
  11. 304 6
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DeviceController.java
  12. 455 1
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceService.java
  13. 9 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/ExcelData.java
  14. 187 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/QrcodeUtil.java
  15. 30 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/ReadExcelUtil.java

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

@ -19,6 +19,7 @@ import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -824,6 +825,7 @@ public class BaseMenuManageService {
        if(StringUtils.isNotBlank(title)){
            sql += " and a.title like '%"+title+"%'";
        }
        sql += " and a.release_time<='"+ DateUtil.getStringDate() +"'";
        sql += "  order by  a.release_time desc,a.create_time desc limit "+(page-1)*pageSize+","+pageSize;
        list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(KnowledgeArticleDictDO.class));

+ 9 - 3
business/base-service/src/main/java/com/yihu/jw/article/service/KnowledgeArticleDictService.java

@ -9,7 +9,6 @@ import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.menu.BaseMenuDictDO;
import com.yihu.jw.entity.base.patient.BasePatientBusinessDO;
import com.yihu.jw.entity.base.user.UserDO;
import com.yihu.jw.entity.hospital.article.KnowledgeArticleDeptDO;
import com.yihu.jw.entity.hospital.article.KnowledgeArticleDictDO;
import com.yihu.jw.entity.hospital.article.KnowledgeArticleUserDO;
@ -170,13 +169,17 @@ public class KnowledgeArticleDictService extends BaseJpaService<KnowledgeArticle
			knowledgeArticleDO.setUsed(0);
			knowledgeArticleDO.setCollection(0);
			knowledgeArticleDO.setIsUsed(0);
			if(knowledgeArticleDO.getReleaseTime()==null){
				knowledgeArticleDO.setReleaseTime(new Date());
			}
			if(type==1){
				UserDO userDO = userDao.findById(knowledgeArticleDO.getCreateUser()).orElse(null);;
				BaseDoctorDO userDO = doctorDao.findById(knowledgeArticleDO.getCreateUser()).orElse(null);;
				if (userDO!=null){
					knowledgeArticleDO.setCreateUserName(userDO.getName());
				}
			}else {
				UserDO userDO = userDao.findById(knowledgeArticleDO.getCreateUser()).orElse(null);;
				BaseDoctorDO userDO = doctorDao.findById(knowledgeArticleDO.getCreateUser()).orElse(null);;
				if (userDO!=null){
					knowledgeArticleDO.setCreateUserName(userDO.getName());
				}
@ -200,6 +203,9 @@ public class KnowledgeArticleDictService extends BaseJpaService<KnowledgeArticle
			one.setCategorySecond(knowledgeArticleDO.getCategorySecond());
			one.setCategorySecondName(knowledgeArticleDO.getCategorySecondName());
			one.setReleaseTime(knowledgeArticleDO.getReleaseTime());
			if(knowledgeArticleDO.getReleaseTime()==null){
				knowledgeArticleDO.setReleaseTime(new Date());
			}
			one.setStatus(0);
			one.setPuplishType(knowledgeArticleDO.getPuplishType());
			one.setPuplishTypeName(knowledgeArticleDO.getPuplishTypeName());

+ 4 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/PatientDeviceDao.java

@ -1,5 +1,6 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.base.device.PatientHealthStandard;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
@ -17,6 +18,9 @@ public interface PatientDeviceDao extends JpaRepository<DevicePatientDevice, Lon
    @Query("select a from DevicePatientDevice a where a.del = 0 ")
    List<DevicePatientDevice> findByAll();
    @Query("select a from PatientHealthStandard a where a.patient = ?1 and a.type = ?2")
    PatientHealthStandard findByPatientType(String patient, int type);
    @Query("select a from DevicePatientDevice a where a.user = ?1 ")
    List<DevicePatientDevice> findByPatient(String user);

+ 6 - 4
business/base-service/src/main/java/com/yihu/jw/knowledge/service/BaseKnowledgeQuestionService.java

@ -110,14 +110,16 @@ public class BaseKnowledgeQuestionService extends BaseJpaService<BaseKnowledgeQu
        String sql = "SELECT\n" +
                "\tid,\n" +
                "\ttype,\n" +
                "\tquestion_name AS questionName,\n" +
                "\tsimilar_question_name AS similarQuestionName,\n" +
                "\tquestion_name AS \"questionName\",\n" +
                "\tsimilar_question_name AS \"similarQuestionName\",\n" +
                "\tanswer,\n" +
                "\tcreate_user as createUser,\n" +
                "\tcreate_user_name as createUserName,\n" +
                "\tcreate_user as \"createUser\",\n" +
                "\tcreate_user_name as \"createUserName\",\n" +
                "\tstatus,\n" +
                "\tflag,\n" +
                "\ttime,\n" +
                "\tscene_code as \"sceneCode\",\n" +
                "\tscene_name as \"sceneName\",\n" +
                "\tsort\n" +
                "FROM\n" +
                "\tbase_knowledge_question where 1=1 ";

+ 11 - 0
common/common-entity/src/db/2024.sql

@ -16,3 +16,14 @@ INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('article_menu_type2', NULL, 'article_menu_type', '2', '广告', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '文章类型 公告、广告、文章、帮助中心');
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('article_menu_type3', NULL, 'article_menu_type', '3', '文章', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '文章类型 公告、广告、文章、帮助中心');
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('article_menu_type4', NULL, 'article_menu_type', '4', '帮助中心', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '文章类型 公告、广告、文章、帮助中心');
ALTER table wlyy_devices add COLUMN `qrcode` varchar(255) DEFAULT NULL COMMENT '二维码地址';
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('devicePriUrl', NULL, 'devicePriUrl', 'devicePriUrl', 'https://hlw.xmdsyy.cn/hlw/ims-wx/#/healthRecords/deviceBind?SN=', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '设备二维码前缀');
ALTER table base_knowledge_question add COLUMN `scene_code` varchar(50) DEFAULT NULL COMMENT '使用场景编码 逗号间隔';
ALTER table base_knowledge_question add COLUMN `scene_name` varchar(200) DEFAULT NULL COMMENT '使用场景名称 逗号间隔';
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('knowledge_question_scene1', NULL, 'knowledge_question_scene', '1', '在线导诊', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '使用场景');
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('knowledge_question_scene2', NULL, 'knowledge_question_scene', '2', '专属服务导诊', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '使用场景');
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('knowledge_question_scene3', NULL, 'knowledge_question_scene', '3', '在线候诊室', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '使用场景');
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('knowledge_question_scene4', NULL, 'knowledge_question_scene', '4', '在线诊室', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '使用场景');

+ 11 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceDetail.java

@ -57,6 +57,8 @@ public class DeviceDetail extends IdEntity {
    private Long collectNum;//采集数据次数
    private Long abnormalNum;//异常指标数据次数
    private String qrcode;//二维码地址
    //导入设备错误信息
    private String errorMsg;
    private Map<String,String> errorMsgMap = new HashMap<>();
@ -416,4 +418,13 @@ public class DeviceDetail extends IdEntity {
    public void setErrorMsgMap(Map<String, String> errorMsgMap) {
        this.errorMsgMap = errorMsgMap;
    }
    @Column(name = "qrcode")
    public String getQrcode() {
        return qrcode;
    }
    public void setQrcode(String qrcode) {
        this.qrcode = qrcode;
    }
}

+ 19 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/knowledge/BaseKnowledgeQuestion.java

@ -28,6 +28,9 @@ public class BaseKnowledgeQuestion extends UuidIdentityEntityWithOperator {
	private Integer sort;//排序
	private Integer del;//0删除1正常
	private String sceneCode;//使用场景编码 逗号间隔
	private String sceneName;//使用场景名称 逗号间隔
	public Integer getFlag() {
		return flag;
	}
@ -109,4 +112,20 @@ public class BaseKnowledgeQuestion extends UuidIdentityEntityWithOperator {
	public void setDel(Integer del) {
		this.del = del;
	}
	public String getSceneCode() {
		return sceneCode;
	}
	public void setSceneCode(String sceneCode) {
		this.sceneCode = sceneCode;
	}
	public String getSceneName() {
		return sceneName;
	}
	public void setSceneName(String sceneName) {
		this.sceneName = sceneName;
	}
}

+ 8 - 6
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/article/ArticleDictEndpoint.java

@ -15,6 +15,7 @@ import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.util.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@ -65,10 +66,10 @@ public class ArticleDictEndpoint extends EnvelopRestEndpoint {
		try {
			String userId=getUID();
			BaseDoctorRoleDO roleDO = doctorRoleDao.findByDoctorCodeAndRoleCode(userId, CommonContant.DR_ARTICLEREVIEWER);
			boolean queryAll=false;
			if (roleDO!=null){
				queryAll=true;
			}
			boolean queryAll=true;
//			if (roleDO!=null){
//				queryAll=true;
//			}
			if (queryAll){
				if(StringUtils.isBlank(filters)){
					filters=filters+"del=1";
@ -226,10 +227,11 @@ public class ArticleDictEndpoint extends EnvelopRestEndpoint {
			@RequestParam(value = "pageSize", required = true,defaultValue = "10")Integer pageSize)throws Exception{
		try {
			String now = DateUtil.getStringDate();
			if(StringUtils.isBlank(filters)){
				filters=filters+"del=1;type=2;status=1";
				filters=filters+"del=1;type=2;status=1;releaseTime<="+now;
			}else{
				filters=filters+";del=1;type=2;status=1";
				filters=filters+";del=1;type=2;status=1;releaseTime<="+now;
			}
			List<KnowledgeArticleDictDO> list  = knowledgeArticleDictService.search(fields,filters,sorts,page,pageSize);
			List<KnowledgeArticleDictDO> totals  = knowledgeArticleDictService.search(fields,filters,sorts);

+ 25 - 2
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java

@ -874,6 +874,29 @@ public class PatientConsultEndpoint extends EnvelopRestEndpoint {
        }
    }
    @PostMapping(value = "robotWelcome")
    @ApiOperation(value = "居民导诊欢迎语", notes = "居民导诊欢迎语")
    public Envelop robotWelcome(
            @ApiParam(name = "sender_id", value = "居民id", defaultValue = "")
            @RequestParam(value = "sender_id", required = true) String sender_id,
            @ApiParam(name = "session_id", value = "session_id", defaultValue = "")
            @RequestParam(value = "session_id", required = false) String session_id,
            @ApiParam(name = "type", value = "咨询type", defaultValue = "")
            @RequestParam(value = "type", required = false) String type
    ) {
        try {
            if(imUtil.sessionIsExist(session_id)){
                return Envelop.getSuccess("success");
            }
            Map<String, JSONObject> map = robotService.robotReply(session_id, type, null);
            imService.getPatientGuaidenceConsult(sender_id, session_id, type);
            robotService.sendReplyMap(map);
            return Envelop.getSuccess("success");
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @PostMapping(value = BaseHospitalRequestMapping.PatientIM.patientGuaidenceAppend)
    @ApiOperation(value = "居民导诊会话发送消息", notes = "居民导诊会话发送消息")
    public Envelop patientGuaidenceAppend(
@ -939,10 +962,10 @@ public class PatientConsultEndpoint extends EnvelopRestEndpoint {
                }
            }
            content = StringUtils.isNotEmpty(content) ? content.trim() : content;
            Map<String, JSONObject> map = robotService.robotReply(session_id, type, content);
//            Map<String, JSONObject> map = robotService.robotReply(session_id, type, content);
            session_id = imService.getPatientGuaidenceConsult(sender_id, session_id, type);
            String result = imService.patientGuaidenceAppend(sender_id, sender_name, session_id, content_type, content, "1", extend);
            robotService.sendReplyMap(map);
//            robotService.sendReplyMap(map);
            //消息存在时文本及问题集类型发送时自动回复
            robotService.replyGuaidenceContent(session_id, type, content, content_type, "1", extend);
            List<BaseDoctorRoleDO> doctorRoleDOS = doctorRoleDao.findByRoleCode("guidance");

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

@ -530,6 +530,39 @@ public class BaseController {
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回表格列表数据
     * @param code 状态码:0成功,非0失败
     * @param errorMsg 错误消息
     * @param page 当前页码
     * @param rows 分页大小
     * @param list 查询的结果集
     * @return
     */
    public String write(int code, String errorMsg, int page, int rows, Page<?> list) {
        try {
            JSONObject object = new JSONObject();
            ObjectMapper mapper = new ObjectMapper();
            object.put("successFlg", code == 0);
            object.put("errorMsg", errorMsg);
            // 是否为第一页
            object.put("errorCode", code);
            // 是否为最后一页
            object.put("currPage", page);
            // 分页大小
            object.put("pageSize", rows);
            // 总条数
            object.put("totalCount", list.getTotalElements());
            // 总页数
            object.put("totalPage", list.getTotalPages());
            // 结果集
            object.put("detailModelList", list.getContent());
            return object.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果

+ 304 - 6
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DeviceController.java

@ -1,28 +1,51 @@
package com.yihu.jw.hospital.module.health.controller;
import com.yihu.jw.device.dao.DeviceDetailDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceCategory;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.health.service.DeviceDetailService;
import com.yihu.jw.hospital.module.health.service.DeviceService;
import com.yihu.jw.hospital.module.health.service.PatientDeviceLogService;
import com.yihu.jw.hospital.module.health.service.PatientDeviceService;
import com.yihu.jw.hospital.utils.QrcodeUtil;
import com.yihu.jw.restmodel.iot.device.WlyyPatientDeviceVO;
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.PageEnvelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jxl.Workbook;
import jxl.write.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
@RestController
@RequestMapping(value = "/common/device", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RequestMapping(value = "/common/device")
@Api(description = "设备管理")
public class DeviceController extends BaseController {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private PatientDeviceService patientDeviceService;
    @Autowired
    private DeviceDetailService deviceDetailService;
    @Autowired
    private PatientDeviceLogService patientDeviceLogService;
    @ApiOperation("获取设备分类")
    @RequestMapping(value = "DeviceCategory", method = {RequestMethod.POST, RequestMethod.GET})
@ -62,4 +85,279 @@ public class DeviceController extends BaseController {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    @Autowired
    private QrcodeUtil qrcodeUtil;
    @ApiOperation("生成设备的小程序二维码")
    @PostMapping(value = "setQrcode")
    public Envelop setQrcode(@ApiParam(name = "id", value = "设备ID", defaultValue = "19")
                            @RequestParam(value = "id", required = true) Long id) {
        try {
            DeviceDetail device = deviceDetailDao.findById(id).orElse(null);
            if(device!=null){
                qrcodeUtil.makeDeviceXcxQrcode(device,null,true);
                deviceDetailDao.save(device);
            }
            return ObjEnvelop.getSuccess("操作成功",device.getQrcode());
        } catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
    //导出设备报表
    @GetMapping(value="exportExcel/toExcel")
    public void exportList(
            @RequestParam(value = "deviceName",required = false)String deviceName,
            @RequestParam(value = "deviceCode",required = false) String deviceCode,
            @RequestParam(value = "linkman",required = false) String linkman,
            HttpServletResponse response){
        try {
            List<DeviceDetail> wlyyDevices = deviceService.exporthDeviceList(deviceName,deviceCode,linkman);
            response.setContentType("octets/stream");
            response.setHeader("Content-Disposition", "attachment; filename="+ new String( "deviceDataList.xls"));
            OutputStream os = response.getOutputStream();
            this.write(os,wlyyDevices);
        }catch (Exception ex){
            error(ex);
        }
    }
    //导入设备报表
    @PostMapping(value = "importData")
    public Envelop importData(HttpServletRequest request) {
        try {
            request.setCharacterEncoding("UTF-8");
            InputStream inputStream = request.getInputStream();
            Workbook workbook = Workbook.getWorkbook(inputStream);
            deviceService.importData(workbook);
            return Envelop.getSuccess("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
    public void addHeader(WritableSheet ws) throws WriteException {
        String[] header = {"设备名称","设备型号","SN码", "SIM卡号", "厂家名称", "厂家地址","法人", "联系人", "联系电话"};
        int i = 0;
        for (String h : header) {
            addCell(ws, 0, i, h);//表名,行,列,header
            i++;
        }
    }
    public void write(WritableWorkbook wwb, List ls) throws Exception {
        try {
            WritableSheet ws;
            ws = wwb.createSheet("sheet",1);
            addHeader(ws);
            int i = 1;
            for (DeviceDetail m : (List<DeviceDetail>) ls) {
                addCell(ws, i, 0, m.getDeviceName(),"");
                addCell(ws, i, 1, m.getDeviceModel(),"");
                addCell(ws, i, 2, m.getDeviceCode(),"");
                addCell(ws, i, 3, m.getSim(),"");
                addCell(ws, i, 4, m.getManufacturer(),"");
                addCell(ws, i, 5, m.getAddress(),"");
                addCell(ws, i, 6, m.getRepresentative(),"");
                addCell(ws, i, 7, m.getLinkman(),"");
                addCell(ws, i, 8, m.getTel(),"");
                i++;
            }
            wwb.write();
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (wwb != null) wwb.close();
            throw e;
        }
    }
    public void write(OutputStream os, List ls) throws Exception{
        write(Workbook.createWorkbook(os), ls);
    }
    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column, String data) throws WriteException {
        Label label = new Label(column ,row, data);
        ws.addCell(label);
    }
    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column, String data, String memo) throws WriteException {
        if("null".equals(data)){
            data = "";
        }
        Label label = new Label(column ,row, data);
        if(!org.springframework.util.StringUtils.isEmpty(memo)){
            WritableCellFeatures cellFeatures = new WritableCellFeatures();
            cellFeatures.setComment(memo);
            label.setCellFeatures(cellFeatures);
        }
        ws.addCell(label);
    }
    //列表查询
    @GetMapping(value="deviceList")
    public Envelop searchList(
            @RequestParam(value = "deviceName",required = false)String deviceName,
            @RequestParam(value = "deviceCode",required = false) String deviceCode,
            @RequestParam(value = "linkman",required = false) String linkman,
            @RequestParam(value = "page",required = false)Integer page,
            @RequestParam(value = "pageSize",required = false)Integer pageSize){
        try {
            return deviceService.searchDeviceList(deviceName,deviceCode,linkman, page, pageSize);
        }catch (Exception ex){
            ex.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
    //设备型号列表
    @GetMapping(value = "modelList")
    public Envelop findAll(){
        try{
            List<Device> list = deviceService.findAll();
            return ListEnvelop.getSuccess("操作成功",list);
        }catch (Exception ex){
            ex.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
    @GetMapping(value = "device")
    public Envelop getDevice(@RequestParam(value = "id") Long id){
        try {
            DeviceDetail device = deviceDetailDao.findById(id).orElse(null);
            return ObjEnvelop.getSuccess("操作成功",device);
        }catch (Exception ex){
            ex.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
    @PostMapping(value = "create")
    public Envelop createDevice(String jsonData){
        try{
            DeviceDetail device = objectMapper.readValue(jsonData, DeviceDetail.class);
            DeviceDetail deviceNew = deviceService.createDevice(device);
            return ObjEnvelop.getSuccess("操作成功",deviceNew);
        }catch (Exception ex){
            ex.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
    @PostMapping(value = "update")
    public Envelop updateDevice(String jsonData){
        try{
            DeviceDetail device = objectMapper.readValue(jsonData, DeviceDetail.class);
            DeviceDetail deviceNew = deviceService.updateDevice(device);
            return ObjEnvelop.getSuccess("操作成功",deviceNew);
        }catch (Exception ex){
            ex.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
    @PostMapping(value = "updateStatus")
    public Envelop updateStatus(String jsonData){
        try{
            DeviceDetail device = objectMapper.readValue(jsonData, DeviceDetail.class);
            DeviceDetail deviceNew = deviceService.updateDevice(device);
            return ObjEnvelop.getSuccess("操作成功",deviceNew);
        }catch (Exception ex){
            ex.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
    @PostMapping(value = "delete")
    public Envelop deleteDevice(Long id){
        try{
            deviceService.deleteDevice(id);
            return Envelop.getSuccess("操作成功!");
        }catch (Exception ex){
            ex.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
    @GetMapping(value = "isCodeExist")
    public Envelop isCodeExist(String deviceCode) {
        try {
            return ObjEnvelop.getSuccess("",deviceService.existDeviceCode(deviceCode));
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
    @GetMapping(value ="healthIndexlist")
    public Envelop healthIndexlist(
            @RequestParam(value = "deviceSn",required = false) String deviceSn,
            @RequestParam(value = "date",required = false) String date,
            @RequestParam(value = "idcard",required = false) String idcard,
            @RequestParam(value = "userName",required = false) String userName,
            @RequestParam(value = "indexType",required = false) String indexType,
            @RequestParam(value = "indexTypeMin1",required = false) Double indexTypeMin1,
            @RequestParam(value = "indexTypeMax1",required = false) Double indexTypeMax1,
            @RequestParam(value = "indexTypeMin2",required = false) Double indexTypeMin2,
            @RequestParam(value = "indexTypeMax2",required = false) Double indexTypeMax2,
            @RequestParam(value = "page",required = false) Integer page,
            @RequestParam(value = "pageSize",required = false) Integer pageSize){
        try{
            return deviceService.healthIndexlist(deviceSn,date, idcard, userName, indexType,page, pageSize,indexTypeMin1, indexTypeMax1, indexTypeMin2,indexTypeMax2);
        }catch (Exception ex){
            ex.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
    @GetMapping(value = "patientDeviceList")
    public Envelop patientDeviceList(
            @RequestParam(value = "deviceName",required = false) String deviceName,
            @RequestParam(value = "categoryCode",required = false) String categoryCode,
            @RequestParam(value = "deviceSn",required = false) String deviceSn,
            @RequestParam(value = "userName",required = false) String userName,
            @RequestParam(value = "page") Integer page,
            @RequestParam(value = "pageSize") Integer pageSize){
        try {
            List<WlyyPatientDeviceVO> patientDevices = deviceService.patientDeviceList(deviceName,categoryCode, deviceSn, userName, page, pageSize);
            Long totalcount = deviceService.patientDeviceListCount(deviceName,categoryCode, deviceSn, userName);
            return PageEnvelop.getSuccessListWithPage("操作成功",patientDevices,page,pageSize,totalcount);
        }catch (Exception ex){
            ex.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
    //设备解绑(记录删除)
    @PostMapping(value = "deletePatientDevice")
    public Envelop deletePatientDevice(@RequestParam(value = "id") String id){
        try {
            if(id == null){
                return Envelop.getError("id不能为空!");
            }
            DevicePatientDevice wlyyPatientDevice = patientDeviceService.findById(id);
            if(id == null){
                return Envelop.getError("设备不存在!");
            }
            patientDeviceService.deleteDevice(id,null);
            String deviceSn = "";
            if (wlyyPatientDevice!=null){
                deviceSn = wlyyPatientDevice.getDeviceSn();
            }
            //全部解绑后去判断就更新设备表中是否绑定字段.
            deviceDetailService.unBindUpdateIsBinding(deviceSn);
            patientDeviceLogService.savePatientDeviceLog(wlyyPatientDevice,deviceSn,3,2);
            return Envelop.getSuccess("操作成功");
        }catch (Exception ex){
            ex.printStackTrace();
            return Envelop.getError("操作失败!");
        }
    }
}

+ 455 - 1
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceService.java

@ -2,13 +2,34 @@ package com.yihu.jw.hospital.module.health.service;
import com.yihu.jw.device.dao.DeviceCategoryDao;
import com.yihu.jw.device.dao.DeviceDao;
import com.yihu.jw.device.dao.DeviceDetailDao;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.entity.base.device.PatientHealthStandard;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceCategory;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.hospital.utils.ExcelData;
import com.yihu.jw.hospital.utils.QrcodeUtil;
import com.yihu.jw.hospital.utils.ReadExcelUtil;
import com.yihu.jw.restmodel.iot.device.DeviceHealthIndexVO;
import com.yihu.jw.restmodel.iot.device.WlyyPatientDeviceVO;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.util.date.DateTimeUtil;
import com.yihu.jw.util.date.DateUtil;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import java.util.List;
import java.util.*;
/**
 * 设备管理
@ -17,13 +38,441 @@ import java.util.List;
@Transactional(rollbackFor = Exception.class)
public class DeviceService {
	// 血糖餐前最小值
	public static final double HEALTH_STANDARD_ST_MIN_BEFORE = 4;//3.9
	// 血糖餐前最大值
	public static final double HEALTH_STANDARD_ST_MAX_BEFORE = 7;//6.1
	// 血糖餐后最小值
	public static final double HEALTH_STANDARD_ST_MIN_AFTER = 4;//4.4
	// 血糖餐后最大值
	public static final double HEALTH_STANDARD_ST_MAX_AFTER = 11.1;//7.8
	// 舒张压最小值
	public static final double HEALTH_STANDARD_SZY_MIN = 60;//60
	// 舒张压最大值
	public static final double HEALTH_STANDARD_SZY_MAX = 90;//89
	// 收缩压最小值
	public static final double HEALTH_STANDARD_SSY_MIN = 90;//90
	// 收缩压最大值
	public static final double HEALTH_STANDARD_SSY_MAX = 140;//139
	@Autowired
	private DeviceCategoryDao deviceCategoryDao;
	@Autowired
	private DeviceDao deviceDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private PatientDeviceDao wlyyPatientDeviceDao;
	@Autowired
	private DeviceDetailDao deviceDetailDao;
	@Autowired
	private QrcodeUtil qrcodeUtil;
	public boolean importData(Workbook workbook) {
		Sheet[] sheets = workbook.getSheets();
		Sheet sheet = sheets[0];
		int rows = ReadExcelUtil.getRightRows(sheet);
		List<DeviceDetail> deviceList = new ArrayList<>();
		for (int row = 1; row < rows; row++) {  //索引从0开始,第一行为标题
			DeviceDetail device = new DeviceDetail();
			Map<Integer, ExcelData> mapping = mappingDevice(device);
			int finalRow = row;
			mapping.forEach((index, excelData) -> {
				String value = sheet.getCell(index, finalRow).getContents().trim();
				excelData.transform(value);
			});
			device.setIsGrant(0);
			device.setIsBinding(0);
			//判断设备是否导入
			List<DeviceDetail> wlyyDevice = deviceDetailDao.findByDeviceCode(device.getDeviceCode());
			if(wlyyDevice.size()>0) {
				device.setId(wlyyDevice.get(0).getId());
			}
			qrcodeUtil.makeDeviceXcxQrcode(device,null,false);
			deviceList.add(device);
		}
		deviceDetailDao.saveAll(deviceList);
		return true;
	}
	private Map<Integer, ExcelData> mappingDevice(DeviceDetail device) {
		Map<Integer, ExcelData> dataMap = new HashMap<>();
		//设备名称
		dataMap.put(0, new ExcelData() {
			@Override
			public void transform(String data) {
				device.setDeviceName(data);
			}
		});
		//设备型号
		dataMap.put(1, new ExcelData() {
			@Override
			public void transform(String data) {
				device.setDeviceModel(data);
				Device dmDevice = deviceDao.findByModel(device.getDeviceModel());
				if(dmDevice != null) {
					if(dmDevice.getIsMultiUser().equals("1")) {
						device.setBindingCount("{\"1\":\"0\", \"2\":\"0\"}");
					}else if(dmDevice.getIsMultiUser().equals("0")) {
						device.setBindingCount("{\"1\":\"0\"}");
					}
				}
			}
		});
		//设备唯一标识 sn
		dataMap.put(2, new ExcelData() {
			@Override
			public void transform(String data) {
				device.setDeviceCode(data);
			}
		});
		//SIM卡号
		dataMap.put(3, new ExcelData() {
			@Override
			public void transform(String data) {
				device.setSim(data);
			}
		});
		//厂商名称
		dataMap.put(4, new ExcelData() {
			@Override
			public void transform(String data) {
				device.setManufacturer(data);
			}
		});
		//厂商地址
		dataMap.put(5, new ExcelData() {
			@Override
			public void transform(String data) {
				device.setAddress(data);
			}
		});
		//法人代表
		dataMap.put(6, new ExcelData() {
			@Override
			public void transform(String data) {
				device.setRepresentative(data);
			}
		});
		//联系人
		dataMap.put(7, new ExcelData() {
			@Override
			public void transform(String data) {
				device.setLinkman(data);
			}
		});
		//联系电话
		dataMap.put(8, new ExcelData() {
			@Override
			public void transform(String data) {
				device.setTel(data);
			}
		});
		return dataMap;
	}
	public List<DeviceDetail> exporthDeviceList(String deviceName, String deviceCode, String linkman){
		Map<String,SearchFilter> filter = new HashMap<>();
		if(!StringUtils.isEmpty(deviceCode)){
			filter.put("deviceCode",new SearchFilter("deviceCode",SearchFilter.Operator.LIKE,deviceCode));
		}
		if(!StringUtils.isEmpty(deviceName)){
			filter.put("deviceName",new SearchFilter("deviceName",SearchFilter.Operator.LIKE,deviceName));
		}
		if(!StringUtils.isEmpty(linkman)){
			filter.put("linkman",new SearchFilter("linkman",SearchFilter.Operator.LIKE,linkman));
		}
		Specification<DeviceDetail> spec = DynamicSpecifications.bySearchFilter(filter.values(), DeviceDetail.class);
		return deviceDetailDao.findAll(spec);
	}
	public PageEnvelop searchDeviceList(String deviceName,String deviceCode,String linkman,Integer page,Integer pageSize){
		if(page == null){
			page = 1;
		}
		if(pageSize == null){
			pageSize = 15;
		}
		String sql = "select * ";
		String countSql = "select count(*) ";
		String filter = "from wlyy_devices where 1=1 ";
		if(StringUtils.isNotBlank(deviceCode)){
			filter += " and device_code like '%"+deviceCode+"%'";
		}
		if(StringUtils.isNotBlank(deviceName)){
			filter += " and device_name like '%"+deviceName+"%'";
		}
		if(StringUtils.isNotBlank(linkman)){
			filter += " and linkman like '%"+linkman+"%'";
		}
		String orderBy = " limit "+(page-1)*pageSize+","+pageSize;
		List<DeviceDetail> list = jdbcTemplate.query(sql+filter+orderBy,new BeanPropertyRowMapper<>(DeviceDetail.class));
		Long count = jdbcTemplate.queryForObject(countSql+filter,Long.class);
		return PageEnvelop.getSuccessListWithPage("查询成功",list,page,pageSize,count);
	}
	@Transactional
	public DeviceDetail createDevice(DeviceDetail device){
		device.setApplyDate(DateUtil.getStringDate());
//		String manufacturerCode = deviceManufacturerDao.getManufacturerCodeByCode(device.getManufacturerId());
//		device.setManufacturerCode(manufacturerCode);
		//根据型号设置绑定次数形式
		if(device.getDeviceModel() != null) {
			Device dmDevice = deviceDao.findByModel(device.getDeviceModel());
			if(dmDevice == null) {
				if(device.getDeviceName().contains("血糖")) {
					device.setBindingCount("{\"1\":\"0\"}");
				}else if(device.getDeviceName().contains("血压")) {
					device.setBindingCount("{\"1\":\"0\", \"2\":\"0\"}");
				}
			}else {
				if(dmDevice.getIsMultiUser().equals("1")) {
					device.setBindingCount("{\"1\":\"0\", \"2\":\"0\"}");
				}else if(dmDevice.getIsMultiUser().equals("0")) {
					device.setBindingCount("{\"1\":\"0\"}");
				}
			}
		}
		qrcodeUtil.makeDeviceXcxQrcode(device,null,false);
		device.setIsGrant(0);
		device.setIsBinding(0);
		DeviceDetail deviceNew = deviceDetailDao.save(device);
		return deviceNew;
	}
	@Transactional
	public DeviceDetail updateDevice(DeviceDetail device){
		DeviceDetail deviceNew = deviceDetailDao.findById(device.getId()).orElse(null);
		if(deviceNew == null){
			return null;
		}
//		deviceNew.setManufacturerCode(manufacturerCode);
		deviceNew.setOrgName(device.getOrgName());
		deviceNew.setLinkman(device.getLinkman());
		deviceNew.setTel(device.getTel());
		deviceNew.setServerIp(device.getServerIp());
		deviceNew.setDeviceName(device.getDeviceName());
		deviceNew.setDeviceModel(device.getDeviceModel());
		deviceNew.setDeviceCode(device.getDeviceCode());
		deviceNew.setManufacturerId(device.getManufacturerId());
		deviceNew.setManufacturer(device.getManufacturer());
		deviceNew.setAddress(device.getAddress());
		deviceNew.setRepresentative(device.getRepresentative());
		deviceNew.setApplicantName(device.getApplicantName());
		deviceNew.setApplicantIdentity(device.getApplicantIdentity());
		deviceNew.setApplicantTel(device.getApplicantTel());
		deviceNew.setApplicantMail(device.getApplicantMail());
		deviceNew.setSim(device.getSim());
		return deviceDetailDao.save(deviceNew);
	}
	@Transactional
	public boolean deleteDevice(Long id){
		deviceDetailDao.deleteById(id);
		return true;
	}
	public boolean existDeviceCode(String deviceCode){
		List<DeviceDetail> device = deviceDetailDao.findByDeviceCode(deviceCode);
		return device.size()>0;
	}
	/*=
	 * 根据社区或者医生名称查找居民设备绑定详情
	 */
	public List<WlyyPatientDeviceVO> patientDeviceList(String deviceName,
												   String categoryCode,
												   String deviceSn,
												   String userName,
												   Integer page, Integer pageSize) {
		List<WlyyPatientDeviceVO> list = new ArrayList<>();
		String sql = "SELECT d.id as id,d.device_id as deviceId,d.user as user,p.name as userName,d.category_code as categoryCode,d.device_name as deviceName," +
				"d.device_sn as deviceSn,d.sim as sim,d.user_type as userType,p.mobile," +
				"CONCAT(LEFT (p.idcard,6),'**********',RIGHT (p.idcard,2)) userIdcard,d.czrq as czrq " +
				"FROM wlyy_patient_device d,base_patient p " +
				"WHERE d.`user`=p.id ";
		if(StringUtils.isNotBlank(userName)){
			sql = sql + "AND p.name like '%"+userName+"%' ";
		}
		if(StringUtils.isNotBlank(deviceSn)){
			sql = sql + "AND d.device_sn like '%"+deviceSn+"%' ";
		}
		if(StringUtils.isNotBlank(categoryCode)){
			sql = sql + "AND d.category_code like '%"+categoryCode+"%' ";
		}
		if(StringUtils.isNotBlank(deviceName)){
			sql = sql + "AND d.device_name like '%"+deviceName+"%' ";
		}
		sql = sql+"ORDER BY czrq DESC limit " + (page-1)*pageSize+", "+pageSize;
		list =  jdbcTemplate.query(sql,new BeanPropertyRowMapper(WlyyPatientDeviceVO.class));
		return list ;
	}
	public Long patientDeviceListCount(String deviceName, String categoryCode, String deviceSn, String userName) {
		String sql  = "SELECT count(d.id) " +
				"FROM " +
				" wlyy_patient_device d," +
				" base_patient p " +
				"WHERE d.`user`=p.id ";
		if(StringUtils.isNotBlank(userName)){
			sql = sql + "AND p.name like '%"+userName+"%' ";
		}
		if(StringUtils.isNotBlank(deviceSn)){
			sql = sql + "AND d.device_sn like '%"+deviceSn+"%' ";
		}
		if(StringUtils.isNotBlank(categoryCode)){
			sql = sql + "AND d.category_code like '%"+categoryCode+"%' ";
		}
		if(StringUtils.isNotBlank(deviceName)){
			sql = sql + "AND d.device_name like '%"+deviceName+"%' ";
		}
		Long total = jdbcTemplate.queryForObject(sql, Long.class);
		return total ;
	}
	public PageEnvelop healthIndexlist(String deviceSn, String date, String idcard, String userName, String indexType, Integer page, Integer pageSize,
									   Double indexTypeMin1, Double indexTypeMax1, Double indexTypeMin2, Double indexTypeMax2)throws Exception{
		if (page == null){
			page = 1;
		}
		if(pageSize == null){
			pageSize = 15;
		}
		StringBuilder filter = new StringBuilder();
		String sql =" SELECT i.* ,s.name userName FROM wlyy_patient_health_index i JOIN base_patient s ON i.user=s.id ";
		String countSql =" SELECT count(1) as num FROM wlyy_patient_health_index i JOIN base_patient s ON i.user=s.id ";
		sql += " WHERE 1=1 ";
		countSql += " WHERE 1=1 ";
		//根据患者名称过滤
		if(!StringUtils.isEmpty(userName)){
			filter.append(" AND s.name LIKE '%"+userName+"%' ");
		}
		if(!StringUtils.isEmpty(deviceSn)){
			filter.append(" and i.device_sn like '%"+deviceSn+"%' ");
		}
		if(!StringUtils.isEmpty(idcard)){
			filter.append(" and i.idcard like '%"+idcard+"%' ");
		}
		//体征数据创建时间
		if(!StringUtils.isEmpty(date)){
			Date startTimeTemp  =  DateTimeUtil.simpleDateParse(date);
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(startTimeTemp);
			calendar.set(Calendar.HOUR,23);
			calendar.set(Calendar.MINUTE,59);
			calendar.set(Calendar.SECOND,59);
			calendar.set(Calendar.MILLISECOND,999);
			Date endTimeTemp = calendar.getTime();
			filter.append(" and i.czrq>='" + DateTimeUtil.simpleDateTimeFormat(startTimeTemp)+"'");
			filter.append(" and i.czrq<='" + DateTimeUtil.simpleDateTimeFormat(endTimeTemp)+"'");
		}
		//指标类型
		if(!StringUtils.isEmpty(indexType)){
			filter.append(" and i.type="+indexType);
		}
		//体征数据
		if(indexTypeMin1!=null){
			filter.append(" and value1>="+indexTypeMin1);
		}
		if(indexTypeMax1!=null){
			filter.append(" and value1<="+indexTypeMax1);
		}
		if(indexTypeMin2!=null){
			filter.append(" and value2>="+indexTypeMin2);
		}
		if(indexTypeMax2!=null){
			filter.append(" and value2<="+indexTypeMax2);
		}
		String f = filter.toString();
		List<DeviceHealthIndexVO> resultList = jdbcTemplate.query(sql+f+" order by i.czrq desc "+" limit "+(page-1)*pageSize+","+pageSize,new BeanPropertyRowMapper<>(DeviceHealthIndexVO.class));
		if(resultList.size()<=0){
			return PageEnvelop.getSuccessListWithPage("",resultList,page,pageSize,0L);
		}
		for (DeviceHealthIndexVO indexVO:resultList){
			indexVO.setHealthStandard(gethealthStandard(indexVO.getType(),indexVO.getUser()).toString());
		}
		long count = jdbcTemplate.queryForObject(countSql+filter.toString(),Long.class);
		String regex = "(\\w{3})(\\w+)(\\w{3})";
		return PageEnvelop.getSuccessListWithPage("",resultList,page,pageSize,count);
	}
	public JSONObject gethealthStandard(Integer type, String patientCode) {
		//血糖校验
		JSONObject json = new JSONObject();
		if (type == 1) {
			// 血糖记录,查询患者血糖预警值
			PatientHealthStandard standard = wlyyPatientDeviceDao.findByPatientType(patientCode, 1);
			Double maxValueBefore = HEALTH_STANDARD_ST_MAX_BEFORE;
			Double minValueBefore = HEALTH_STANDARD_ST_MIN_BEFORE;
			Double maxValueAfter = HEALTH_STANDARD_ST_MAX_AFTER;
			Double minValueAfter = HEALTH_STANDARD_ST_MIN_AFTER;
			if (standard != null) {
				if (standard.getMaxValue1() > 0) {
					maxValueBefore = standard.getMaxValue1();
				}
				if (standard.getMinValue1() > 0) {
					minValueBefore = standard.getMinValue1();
				}
				if (standard.getMaxValue2() > 0) {
					maxValueAfter = standard.getMaxValue2();
				}
				if (standard.getMinValue2() > 0) {
					minValueAfter = standard.getMinValue2();
				}
			}
			json.put("maxValueAfter", maxValueAfter);
			json.put("maxValueBefore", maxValueBefore);
			json.put("minValueBefore", minValueBefore);
			json.put("minValueAfter", minValueAfter);
		}
		//血压校验
		else if (type == 2) {
			// 血压记录,查询患者血压预警值
			PatientHealthStandard standard = wlyyPatientDeviceDao.findByPatientType(patientCode, 2);
			Double maxValueSSY = HEALTH_STANDARD_SSY_MAX;
			Double minValueSSY = HEALTH_STANDARD_SSY_MIN;
			Double maxValueSZY = HEALTH_STANDARD_SZY_MAX;
			Double minValueSZY = HEALTH_STANDARD_SZY_MIN;
			if (standard != null) {
				if (standard.getMaxValue1() > 0) {
					maxValueSSY = standard.getMaxValue1();
				}
				if (standard.getMinValue1() > 0) {
					minValueSSY = standard.getMinValue1();
				}
				if (standard.getMaxValue2() > 0) {
					maxValueSZY = standard.getMaxValue2();
				}
				if (standard.getMinValue2() > 0) {
					minValueSZY = standard.getMinValue2();
				}
			}
			json.put("minValueSZY", minValueSZY);
			json.put("maxValueSZY", maxValueSZY);
			json.put("minValueSSY", minValueSSY);
			json.put("maxValueSSY", maxValueSSY);
		}
		return json;
	}
	/**
	 * 查询所有的设备类型
@ -41,6 +490,11 @@ public class DeviceService {
		return deviceDao.findByCategoryCode(categoryCode);
	}
	public List<Device> findAll(){
		List<Device> deviceList = deviceDao.findAll();
		return deviceList;
	}
	/**
	 * 获取设备信息
     */

+ 9 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/ExcelData.java

@ -0,0 +1,9 @@
package com.yihu.jw.hospital.utils;
/**
 * @author Airhead
 * @since 2017/3/27.
 */
public interface ExcelData {
    void transform(String data);
}

+ 187 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/QrcodeUtil.java

@ -0,0 +1,187 @@
package com.yihu.jw.hospital.utils;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.device.dao.DeviceDetailDao;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.wechat.service.WxAccessTokenService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
 * Created by yeshijie on 2024/1/17.
 */
@Component
public class QrcodeUtil {
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Value("${testPattern.sign}")
    private String isClose;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private FileUploadService fileUploadService;
    @Value("${testPattern.remote_inner_url}")
    private String remote_inner_url;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Value("${wechat.id}")
    private String wxId;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    //获取设备二维码前缀
    // https://hlw.xmdsyy.cn/hlw/ims-wx/#/healthRecords/deviceBind?SN=
    public String devicePriUrl(){
        WlyyHospitalSysDictDO dictDO = wlyyHospitalSysDictDao.findById("devicePriUrl").orElse(null);
        if(dictDO!=null){
            return dictDO.getDictValue();
        }
        return "";
    }
    //生成设备的小程序二维码 flag 是否强制生成
    public String makeDeviceXcxQrcode(DeviceDetail device, List<DeviceDetail> deviceDetailList,boolean flag){
        try {
//            String token = wxAccessTokenService.getWxAppletsAccessTokenById(wxId).getAccessToken();
            String url = devicePriUrl();
            if (device!=null){
                if (flag||StringUtils.isBlank(device.getQrcode())){
                    InputStream ipt = com.yihu.jw.util.common.QrcodeUtil.createQrcode(url+device.getDeviceCode(), 300, "png");
                    String qrcode = getFullUri(ipt);
                    device.setQrcode(qrcode);
//                deviceDetailDao.save(device);
                    return qrcode;
                }else {
                    return device.getQrcode();
                }
            }else {
                for (DeviceDetail deviceTmp : deviceDetailList) {
                    if (StringUtils.isBlank(deviceTmp.getQrcode())){
                        InputStream ipt = com.yihu.jw.util.common.QrcodeUtil.createQrcode(url+deviceTmp.getDeviceCode(), 300, "png");
                        String qrcode = getFullUri(ipt);
                        deviceTmp.setQrcode(qrcode);
                        deviceDetailDao.save(deviceTmp);
                        return qrcode;
                    }
                }
                System.out.println("批量生成完成!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public String getFullUri(InputStream inputStream) throws Exception {
        String fileName = "QRCode_" + System.currentTimeMillis() + ".jpg";
        UploadVO uploadVO = new UploadVO();
        MultipartFile multipartFile = new MockMultipartFile(fileName,fileName,"", inputStream);
        if (isClose.equalsIgnoreCase("1")){
            System.out.println("isClose"+1);
            Map<String, Object> map = fileUploadService.uploadImg(multipartFile);
            uploadVO.setFullUri(map.get("accessory").toString());
        }else if(isClose.equals("2")){
            System.out.println("isClose"+2);
            String originalFilename = multipartFile.getOriginalFilename();
            String[] fs = originalFilename.split("\\.");
            String type = fs[1];
            //内网上传
            String rs = fileUploadService.request(remote_inner_url,multipartFile,type);
            System.out.println("rs"+rs);
            com.alibaba.fastjson.JSONObject rsJson = JSON.parseObject(rs);
            uploadVO = objectMapper.readValue(rsJson.getJSONObject("obj").toJSONString(),UploadVO.class);
            inputStream.close();
        }else {
            // 上传服务器
            uploadVO = fileUploadService.uploadStream(multipartFile.getInputStream(),fileName,fastdfs_file_url);
        }
        return uploadVO.getFullUri();
    }
    /**
     * 从微信生成小程序二维码并下载到本地
     * @param fileName
     * @param page
     * @param scene
     * @param accessToken
     * @return
     */
    public String makeXcxQrcodeFromWx(String fileName, String page, String scene, String accessToken) {
        try {
            //调用微信接口生成二维码
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            //这就是你二维码里携带的参数 String型  名称不可变
            paramJson.put("scene", scene);
            //注意该接口传入的是page而不是path
            paramJson.put("page", page);
            paramJson.put("width", 430);
            //这是设置扫描二维码后跳转的页面
            /*    paramJson.put("width", 430);*/
            /* paramJson.put("is_hyaline", false);*/
            /*   paramJson.put("auto_color", true);*/
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            InputStream inputStream = httpURLConnection.getInputStream();
            UploadVO uploadVO = new UploadVO();
            MultipartFile multipartFile = new MockMultipartFile(fileName,fileName,"", inputStream);
            if (isClose.equalsIgnoreCase("1")){
                System.out.println("isClose"+1);
                Map<String, Object> map = fileUploadService.uploadImg(multipartFile);
                uploadVO.setFullUri(map.get("accessory").toString());
            }else if(isClose.equals("2")){
                System.out.println("isClose"+2);
                String originalFilename = multipartFile.getOriginalFilename();
                String[] fs = originalFilename.split("\\.");
                String type = fs[1];
                //内网上传
                String rs = fileUploadService.request(remote_inner_url,multipartFile,type);
                System.out.println("rs"+rs);
                com.alibaba.fastjson.JSONObject rsJson = JSON.parseObject(rs);
                uploadVO = objectMapper.readValue(rsJson.getJSONObject("obj").toJSONString(),UploadVO.class);
                inputStream.close();
            }else {
                // 上传服务器
                uploadVO = fileUploadService.uploadStream(multipartFile.getInputStream(),fileName,fastdfs_file_url);
            }
            return uploadVO.getFullUri();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

+ 30 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/ReadExcelUtil.java

@ -0,0 +1,30 @@
package com.yihu.jw.hospital.utils;
import jxl.Sheet;
import org.apache.commons.lang3.StringUtils;
/**
 * Created by Administrator on 2017/4/13 0013.
 */
public class ReadExcelUtil {
    // 返回去掉空行的记录数
    public static int getRightRows(Sheet sheet) {
        int rsCols = sheet.getColumns(); // 列数
        int rsRows = sheet.getRows(); // 行数
        int nullCellNum;
        int afterRows = rsRows;
        for (int i = 0; i < rsRows; i++) { // 统计行中为空的单元格数
            nullCellNum = 0;
            for (int j = 0; j < rsCols; j++) {
                String val = sheet.getCell(j, i).getContents();
                val = StringUtils.trimToEmpty(val);
                if (StringUtils.isBlank(val))
                    nullCellNum++;
            }
            if (nullCellNum >= rsCols) { // 如果nullCellNum大于或等于总的列数
                afterRows--;// 行数减一
            }
        }
        return afterRows;
    }
}