Package clips.delegate.doctor

Source Code of clips.delegate.doctor.DiseaseLocal

/*
* DiseaseLocal.java
*
* Created on 12 Декабрь 2007 г., 11:57
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package clips.delegate.doctor;

import beans.contract.entity.Polis;
import beans.doctor.disease.DiseaseBean;
import beans.doctor.disease.DiseaseBeanRemote;
import beans.doctor.disease.DiseaseFolluwupPrintInfo;
import clips.delegate.client.ClientLocal;
import cli_fmw.delegate.cache.ExtraDataManager;
import beans.doctor.disease.DiseaseDetails;
import clips.delegate.service.SerRenLocal;
import cli_fmw.main.ClipsException;
import cli_fmw.delegate.directory.complex.DirectoryLocator;
import clips.delegate.doctor.diagnosis.DiagnosisLocal;
import clips.delegate.doctor.sicklist.SicklistLocal;
import clips.delegate.DEC.DECEmc;
import cli_fmw.delegate.DelegateLine2;
import cli_fmw.delegate.cache.Cache;
import cli_fmw.delegate.cache.DelegateSecondaryCacheDgt;
import cli_fmw.delegate.client.Address;
import cli_fmw.delegate.utils.TimeLocal;
import cli_fmw.main.DelegatePrintable;
import cli_fmw.report.CombinedReportCreator;
import cli_fmw.report.FormReportCreator;
import cli_fmw.utils.MultiIcon;
import clips.doctor.newEMC.init.generic.ChildrenListStateless;
import clips.doctor.newEMC.init.generic.DelegateNode;
import clips.delegate.contract.PolisData;
import clips.delegate.directory.complex.DirectoryCollaboratorFunctionsItem;
import clips.delegate.directory.complex.DirectoryMKB10;
import clips.delegate.directory.complex.DirectoryMKB10Item;
import clips.delegate.directory.ro.DirectoryCollaborator;
import clips.delegate.directory.ro.DirectoryCollaboratorItem;
import clips.delegate.directory.simple.disablilityType.DirectoryDisabilityTypeItem;
import clips.delegate.directory.simple.diseaseResult.DirectoryDiseaseResult;
import clips.delegate.directory.simple.diseaseResult.DirectoryDiseaseResultItem;
import clips.delegate.directory.complex.DirectoryDistrictItem;
import clips.delegate.directory.simple.insurer.DirectoryInsurerItem;
import clips.delegate.directory.simple.medicalAidType.DirectoryMedicalAidTypeItem;
import clips.delegate.directory.simple.regionIdCode.DirectoryRegionIdCodeItem;
import clips.delegate.directory.simple.servicingPlace.DirectoryServicingPlaceItem;
import clips.delegate.directory.simple.visitingPurpose.DirectoryVisitingPurpose;
import clips.delegate.directory.simple.visitingPurpose.DirectoryVisitingPurposeItem;
import clips.delegate.doctor.medexam.MedexamLocal;
import clips.login.UserInfo;
import beans.directory.simple.entities.DiagnosisType;
import beans.service.medexam.MedexamDetails;
import framework.utils.Converter;
import beans.service.ServiceRenderDetails;
import beans.doctor.sicklist.entity.SicklistDetails;
import cli_fmw.delegate.AuditListener;
import cli_fmw.utils.ConfigGui;
import clips.delegate.client.ClientDocumentData;
import clips.delegate.client.ClientExemptionData;
import clips.delegate.config.ConfigLocal;
import clips.delegate.directory.simple.exemptionType.DirectoryExcemptionItem;
import clips.delegate.directory.simple.representativeStatus.DirectoryRepresentativeStatusItem;
import clips.delegate.job.JobLocal;
import framework.utils.DateTimeUtils;
import framework.utils.ROList;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.Icon;
import javax.swing.ImageIcon;

public class DiseaseLocal extends
    DelegateNode<DiseaseBeanRemote, DiseaseDetails, SerRenLocal>
        implements Iconable, DelegatePrintable, Signable {

    private SerrenCache serrenCache = new SerrenCache(getEDM());
    private DECEmc emc = new DECEmc(this, getAuditListener());
    private DECMedexam medexam = new DECMedexam(this);
    private Cache<Date> profcheckupDate = new Cache<Date>();
    private Boolean isFollowupEvent;
    private DirectoryMKB10Item mKB10Item = null;

    private static ImageIcon diseaseIcon = new ImageIcon(DiseaseLocal.class.getResource("/resources/icons/disease.gif"));
    private static ImageIcon diseaseIconOpened = new ImageIcon(DiseaseLocal.class.getResource("/resources/icons/disease_opened.gif"));
    private static ImageIcon profcheckupIcon = new ImageIcon(DiseaseLocal.class.getResource("/resources/icons/Profcheckup.gif"));
    private static ImageIcon profcheckupIconOpened = new ImageIcon(DiseaseLocal.class.getResource("/resources/icons/Profcheckup_opened.gif"));
    private static ImageIcon followupEventIcon = new ImageIcon(DiseaseLocal.class.getResource("/resources/icons/followup.gif"));
    private static ImageIcon followupEventIconOpened = new ImageIcon(DiseaseLocal.class.getResource("/resources/icons/followup_opened.gif"));
    private static ImageIcon medexamIcon = new ImageIcon(DiseaseLocal.class.getResource("/resources/icons/medexam.gif"));
    private static ImageIcon medexamIconOpened = new ImageIcon(DiseaseLocal.class.getResource("/resources/icons/medexam_opened.gif"));
    private static ImageIcon haveNotSpecificDiagnosesIcon = new ImageIcon(DiseaseLocal.class.getResource("/resources/icons/notrendered.gif"));
    private HashMap<String, Object> data;

    private static final int CONST_1 = 1;
    private static final int CONST_2 = 2;
    private static final int CONST_3 = 3;
   
    /**
     *
     * @param e
     * @param details
     * @throws ClipsException
     */
    public DiseaseLocal(EmcLocal e, DiseaseDetails details, AuditListener al) throws ClipsException {
        super(details, al);
        emc.initBy(e);
    }

    public DiseaseLocal(EmcLocal e, int id, int mkbSpecId, AuditListener al) throws ClipsException {
        this(e, id, al);
        setSpecDiagnosisMkbID(mkbSpecId);
    }

    public DiseaseLocal(EmcLocal e) throws ClipsException {
        super(e.getAuditListener());
        emc.initBy(e);
        getDetails().collaboratorID = UserInfo.get().getCollaborator().getID();
        Date date = TimeLocal.getCurrentTime().getTime();
        getDetails().created = date;
        getDetails().dateReg = date;
    }
   
    public DiseaseLocal(EmcLocal e, int id, AuditListener al) throws ClipsException {
        super(id, al);
        emc.initBy(e);
    }

    public DiseaseLocal(int diseaseID, AuditListener auditListener) throws ClipsException {
        super(diseaseID, auditListener);
    }

    @Override
    protected DiseaseDetails getNewDetails() {
        return new DiseaseDetails();
    }

    public Date getCreated() throws ClipsException {
        return isProfcheckup() ? profcheckupDate.get() : getDetails().created;
    }

    //never use client date
    @Deprecated
    public void setCreated(Date created) throws ClipsException {
        getDetails().created = created;
        getDetails().dateReg = created;
        fireContentStateEvent();
    }

    public EmcLocal getEmcLocal() throws ClipsException {
        return emc.get();
    }

    public DirectoryCollaboratorItem getCollaborator() throws ClipsException {
        DirectoryCollaborator dir = DirectoryLocator.getDirectory(DirectoryCollaborator.class, false);
        return dir.getItemFromID(getDetails().collaboratorID);
    }

    public Date getClosed() throws ClipsException {
        return getDetails().closed;
    }

    public void setClosed(Date closed) throws ClipsException {
        getDetails().closed = closed;
        fireContentStateEvent();
    }

    public DirectoryCollaboratorItem getCloser() throws ClipsException {
        if (getDetails().closerID == 0) {
            return null;
        }
        DirectoryCollaborator dir = DirectoryLocator.getDirectory(DirectoryCollaborator.class, false);
        return dir.getItemFromID(getDetails().closerID);
    }

    public void setCloser(DirectoryCollaboratorItem closer) throws ClipsException {
        getDetails().closerID = closer == null ? 0 : closer.getID();
        fireContentStateEvent();
    }

    public DirectoryVisitingPurposeItem getVisitingPurpose() throws ClipsException{
        DirectoryVisitingPurpose purpose = DirectoryLocator.getDirectory(DirectoryVisitingPurpose.class);
        return purpose.getItemFromID(getDetails().visitingPurposeID);
    }

    /**
     *
     * @param item can't be null
     * @throws cli_fmw.main.ClipsException
     */
    public void setVisitingPurpose(DirectoryVisitingPurposeItem item) throws ClipsException{
        getDetails().visitingPurposeID = item.getID();
        fireContentStateEvent();
    }
   
    public DirectoryDiseaseResultItem getDiseaseResult() throws ClipsException{
        DirectoryDiseaseResult result = DirectoryLocator.getDirectory(DirectoryDiseaseResult.class);
        return result.getItemFromID(getDetails().diseaseResultID);
    }

    /**
     *
     * @param item can't be null
     * @throws cli_fmw.main.ClipsException
     */
    public void setDiseaseResult(DirectoryDiseaseResultItem item) throws ClipsException{
        getDetails().diseaseResultID = item.getID();
        fireContentStateEvent();
    }

    /**
     * Является ли заболевание профосмотром
     * @return
     * @throws ClipsException
     */
    public Boolean isProfcheckup() throws ClipsException {
        return getProfcheckupDate() != null;
    }
   
    /**
     * Является ли заболевание событием диспансеризации
     * @return
     * @throws ClipsException
     */
    public Boolean isFollowupEvent() throws ClipsException {
        if (isNewlyCreated()){
            return false;
        }
        if (isFollowupEvent == null) {
            try {
                isFollowupEvent = getBean().isFollowupEvent();
            } catch (Exception ex) {
                clearBean();
                throw new ClipsException("Ошибка: не удалось проверить является ли заболевание событием диспансеризации", ex);
            }
        }
        return isFollowupEvent;
    }

    /**
     * Является ли заболевание медосмотром
     * @return
     * @throws ClipsException
     */
    public Boolean isMedexam() throws ClipsException {
        if (isNewlyCreated()){
            return false;
        }
        return (medexam.get() != null);
    }

    public MedexamLocal getMedexamLocal() throws ClipsException {
        return medexam.get();
    }

    /**
     * Возвращает первый попавшийся заключительный диагноз
     * предполагается что в заболевании может существовать только один заключительный диагноз
     * @return диагноз. если диагноза нет, то null
     * @throws cli_fmw.main.ClipsException
     */
    public DiagnosisLocal getSpecificDiagnosis() throws ClipsException{
        if (getID() == 0) {
            return null;
        }
        for (SerRenLocal serRenLocal : serrenCache.get()) {
            List<DiagnosisLocal> diagnosisList = serRenLocal.getDiagnosisList();
            for (DiagnosisLocal diagnosis : diagnosisList) {
                if (diagnosis.isFinal()){
                    if (mKB10Item == null && !diagnosis.isNewlyCreated()){
                        mKB10Item = diagnosis.getMkb();
                    }
                    return diagnosis;
                }
            }
        }
        return null;
    }
   
    @Override
    public String toString() {
        String toStr;
        try {
            toStr = "[" + Converter.dateToString(getCreated()) + "] ";
            if (getID() == 0) {
                toStr += "Новое заболевание";
            } else if (isProfcheckup()) {
                toStr += "Профосмотр";
            } else if (isFollowupEvent()){
                toStr += "Приход по диспансерному учёту";
            } else if (isMedexam()){
                toStr += "Медосмотр";
            } else {
                if (serrenCache.inCache()){
                    DiagnosisLocal sd = getSpecificDiagnosis();
                    if (sd != null) {
                        toStr += "МКБ:" + sd.getMkb().getDiseaseCode();
                    }
                }else if (mKB10Item != null){
                    toStr += "МКБ:" + mKB10Item.getDiseaseCode();
                }
            }
        } catch (ClipsException ex) {
            //ex.printStackTrace();
            toStr = "Ошибка сервера";
           
        }
        return toStr;
    }

    /**
     * Возвращает список услуг и больничных, которые ссылаются на данное заболевание
     * Список только для отображения в дереве. (только кеш)
     * @return
     * @throws ClipsException
     */
    @Override
    public ROList<SerRenLocal> getChildren() throws ClipsException {
        List<SerRenLocal> list = new ArrayList<SerRenLocal>();
        list.addAll(getSerrenList());
        return new ROList<SerRenLocal>(list);
    }

    private DiseaseFolluwupPrintInfo getPrintInfo() throws ClipsException{
        try {
            return getBean().getFollowupPrintInfo();
        } catch (Exception ex) {
            clearBean();
            throw new ClipsException("не удалось получить информацию для печати", ex);
        }
    }

    @Override
    public int getChildCount() throws ClipsException {
        return serrenCache.getSize();
    }

    @Override
    protected void addChildImpl(SerRenLocal child) throws ClipsException {
        serrenCache.get().add(child);
        medexam.clearCache();
    }

    void setSpecDiagnosisMkbID(int mkbID) {
        try {
            mKB10Item = DirectoryLocator.getDirectory(DirectoryMKB10.class).getItemFromID(mkbID);
        } catch (ClipsException ex) {
            ex.printStackTrace();
        }
    }

    class DelegateComparator implements Comparator<DelegateLine2>{

        @Override
        public int compare(DelegateLine2 o1, DelegateLine2 o2) {
            //попытка сравнить по дате
            try {
                Date d1 = null;
                Date d2 = null;
                if (o1 instanceof SerRenLocal) {
                    d1 = ((SerRenLocal) o1).getSerDate();
                }
                if (o1 instanceof SicklistLocal) {
                    d1 = ((SicklistLocal) o1).getDateOpen().getTime();
                }
                if (o2 instanceof SerRenLocal) {
                    d2 = ((SerRenLocal) o2).getSerDate();
                }
                if (o2 instanceof SicklistLocal) {
                    d2 = ((SicklistLocal) o2).getDateOpen().getTime();
                }
                if (d1 == null && d2 == null) {
                    return 0;
                } else if (d1 == null) {
                    return 1;
                } else if (d2 == null) {
                    return -1;
                } else {
                    return d1.compareTo(d2);
                }
            } catch (ClipsException ex) {
                //дропаем
                return 1;
            }
        }

    }
   
    @Override
    public void removeChildImpl(SerRenLocal child) throws ClipsException {
        if(child instanceof SerRenLocal) {
            serrenCache.get().remove(child);
            medexam.clearCache();
        } else {
            throw new IllegalArgumentException("Not existent child");
        }
    }
   
