/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package beans.service.quickInput;
import beans.contract.entity.Polis;
import beans.doctor.disease.updater.EventKey;
import beans.service.create.SerrenMod;
import framework.beans.ModificationInfo;
import framework.beans.SecuredBean;
import framework.beans.security.BeanRights;
import framework.generic.ClipsServerException;
import beans.UserRightsSet;
import beans.directory.simple.entities.DiagnosisType;
import beans.doctor.diagnosis.DiagnosisBeanRemote;
import beans.service.ServiceRenderBeanLocal;
import beans.user.client.ClientBean;
import beans.doctor.diagnosis.Diagnosis;
import beans.doctor.diagnosis.DiagnosisBean;
import beans.doctor.diagnosis.DiagnosisDetails;
import beans.doctor.disease.Disease;
import beans.doctor.disease.DiseaseBeanLocal;
import beans.doctor.disease.DiseaseDetails;
import beans.doctor.disease.updater.FollowUpKey;
import beans.doctor.disease.updater.UpdaterStattalonBean;
import beans.doctor.emc.Emc;
import beans.service.ServiceRender;
import beans.service.ServiceRenderDetails;
import beans.service.create.CreateServiceBeanLocal;
import framework.audit.AuditDetails;
import framework.generic.EDataIntegrity;
import framework.utils.DateTimeUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.persistence.Query;
/**
*
* @author vip
*/
@Stateful(mappedName="clips-beans/QuickInputBean")
public class QuickInputBean extends SecuredBean
implements QuickInputBeanRemote {
public static final int COMMAND_CREATE = 0;
@EJB
private CreateServiceBeanLocal createServiceBean;
@EJB
private DiseaseBeanLocal diseaseBean;
@EJB
private ServiceRenderBeanLocal serviceRenderBean;
private int counter = 0;
@Override
protected void initBeanRights() throws ClipsServerException {
int[] r = new int[1];
r[COMMAND_CREATE] = RightPresence(UserRightsSet.WRITE_STATISTIC_MEDICAL_DATA.id);
rights = new BeanRights(r);
}
@Override
public DisSerDiagAuditChunk saveChunk(QuickInputChunk c, boolean needResult) throws ClipsServerException {
if ((counter % 5000) == 0) {
manager.flush();
manager.clear();
System.gc();
}
counter ++;
//Проверка может данная услуга уже присутствует
Date beg = DateTimeUtils.getDateOnly(c.date);
Date end = DateTimeUtils.getNextDay(beg);
String sql = null;
if (c.nSyst == 0) {
sql = "SELECT sr.renderedDate, sr.disease.extKey FROM ServiceRender sr " +
"WHERE sr.service.id = :serviceID " +
"AND sr.disease.extKey IS NULL " +
"AND sr.disease.emc.id = :emcID " +
"AND sr.functions.id = :collFuncID " +
"AND sr.renderedDate >= :beg " +
"AND sr.renderedDate <= :end ";
} else {
sql = "SELECT sr.renderedDate, sr.disease.extKey FROM ServiceRender sr " +
"WHERE sr.service.id = :serviceID " +
"AND sr.disease.extKey = :nSyst " +
"AND sr.disease.emc.id = :emcID " +
"AND sr.functions.id = :collFuncID " +
"AND sr.renderedDate >= :beg " +
"AND sr.renderedDate <= :end ";
}
Query q = manager.createQuery(sql);
q.setParameter("serviceID", c.serviceID);
q.setParameter("emcID", c.emcID);
q.setParameter("collFuncID", c.collFuncID);
q.setParameter("beg", beg);
q.setParameter("end", end);
if (c.nSyst != 0) {
q.setParameter("nSyst", c.nSyst);
}
List<Object[]> list = q.getResultList();
if (list.size() > 0) {
boolean founded = false;
for (int i = 0; i < list.size(); i++) {
Date srDate = (Date) list.get(i)[0];
Integer extKey = (Integer) list.get(i)[1];
boolean diseaseEqual = (extKey == null && c.nSyst == 0)
|| (extKey != null && extKey == c.nSyst);
if (DateTimeUtils.daysBetween(srDate, c.date) == 0 && diseaseEqual) {
founded = true;
}
}
if (founded == true) {
return null;
}
}
DisSerDiagAuditChunk result = new DisSerDiagAuditChunk();
ArrayList<AuditDetails> auditDetailsList = new ArrayList<AuditDetails>();
//создание заболевания
createDisease(c,auditDetailsList);
//создание услуги
ServiceRender newSerren = createSerren(c, auditDetailsList);
//создание диагнозов
result.diagnosisDetails = saveDiagnosis(newSerren, c, needResult, auditDetailsList);
result.serrenDetails = closeSerren(newSerren, c, needResult, auditDetailsList);
result.diseaseDetails = closeDisease(c, needResult, auditDetailsList);
result.auditDetailsList = auditDetailsList;
if (needResult) {
return result;
} else {
return null;
}
}
private void createDisease(QuickInputChunk c, ArrayList<AuditDetails> auditDetailsList) throws ClipsServerException {
if (c.diseaseID == 0) {
List<Disease> list = findEntityList(Disease.class, "extKey", c.nSyst);
if (list.size() > 1) {
throw new EDataIntegrity("Найдено более одного заболевания с внешним ключем " + c.nSyst);
}
if (list.size() == 1) {
c.diseaseID = list.get(0).getId();
return;
} else {
//Создаем новое заболевание
DiseaseDetails d = new DiseaseDetails();
d.collaboratorID = c.collID;
d.created = c.date;
d.dateReg = c.dataSt;
d.emcID = c.emcID;
d.extKey = c.nSyst;
diseaseBean.initByID(0, getSessionId());
ModificationInfo info = diseaseBean.update(d);
c.diseaseID = info.getId();
auditDetailsList.addAll(info.getAudit());
}
}
}
private DiseaseDetails closeDisease(QuickInputChunk c,
boolean needResult, ArrayList<AuditDetails> auditDetailsList) throws ClipsServerException {
DiseaseDetails d = findEntity(Disease.class, c.diseaseID).getDetails(this);
diseaseBean.initByID(c.diseaseID, getSessionId());
if (c.resultID != 0) {
d.closed = c.dateEnd == null ? c.date : c.dateEnd;
d.closerID = c.collID;
}
d.visitingPurposeID = c.purposeID;
d.diseaseResultID = c.resultID;
//d.closed = c.date;
ModificationInfo info = diseaseBean.update(d);
auditDetailsList.addAll(info.getAudit());
if (needResult) {
return findEntity(Disease.class, c.diseaseID).getDetails(this);
} else {
return null;
}
}
private ServiceRender createSerren(QuickInputChunk c, ArrayList<AuditDetails> auditDetailsList) throws ClipsServerException {
//серрен обязательно новый
Polis polisOMI = ClientBean.findPolisOMI(findEntity(Emc.class, c.emcID).getClient(), manager);
if (polisOMI == null) {
throw new EDataIntegrity("У пациента отсутствует полис ОМС");
}
ServiceRenderDetails d = new ServiceRenderDetails();
d.date = c.date; //дата назначения услуги
d.discount = 0; //Скидка в процентах
d.cancelled = false; //флаг отменена
d.repeat = 0; //повторы услуги
d.serviceID = c.serviceID; // услуга
d.directorID = c.collID;
d.packetServiceID = 0;
d.diseaseID = c.diseaseID;
d.polisID = polisOMI.getId();
d.cardID = 0;
d.servPlaceID = c.placeID;
d.receptionDetails = null; //запись на прием
d.referencedID = 0;
createServiceBean.setSession(getSessionId());
SerrenMod serrenMod = createServiceBean.createNewSerren(d);
auditDetailsList.addAll(serrenMod.info.getAudit());
return serrenMod.serren;
}
private ServiceRenderDetails closeSerren(ServiceRender serren, QuickInputChunk c,
boolean needResult, ArrayList<AuditDetails> auditDetailsList) throws ClipsServerException {
ServiceRenderDetails d = serren.getDetails(this);
d.renderDate = c.date; //дата оказания
d.functionsID = c.collFuncID; //исполняемые обязанности
d.uet = c.uet;
d.received = c.received;
serviceRenderBean.initByID(serren.getId(), getSessionId());
ModificationInfo info = serviceRenderBean.update(d);
int serrenID = info.getId();
auditDetailsList.addAll(info.getAudit());
if (needResult) {
return findEntity(ServiceRender.class, serrenID).getDetails(this);
} else {
return null;
}
}
private DiagnosisDetails saveDiagnosis(ServiceRender serren, QuickInputChunk c,
boolean needResult, ArrayList<AuditDetails> auditDetailsList) throws ClipsServerException {
//Диагноз записывать не надо, если введенные данные совпадают с диагнозом заболевания
//На данном этапе заболевание и услуга уже соданы
int mainDiagId = 0;
for (DiagnosChunk dc : c.diagList) {
//записываем диагнозы
DiagnosisBeanRemote bean = getBean(DiagnosisBean.class);
bean.initByID(0, getSessionId());
DiagnosisDetails d = new DiagnosisDetails();
d.author = null; //Кто поставил (только если из др клиники)
d.date = dc.dateDs; //Дата постановки диагноза
d.mkbID = dc.mkbID; //диагноз по мкб
if (dc.diagTypeID == 0) {
if (mainDiagId == 0) {
if (dc.mkbID == 0) {
throw new EDataIntegrity("Отсутствует основной диагноз");
} else {
throw new EDataIntegrity("Указан сопутствующий диагноз при отсутствии основного");
}
}
d.type = DiagnosisType.DIAGNOSIS_TYPE_PRELIMINARY;
d.referenced = mainDiagId;
} else {
d.type = dc.diagTypeID; //тип (предварительный, заключительный)
d.referenced = 0;
}
d.encounter = dc.encounterID; //установлен впервые, впервые за год, повторно в году
d.serviceRenderID = serren.getId();
if (bean.mustHaveStage(d.mkbID)) {
d.stage = 1;
} else {
d.stage = 0;
}
d.complicationID = dc.complicationID;
d.traumaTypeID = dc.trawmaTypeID;
ModificationInfo info = bean.update(d);
int id = info.getId();
auditDetailsList.addAll(info.getAudit());
manager.flush();
if (dc.diagTypeID != 0) {
if (mainDiagId != 0) {
throw new EDataIntegrity("Указано более одного основного диагноза");
}
mainDiagId = id;
if (dc.disp > 1) {
//Запомним в мапе что диагноз относится к диспансеризации
String sql = "SELECT s.disease.emc.id FROM ServiceRender s " +
"WHERE s.id = :serviceID";
Query q = manager.createQuery(sql);
q.setParameter("serviceID", serren.getId());
int emcID = (Integer) q.getSingleResult();
FollowUpKey fkey = new FollowUpKey(emcID, dc.mkbCode);
ArrayList<EventKey> eventList = UpdaterStattalonBean.getFollowMap().get(fkey);
eventList.add(new EventKey(id, dc.disp, dc.dispSn, dc.dateDs));
}
}
}
if (mainDiagId != 0 && needResult) {
return findEntity(Diagnosis.class, mainDiagId).getDetails(this);
} else {
return null;
}
}
}