package com.hx.phip.his.service.impl; import javax.annotation.Resource; import com.alibaba.fastjson.JSON; import com.hx.phiappt.common.RoleType; import com.hx.phiappt.model.*; import com.hx.phiappt.model.consumables.Consumables; import com.hx.phiappt.model.order.OrdersTotal; import com.hx.phiappt.model.prescription.*; import com.hx.phip.his.config.SystemConfig; import com.hx.phiappt.dao.mapper.*; import com.hx.phip.model.SyncBasicInformationRecord; import com.hx.phip.his.service.GetTokenService; import com.hx.phip.uti.PageUtil; import com.hx.phip.uti.WeChatApiUtil; import com.hx.util.DateUtil; import com.hx.util.StringUtils; import com.mongodb.BasicDBObject; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.hx.exception.TipsException; import com.hx.phip.his.service.PrescriptionService; import com.hx.mybatisTool.SqlSentence; import java.text.SimpleDateFormat; import java.util.*; @Transactional @Service public class PrescriptionServiceImpl implements PrescriptionService { private static Logger logger = LoggerFactory.getLogger(PrescriptionServiceImpl.class); @Resource private SystemParameterMapper systemParameterMapper; @Resource private SystemConfig systemConfig; // @Autowired private MongoTemplate mongoTemplate; @Resource private PrescriptionMapper prescriptionMapper; @Resource private UserMapper userMapper; @Resource private EmployeeMapper employeeMapper; @Resource private ShopMapper shopMapper; @Resource private FamiliesRoomMapper familiesRoomMapper; @Resource private OrdersTotalMapper ordersTotalMapper; @Resource private ConsumablesMapper consumablesMapper; @Resource private PrescriptionItemMapper prescriptionItemMapper; @Resource private PrescriptionGroupMapper prescriptionGroupMapper; /**查询列表*/ @Override public List selectList(SqlSentence sqlSentence) { return prescriptionMapper.selectList(sqlSentence); } /**查询列表*/ @Override public List> selectListMap(SqlSentence sqlSentence) { return prescriptionMapper.selectListMap(sqlSentence); } /**查询单个*/ @Override public Prescription selectOne(SqlSentence sqlSentence) { return prescriptionMapper.selectOne(sqlSentence); } /**查询单个*/ @Override public Map selectOneMap(SqlSentence sqlSentence) { return prescriptionMapper.selectOneMap(sqlSentence); } /**查询单个,大数据不拿取*/ @Override public Prescription selectOneByKey(Object object) { return prescriptionMapper.selectOneByKey(object); } /**查询单个,大数据拿取*/ @Override public Prescription selectOneByKeyBlob(Object object) { return prescriptionMapper.selectOneByKeyBlob(object); } /**新增*/ @Override public void insert(Prescription prescription) { int count = prescriptionMapper.insert(prescription); if(count != 1) { throw new TipsException("新增失败!"); } } /**修改*/ @Override public void updateAll(Prescription prescription) { int count = prescriptionMapper.updateAll(prescription); if(count!=1) { throw new TipsException("保存失败!"); } } /**修改*/ @Override public void updateWhere(SqlSentence sqlSentence) { int count = prescriptionMapper.updateWhere(sqlSentence); if(count!=1) { throw new TipsException("保存失败!"); } } /**删除一个*/ @Override public void deleteOne(String delId) { int count = prescriptionMapper.deleteById(delId); if(count!=1) { throw new TipsException("删除失败!"); } } /**查询条数*/ @Override public int selectCount(SqlSentence sqlSentence) { int count = prescriptionMapper.selectCount(sqlSentence); return count; } @Resource private GetTokenService getTokenService; //获取企业微信token public String getApplicationAccessToken(){ String at = getTokenService.getApplicationAccessToken(systemParameterMapper, systemConfig.getCorpId(), systemConfig.getCorpMpSecret()); return at; } /** * 初始化处方 * @param basicInformationRecord */ @Override public void saveHisPrescription(SyncBasicInformationRecord basicInformationRecord) { //查询mongodb处方表的数据 List testList = new ArrayList<>(); testList.add(null); testList.add(""); basicInformationRecord.setStartTime(new Date()); Query query = new Query(); Calendar now = Calendar.getInstance(); //当前时间 now.add(Calendar.MINUTE,-30); Date before = now.getTime(); Criteria criteria = new Criteria(); if (basicInformationRecord.getType() == 2) { criteria = Criteria.where("metadata.state").is(1) .andOperator( new Criteria().and("metadata.createTimestamp").gte(before), new Criteria().and("metadata.createTimestamp").lt(new Date()), new Criteria().and("metadata.state").is(1), new Criteria().and("access.global").is(false) ); }else { criteria.and("access.global").is(false); criteria.and("metadata.state").is(1); } query.addCriteria(criteria); Integer pageSize = 100; //查找处方总数 long total= mongoTemplate.count(query, Map.class,"his-prescription"); logger.info("处方总数:"+total); long pageCount = total/pageSize+1; Integer num = 0; //每次取100条查询 for (long i = 0; i < pageCount; i++) { Integer pageNum= Math.toIntExact(i+1); pageNum = PageUtil.getPageNum(pageNum); pageSize = PageUtil.getPageSize(pageSize); query.with(Sort.by(Sort.Direction.ASC, "_id")); query.with(PageRequest.of(pageNum , pageSize)); List prescriptionMaps = mongoTemplate.find(query, Map.class, "his-prescription"); logger.info("第" + Math.toIntExact(i+1) + "页条数:" + prescriptionMaps.size()); System.out.println("第" + Math.toIntExact(i+1) + "页条数:" + prescriptionMaps.size()); num = num + prescriptionMaps.size(); //循环try-catch处理数据(根绝hisid查询新增修改) for (Map prescription : prescriptionMaps) { try { handleHisPrescription(JSONObject.fromObject(prescription)); basicInformationRecord.setSuccessNumber(basicInformationRecord.getSuccessNumber()+1); } catch (Exception e) { basicInformationRecord.setFailNumber(basicInformationRecord.getFailNumber()+1); logger.error("同步处方失败:"+prescription.get("_id"),e); System.out.println("同步处方失败:"+prescription.get("_id")); } } } if (basicInformationRecord.getType() == 1){ sendAppointment("同步处方完成,成功" + basicInformationRecord.getSuccessNumber() + "条,失败"+basicInformationRecord.getFailNumber()+"条。"); } } /** * 处理处方数据 * @param jsonObject */ @Override public void handleHisPrescription(JSONObject jsonObject){ SqlSentence sqlSentence = new SqlSentence(); Map sqlMap = new HashMap<>(); sqlMap.put("isDel", BaseEntity.NO); Prescription prescription = prescriptionMapper.selectOneByApiId(jsonObject.optString("_id")); Prescription handlePrescription = handlePrescription(prescription,jsonObject); if (handlePrescription == null){ return; } if (prescription == null){ prescriptionMapper.insert(handlePrescription); }else { prescriptionMapper.updateAll(handlePrescription); sqlMap.put("prescriptionId",handlePrescription.getId()); sqlSentence.sqlSentence("SELECT id FROM prescription_group WHERE prescriptionId = #{m.prescriptionId} AND isDel = #{m.isDel}",sqlMap); List groupList = prescriptionGroupMapper.selectList(sqlSentence); StringBuffer sql = new StringBuffer(); sql.append("prescriptionId in ("); if (groupList != null && groupList.size() > 0){ for (PrescriptionGroup prescriptionGroup : groupList) { sql.append("'").append(prescriptionGroup.getId()).append("'").append(","); } } sql.append("'").append(handlePrescription.getId()).append("'").append(")"); sqlSentence.sqlWhere(sql.toString(),sqlMap); prescriptionItemMapper.deleteWhere(sqlSentence); sqlSentence.sqlWhere("prescriptionId = #{m.prescriptionId}",sqlMap); prescriptionGroupMapper.deleteWhere(sqlSentence); } //处方详细内容(药品信息等) if (jsonObject.get("medicines") != null) { List> medicines = jsonObject.getJSONArray("medicines"); if (medicines != null && medicines.size() > 0) { for (Map medicine : medicines) { //处方模板药品信息 if (medicine.get("entries") == null) { PrescriptionItem handlePrescriptionItem = handlePrescriptionItem(medicine); handlePrescriptionItem.setPrescriptionId(handlePrescription.getId()); handlePrescriptionItem.setType(0); prescriptionItemMapper.insert(handlePrescriptionItem); } else { //药品组 PrescriptionGroup templateGroup = new PrescriptionGroup(); templateGroup.setPrescriptionId(handlePrescription.getId()); templateGroup.setName((String) medicine.get("name")); templateGroup.setRemarks((String) medicine.get("note")); prescriptionGroupMapper.insert(templateGroup); List> entriesList = (List>) medicine.get("entries"); //药品组的详细信息 for (Map entries : entriesList) { PrescriptionItem handlePrescriptionItem = handlePrescriptionItem(entries); handlePrescriptionItem.setPrescriptionId(templateGroup.getId()); handlePrescriptionItem.setType(1); prescriptionItemMapper.insert(handlePrescriptionItem); } } } } } } /** * 处理处方数据,组装成实体类 * @return */ private Prescription handlePrescription(Prescription prescription,JSONObject jsonObject){ //用户的hisId String userApiId = JSON.parseObject(jsonObject.optString("patient")).getString("_id"); //根据hisid查询用户信息 User user = userMapper.selectOneByApiId(userApiId); //医生hisid String doctorApiId = JSON.parseObject(jsonObject.optString("doctor")).getString("_id"); String doctorApiName = JSON.parseObject(jsonObject.optString("doctor")).getString("name"); //根据hisId查询医生(员工)信息 Employee employee = employeeMapper.selectByApiId(doctorApiId); //门店hisId String shopApiId = JSON.parseObject(jsonObject.optString("organization")).getString("_id"); String shopApiName = JSON.parseObject(jsonObject.optString("organization")).getString("name"); //根据hisId查询门店信息 Shop shop = shopMapper.selectOneByApiId(shopApiId); //科室hisId String roomApiId = JSON.parseObject(jsonObject.optString("medicalDepartment")).getString("_id"); String roomApiName = JSON.parseObject(jsonObject.optString("medicalDepartment")).getString("name"); //根据hisId查询科室信息 FamiliesRoom familiesRoom = familiesRoomMapper.selectOneByApiId(roomApiId); //订单hisId String orderApiId = jsonObject.optString("orderId"); //根据hisId查询订单信息 OrdersTotal ordersTotal = ordersTotalMapper.selectOneByApiId(orderApiId); //就诊号 String visitNumber = jsonObject.optString("visitNumber"); //病历号 String numberNo = jsonObject.optString("patientNumber"); //临床诊断 String clinicalDiagnose = jsonObject.optString("clinicalDiagnose"); //处方类型 String typeValue = JSON.parseObject(jsonObject.optString("type")).getString("value"); //状态类型 String statusValue = JSON.parseObject(jsonObject.optString("status")).getString("value"); //备注 String note = jsonObject.optString("note"); if (prescription == null){ prescription = new Prescription(); }else { prescription.setEditTime(new Date()); // logger.info("创建时间:{}",jsonObject.toString()); //logger.info("创建时间:{}",jsonObject.getJSONObject("metadata").getJSONObject("createTimestamp").getLong("time")); } prescription.setCreateTime(new Date(jsonObject.getJSONObject("metadata").getJSONObject("createTimestamp").getLong("time"))); prescription.setApiId(jsonObject.optString("_id")); //处方的用户id if (user == null){ prescription.setUserId(userApiId); }else { prescription.setUserId(user.getId()); } //处方类型处理 //非普通处方 if (typeValue.equals("special-mp")){ prescription.setPrescriptionType(Prescription.TYPE_NO_ORDINARY); //非普通处方都是已完成状态 prescription.setStatus(Prescription.STATUS_SUC); }else if (typeValue.equals("general-mp")){ //普通处方 prescription.setPrescriptionType(Prescription.TYPE_ORDINARY); //普通处方状态处理 //状态-草稿 if (statusValue.equals("pre-draft")){ prescription.setStatus(Prescription.STATUS_DRAFT); }else if (statusValue.equals("draft")){ //状态-待确认 prescription.setStatus(Prescription.STATUS_WAIT); }else if (statusValue.equals("confirmed")){ //状态-待支付 prescription.setStatus(Prescription.STATUS_UNPAID); }else if (statusValue.equals("executed")){ //状态-已收费 prescription.setStatus(Prescription.STATUS_SUC); }else if (statusValue.equals("cancelled")){ //状态-已作废 prescription.setStatus(Prescription.STATUS_INVALID); } }else { return null; } //处方的医生信息 if (employee == null){ prescription.setDoctorId(doctorApiId); prescription.setDoctorName(doctorApiName); }else { prescription.setDoctorId(employee.getId()); prescription.setDoctorName(employee.getCnName()); } //处方所属门店信息 if (shop == null){ prescription.setShopId(shopApiId); prescription.setShopName(shopApiName); }else { prescription.setShopId(shop.getId()); prescription.setShopName(shop.getName()); } //处方所属科室信息 if (familiesRoom == null){ prescription.setFamiliesRoomId(roomApiId); prescription.setFamiliesRoomName(roomApiName); }else { prescription.setFamiliesRoomId(familiesRoom.getId()); prescription.setFamiliesRoomName(familiesRoom.getFamiliesRoomName()); prescription.setFamiliesRoomCode(familiesRoom.getFamiliesRoomCode()); } //就诊号处理 if (visitNumber != null){ prescription.setVisitNo(visitNumber); }else { if (shop != null){ prescription.setVisitNo(getVisitNo(shop.getCode())); }else { prescription.setVisitNo(getVisitNo(null)); } } //病例号处理 if (numberNo != null){ prescription.setNumberNo(numberNo); }else if (user != null){ prescription.setNumberNo(user.getCIQ()); } if (ordersTotal != null){ prescription.setOrderId(ordersTotal.getId()); prescription.setOrderNo(ordersTotal.getOrderNo()); } prescription.setClinicalDiagnosis(clinicalDiagnose); prescription.setRemarks(note); return prescription; } /** 处方生成就诊号 */ private String getVisitNo(String shopNo) { if (StringUtils.isEmpty(shopNo)) { shopNo = ""; } SqlSentence sqlSentence = new SqlSentence(); Map sqlMap = new HashMap<>(); sqlSentence.setSqlSentence(" to_days(createTime) = to_days(now())"); int count = prescriptionMapper.selectCount(sqlSentence); count += 1; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); String s = simpleDateFormat.format(new Date()) + "0000"; long num = new Long(s) + count; return "CF" + shopNo + num; } /** * 处理处方详细信息 * @param medicine * @return */ private PrescriptionItem handlePrescriptionItem(Map medicine){ SqlSentence sqlSentence = new SqlSentence(); Map sqlMap = new HashMap<>(); sqlMap.put("isDel", BaseEntity.NO); sqlMap.put("consumablesId", medicine.get("skuId")); PrescriptionItem prescriptionItem = new PrescriptionItem(); prescriptionItem.setName((String) medicine.get("name")); sqlSentence.sqlSentence("SELECT * FROM consumables WHERE hisId = #{m.consumablesId} AND isDel = #{m.isDel}",sqlMap); Consumables consumables = consumablesMapper.selectOne(sqlSentence); if (consumables != null){ prescriptionItem.setConsumablesId(consumables.getId()); prescriptionItem.setPrice(consumables.getPrice()); }else { prescriptionItem.setConsumablesId((String) medicine.get("skuId")); } //规格 if (medicine.get("specification") != null) { prescriptionItem.setSpec((String) medicine.get("specification")); }else { prescriptionItem.setSpec("-"); } //单位 if (medicine.get("unit") != null) { prescriptionItem.setUnit((String) medicine.get("unit")); }else { prescriptionItem.setUnit("-"); } //剂量 if (medicine.get("dose") != null) { prescriptionItem.setDose((String) medicine.get("dose")); }else { prescriptionItem.setDose("-"); } //剂量单位 Map doseUnit = (Map) medicine.get("doseUnit"); if (doseUnit != null) { prescriptionItem.setDoseUnitName(doseUnit.get("displayText")); prescriptionItem.setDoseUnit(doseUnit.get("vocabName").replaceAll("-", "_") + doseUnit.get("value")); }else { prescriptionItem.setDoseUnitName("-"); prescriptionItem.setDoseUnit("-"); } //频次 Map frequency = (Map) medicine.get("frequency"); if (frequency != null) { prescriptionItem.setFrequencyName(frequency.get("displayText")); prescriptionItem.setFrequency(frequency.get("vocabName").replaceAll("-", "_") + doseUnit.get("value")); }else { prescriptionItem.setFrequencyName("-"); prescriptionItem.setFrequency("-"); } //天数 if (medicine.get("duration") != null) { Double duration = (Double) medicine.get("duration"); Double dayNum = new Double(duration); prescriptionItem.setDayNum(dayNum.intValue()); }else { prescriptionItem.setDayNum(0); } //数量 if (medicine.get("quantity") != null) { prescriptionItem.setNum((Integer) medicine.get("quantity")); }else { prescriptionItem.setNum(0); } //用法 if (medicine.get("instruction") != null) { prescriptionItem.setUsageName((String) medicine.get("instruction")); }else { prescriptionItem.setUsageName("-"); } //备注 prescriptionItem.setRemarks((String) medicine.get("note")); return prescriptionItem; } public void sendAppointment(String source){ SqlSentence sqlSentence = new SqlSentence(); Map map=new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence("SELECT e.* FROM employee e INNER JOIN employee_role er on e.id=er.employeeId " + "INNER JOIN employee_role_type ert on er.roleTypeId=ert.id WHERE ert.uniqueStr = #{m.uniqueStr} GROUP BY e.id"); map.put("uniqueStr", RoleType.UNIQUE_STR_ADMIN); List list= employeeMapper.selectList(sqlSentence); StringBuffer touser=new StringBuffer(); for (int i = 0; i < list.size(); i++) { if(i==list.size()-1){ touser.append(list.get(i).getUserId()); }else { touser.append(list.get(i).getUserId()+"|"); } } WeChatApiUtil.sendSyncAppointment(getApplicationAccessToken(),systemConfig.getAppId(),touser.toString(),source); } }