//                return PROFCHECUP_ICON;
//            } else {
//                return STT_ICON;
   
    @Override
    public Icon getIcon() {
        MultiIcon icon = null;
        try {
            if (isProfcheckup()) {
                if (getClosed() == null) {
                    icon = new MultiIcon(profcheckupIconOpened);
                } else {
                    icon = new MultiIcon(profcheckupIcon);
                }
            } else if (isFollowupEvent()){
                if (getClosed() == null) {
                    icon = new MultiIcon(followupEventIconOpened);
                } else {
                    icon = new MultiIcon(followupEventIcon);
                }
            } else if (isMedexam()){
                if (getClosed() == null) {
                    icon = new MultiIcon(medexamIconOpened);
                } else {
                    icon = new MultiIcon(medexamIcon);
                }
            } else {
                if (getClosed() == null) {
                    icon = new MultiIcon(diseaseIconOpened);
                } else {
                    icon = new MultiIcon(diseaseIcon);
                }
            }
            if ((serrenCache.inCache() && getSpecificDiagnosis() == null)) {
                icon.addIcon(haveNotSpecificDiagnosesIcon);
            }else if (mKB10Item == null){
                icon.addIcon(haveNotSpecificDiagnosesIcon);
            }
            return icon;
        } catch (ClipsException ex) {
            ex.printStackTrace();
            if (icon == null) {
                return new MultiIcon(diseaseIcon);
            } else {
                return icon;
            }
        }
    }

    @Override
    protected String getBeanName() {
        return DiseaseBean.class.getSimpleName();
    }
   
    /**
     * Возвращает списог услуг в данном заболевании
     * @return
     * @throws ClipsException
     */
    public List<SerRenLocal> getSerrenList() throws ClipsException{
        return serrenCache.get();
    }
   
    public void clearSerrenCache() {
        serrenCache.clearCache();
    }

    private class SerrenCache extends ChildrenListStateless<SerRenLocal, ServiceRenderDetails> {
        public SerrenCache(ExtraDataManager contaner) {
            super(contaner);
        }
       
        @Override
        protected List<SerRenLocal> initNew() {
            return new ArrayList<SerRenLocal>();
        }

        @Override
        protected SerRenLocal createDelegate(ServiceRenderDetails d) throws Exception {
            return new SerRenLocal(DiseaseLocal.this, d, getAuditListener());
        }

        @Override
        protected List<ServiceRenderDetails> initDetails() throws Exception {
            return getBean().getServiceRenders();
        }
    }

    private class DECMedexam extends DelegateSecondaryCacheDgt<MedexamLocal> {
        DiseaseLocal sst;

        public DECMedexam(DiseaseLocal sst) throws ClipsException {
            super(sst.getSCM(), true, "информацию о медосмотре");
            this.sst = sst;
        }

        @Override
        protected MedexamLocal init() throws Exception {
            MedexamDetails details = sst.getBean().getMedexam();
            if (details == null) {
                return null;
            } else {
                return new MedexamLocal(sst, details, getAuditListener());
            }
        }

        @Override
        protected void setPrimary(MedexamLocal medexamLocal) throws ClipsException {
            if (medexamLocal != null) {
                throw new ClipsException("Некорректный вызов функции");
            }
        }

    }

    public ArrayList<DirectoryCollaboratorFunctionsItem> getCollabsIn() throws ClipsException {
        ArrayList<DirectoryCollaboratorFunctionsItem> collabs = new ArrayList<DirectoryCollaboratorFunctionsItem>();
        SerRenLocal serRenLocal;
        for (int i = 0; i < getSerrenList().size(); i++) {
            serRenLocal = getSerrenList().get(i);
            if (serRenLocal.isRendered()) {
                if (!collabs.contains(serRenLocal.getCollaboratorFunctions())) {
                    collabs.add(serRenLocal.getCollaboratorFunctions());
                }
            }
        }
        return collabs;
    }

    public ArrayList<SerRenLocal> getSerRensByCollab(DirectoryCollaboratorFunctionsItem collab) throws ClipsException {
        ArrayList<SerRenLocal> serRens = new ArrayList<SerRenLocal>();
        for (int i = 0; i < getSerrenList().size(); i++) {
            SerRenLocal serRen = getSerrenList().get(i);
            if (serRen.isRendered() && serRen.getCollaboratorFunctions().getID() == collab.getID()) {
                serRens.add(serRen);
            }
        }
        return serRens;
    }

    public DiagnosisLocal getDiagsByType(ArrayList<SerRenLocal> serrens, int diagType) throws ClipsException {
        DiagnosisLocal res = null;
        for (int i = 0; i < serrens.size(); i++) {
            for (DiagnosisLocal diag : serrens.get(i).getDiagnosisList()) {
                if (diag.getType().getID() == diagType) {
                    if (res == null || res.getDate().before(diag.getDate())) {
                        res = diag;
                    }
                }
            }
        }
        return res;
    }

    public SicklistLocal getSickListState(ArrayList<SerRenLocal> serrens) throws ClipsException {
        Set<Integer> serIds = new HashSet<Integer>();
        for (SerRenLocal serren : serrens) {
            serIds.add(serren.getID());
        }
        SicklistDetails details = getBean().getSickListData(serIds);
        if (details == null) {
            return null;
        }
        return new SicklistLocal(details, getAuditListener());
    }


    public void formPrintFields(DirectoryCollaboratorFunctionsItem collab) throws ClipsException {
        ClientLocal client = getEmcLocal().getClient();
        DiseaseFolluwupPrintInfo printInfo = getPrintInfo();
        DirectoryMKB10 mKB10 = DirectoryLocator.getDirectory(DirectoryMKB10.class);

        ArrayList<SerRenLocal> serrensInTap = getSerRensByCollab(collab);

        data = new HashMap<String, Object>();

        String emcNum = getEmcLocal().getClient().getNumberEmc();
        if (emcNum != null) {
            data.put("emc_code", emcNum);
        }
        data.put("tap_date", Converter.dateToString(getCreated(), "dd.MM.yy"));

        DirectoryDistrictItem dist = client.getDistrict();
        if (dist != null && dist.getID() != 0) {
            String district = dist.getTitle();
            data.put("pacient_district", district);
        }
        String snils = client.getSnils();
        if (snils != null) {
            data.put("pacient_snils", snils);
        }

        ClientExemptionData chunk = client.getExemption();
        if (chunk != null) {
            DirectoryExcemptionItem exemp = chunk.getExemption();
            if (exemp != null && exemp.getID() != 0) {
                data.put("exemption_code", exemp.getExtKey());
            }
        }

        data.put("pacient_fio", client.toString());
        data.put("pacient_sex", client.getSex().getID());
        String bornDate = Converter.dateToString(client.getBorn());
        data.put("pacient_born_date", bornDate.isEmpty() ? "          " : bornDate);

        ClientLocal representative = null;
        if (client.getPolisOMS().getNumber().equals(Polis.FICTIVE_POLIS_NUMBER)) {
            representative = client.getRepresentative();
        }

        ClientDocumentData doc;
        PolisData polis;
        if (representative != null) {
            data.put("representative_surname", representative.getSurname().getTitle());
            data.put("representative_name", representative.getName().getTitle());
            data.put("representative_patron", representative.getPathron().getTitle());
            data.put("is_representative_document", Boolean.TRUE);
            DirectoryRepresentativeStatusItem item = client.getRepresStatus();
            if (item != null) {
                data.put("representative_status", item.getID());
            }

            doc = representative.getClientDocument();
            polis = representative.getPolisOMS();
        }
        else {
            doc = client.getClientDocument();
            polis = client.getPolisOMS();
        }

        if (doc != null) {
            data.put("pacient_document_title", doc.getType().getTitle());
            String docS = doc.getSeries();
            if (docS != null) {
                data.put("pacient_document_series", docS);
            }
            docS = doc.getNumber();
            if (docS != null) {
                data.put("pacient_document_number", docS);
            }
        }
       
        if (polis != null) {
            String polisS = polis.getSeries();
            if (polisS != null) {
                data.put("polis_series", polisS);
            }
            polisS = polis.getNumber();
            if (polisS != null) {
                data.put("polis_number", polisS);
            }

            DirectoryRegionIdCodeItem regItem = polis.getRegionCode();
            if (regItem != null && regItem.getID()!=0) {
                data.put("polis_area", regItem.getRegionTitle());
            }

            DirectoryInsurerItem ins = polis.getInsurer();
            if (ins != null && ins.getID() != 0) {
                data.put("polis_insurer", ins.getTitle());
            }

            Date date = polis.getFromDate();
            if (date != null) {
                data.put("polis_begin_date", Converter.dateToString(date));
            }
            date = polis.getTillDate();
            if (date != null) {
                data.put("polis_end_date", Converter.dateToString(date));
            }

            data.put("polis_giver", "");//TODO кого сюда пихать? Парамаетр - "Кем выдан"
        }

        Address address = client.getAddress();
        if (address != null) {
            data.put("address_index", address.getZipCode() !=0 ? Integer.toString(address.getZipCode()) : "");
            data.put("address_region", address.getRegionTitle());
            data.put("address_town", address.getAreaOrCity());
            data.put("address_village", address.getVillageOrCityDistrict());
            data.put("address_village_type", address.getSettlementType() != null ?
                address.getSettlementType().getTitle() : "");
            data.put("address_street", address.getStreetTitle());
            data.put("address_street_type", address.getStreet().getType() != null ?
                address.getStreet().getType().getTitle() : "");
            data.put("building_number", Converter.getBuildingNumber(address.getBuilding()));
            data.put("building_corps", Converter.getBuildingCorpus(address.getBuilding()));
            data.put("building_letter", Converter.getBuildingLetter(address.getBuilding()));
            data.put("flat_number", address.getFlat() == null ? "" : address.getFlat());
            if (address.isCitizen() != null) {
                data.put("pacient_resident", address.isCitizen() ? CONST_1 : CONST_2);
            }
        }

        JobLocal job = client.getLastJob();
        if (job != null && job.getEnterprise() != null) {
            data.put("pacient_job", job.getEnterprise().getTitle());
        }

        if (client.getSocialStatus() != null && client.getSocialStatus().getID() != 0 ) {
            data.put("soc_stat", client.getSocialStatus().getID());
        }

        //TODO инвалидность

        //TODO вид оплаты. пока всегда ОМС
        data.put("pay_type", CONST_1);

        String collab_code = collab.getReceptionType().getExtKey();
        data.put("collaborator_code", collab_code);
        data.put("collaborator_fio", collab.getCollaborator().getTitle());
        DirectoryMedicalAidTypeItem aidTypeItem = collab.getFirstMedicalAid();
        if (aidTypeItem != null && aidTypeItem.getID() != 0) {
            data.put("medical_aid_type", aidTypeItem.getExtKey());
        }

        DirectoryServicingPlaceItem dspi = serrensInTap.get(0).getServicingPlace();
        System.out.println("SERVICING PLACE: " + dspi);
        data.put("servicing_place", dspi != null ? dspi.getID() : 0);

        if (getVisitingPurpose() != null && getVisitingPurpose().getID() != 0) {
            data.put("visiting_purpose", getVisitingPurpose().getID());
        }

        if (getDiseaseResult() != null && getDiseaseResult().getID() != 0) {
            data.put("disease_result", getDiseaseResult().getID());
        }

        ArrayList<String> serDates = new ArrayList<String>();
        ArrayList<String> serTitles = new ArrayList<String>();
        ArrayList<String> serUets = new ArrayList<String>();
        //TODO если посещение по МЭС, то УКЛ (уровень качества лечения)
        ArrayList<String> serUKLs = new ArrayList<String>();
        for (int i = 0; i < serrensInTap.size(); i++) {
            SerRenLocal serRen = serrensInTap.get(i);
            serDates.add(Converter.dateToString(serRen.getSerRenderDate(), "dd.MM.yy"));
            serTitles.add(serRen.getService().getFullCode());
            if (serRen.getCollaboratorFunctions().getReceptionType().getExtKey().contains("29")) {
                serUets.add(Double.toString(serRen.getUet()/100));
            }
        }
       
        data.put("service_dates", serDates);
        data.put("service_titles", serTitles);
        data.put("service_UKL", serUKLs);
        data.put("service_uet", serUets);

        DiagnosisLocal preliminary = getDiagsByType(serrensInTap, DiagnosisType.DIAGNOSIS_TYPE_PRELIMINARY);
        if (preliminary != null) {
            data.put("diagnosis_presumptive_code", preliminary.getMkb().getDiseaseCode());
            data.put("diagnosis_presumptive_date", Converter.dateToString(preliminary.getDate(), "dd.MM.yy"));
        }

        DiagnosisLocal specDiag = getSpecificDiagnosis();
        if (specDiag != null) { //&& finalD.getSerrenLocal().getCollaboratorFunctions().getID() == collab.getID()) {
            data.put("diagnosis_final_code", specDiag.getMkb().getDiseaseCode());
            data.put("diagnosis_final_date", Converter.dateToString(specDiag.getDate(), "dd.MM.yy"));
            data.put("diagnosis_final_encounter", specDiag.getEncounter().getID());

            data.put("followup_final", printInfo.mainFollowStage);
            data.put("followup_down_final", printInfo.mainFollowDownReason);

            if ((specDiag.getTrauma()!=null
                    && specDiag.getTrauma().getExtKey() != null)
                    && !specDiag.getTrauma().getExtKey().isEmpty()){
                data.put("trauma_type",  specDiag.getTrauma().getID());
            }

            data.put("diagnosis_associated_code_0", mKB10.getItemFromID(printInfo.attendant0DiagnosisMkbID).getDiseaseCode());
            data.put("diagnosis_associated_encounter_0", printInfo.attendant0DiagnosisEncounter);
            data.put("followup_associated_0", printInfo.attendant0FollowStage);
            data.put("followup_down_associated_0", printInfo.attendant0FollowDownReason);

            data.put("diagnosis_associated_code_1", mKB10.getItemFromID(printInfo.attendant1DiagnosisMkbID).getDiseaseCode());
            data.put("diagnosis_associated_encounter_1", printInfo.attendant1DiagnosisEncounter);
            data.put("followup_associated_1", printInfo.attendant1FollowStage);
            data.put("followup_down_associated_1", printInfo.attendant1FollowDownReason);

            DirectoryMKB10Item compl = specDiag.getComplication();
            if (compl != null && compl.getID() != 0) {
                data.put("diagnosis_complication_code", compl.getDiseaseCode());
                data.put("diagnosis_complication_encounter", client.getDiagnosisCharacter(compl, specDiag.getDate()));
            }
        }

        SicklistLocal sicklist = getSickListState(serrensInTap);
        if (sicklist != null) {
            DirectoryDisabilityTypeItem ddti = sicklist.getDisability();
            if (ddti != null && ddti.getID() != 0) {
                data.put("sicklist_reason", sicklist.getDisability().getExternalKey());
            }
            int state = 0;
            if (sicklist.isClosed()) {
                state = CONST_3;
                data.put("sicklist_close_date", Converter.dateToString(sicklist.getTill().getTime(), "dd.MM.yy"));
            }
//            else {
            if (sicklist.getProlongationCount() > 1) {
                if (state != CONST_3){
                    state = CONST_2;
                }
            }
            else {
                if (state != CONST_3){
                    state = CONST_1;
                }
                data.put("sicklist_open_date", Converter.dateToString(sicklist.getDateOpen().getTime(), "dd.MM.yy"));
            }
//            }
            data.put("sicklist_open_type", state);
            if (ddti.isDiseatedSupport()){
                data.put("sicklist_care_sex", client.getSex().getID());
                if (client.getBorn() != null) {
                    data.put("sicklist_care_age", ""+DateTimeUtils.calcAge(client.getBorn(), TimeLocal.getCurrentTime().getTime()));
                }
            }
        }
       
    }

    @Override
    public void print(CombinedReportCreator cCreator) throws ClipsException {
        FormReportCreator creater = cCreator.createFormReporter(getClass(), 1);
        creater.createReport(null, null, data.entrySet(), null);
        creater.finish();
    }
   
   
    /**
     * кеш диагноза
     */
//    private class DiagnosisCache extends DelegateExtraDataRO<DiagnosisLocal> {
//
//        public DiagnosisCache(ExtraDataManager contaner) {
//            super(contaner);
//        }
//        @Override
//        protected DiagnosisLocal init() throws Exception {
//            DiagnosisDetails dd = getBean().getSpecificDiagnosis();
//            if (dd != null) {
//                return new DiagnosisLocal(dd, new SerRenLocal(dd.serviceRenderID));
//            }
//            return null;
//        }
//    }

    @Override
    public boolean isSignCorrect() throws ClipsException{
        //STUB
        return (getID() != -1 );
        //END STUB
    }

    @Override
    public String getSignMessage() throws ClipsException {
        if (getID() == 0) {
            return "Подпись отсутствует";
        }
        //STUB
        String coll;
        if (getCollaborator() != null) {
            coll = getCollaborator().getTitle();
        } else {
            return "Подпись отсутствует";
        }

        String s = "Подписано " + Converter.dateToString(getCreated())
                + " - " + coll;
        if (isSignCorrect() ) {
            return s;
        } else {
            return "Подпись не соответствует данным!";
        }
        //END STUB
    }

    private Date getProfcheckupDate() throws ClipsException {
        if (!profcheckupDate.inCache()){
            try {
                profcheckupDate.set(getBean().getProfcheckupDate());
            } catch (Exception ex) {
                clearBean();
                profcheckupDate.set(null);
                throw new ClipsException("Не удалось получить дату профосмотра", ex);
            }
        }
        return profcheckupDate.get();
    }

    public void getPrintFormPath() throws ClipsException {
        String dirStr = ConfigLocal.getPrintFormPath();
        File dir = new File(dirStr);
        File file = new File(dir, "TAL.odt");
        if (!file.exists()) {
            throw new ClipsException("Не найден шаблон для печати");
        }
    }

}
TOP

Related Classes of clips.delegate.doctor.DiseaseLocal

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.