package com.docus.server.report.webservice.impl;

import com.docus.core.util.DateUtil;
import com.docus.core.util.Func;
import com.docus.infrastructure.core.exception.BaseException;
import com.docus.server.report.api.dto.ReportDto;
import com.docus.server.report.config.ZdAssortConfig;
import com.docus.server.report.service.ReportService;
import com.docus.server.report.util.IdUtil;
import com.docus.server.report.util.XmlUtil;
import com.docus.server.report.webservice.WebserviceMessageType;
import com.docus.server.report.webservice.WebserviceReceiveServerHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.w3c.dom.Node;

import javax.annotation.Resource;
import java.util.Date;

/**
 * HIP1009-检查报告更新服务
 *
 * @author jiahsi
 */
@Service(WebserviceMessageType.HIP1011)
@Slf4j
public class HIP1011LaboratoryReportUpdatesHandler implements WebserviceReceiveServerHandler {
    @Resource
    private ReportService reportService;

    @Override
    public String handle(String receiveMessage) {
        log.info("收到检验报告更新消息{}", receiveMessage);
        String msgId = "";
        String sender = "";
        String receiver = "";
        try {
            XmlUtil xmlUtil = XmlUtil.of(receiveMessage);
            msgId = xmlUtil.getNode("/PRPA_HIP1011/id/@extension").getNodeValue();
            sender = xmlUtil.getNode("/PRPA_HIP1011/sender/device/id/item/@extension").getNodeValue();
            receiver = xmlUtil.getNode("/PRPA_HIP1011/receiver/device/id/item/@extension").getNodeValue();
            ReportDto reportDto = getReportDtoByLaboratoryUpdate(xmlUtil);
            verifyReportDto(reportDto);
            reportService.report(reportDto);
            return updateSuccess(msgId, sender, receiver);
        } catch (BaseException baseException) {
            log.error(baseException.getMessage(), baseException);
            return updateFailed(msgId, sender, receiver, baseException.getMessage());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return updateFailed(msgId, sender, receiver, "系统错误");
        }
    }

    public static ReportDto getReportDtoByLaboratoryUpdate(XmlUtil xmlUtil) {
        Node senderNode = xmlUtil.getNode("/PRPA_HIP1011/sender/device/id/item/@extension");
        String sender = senderNode.getNodeValue();
        String zdAssortId = ZdAssortConfig.getZdAssortId(sender);
        if (Func.isBlank(zdAssortId)) {
            zdAssortId = ZdAssortConfig.getOtherAssortId();
        }

        Node inpatientNoNode = xmlUtil.getNode("/PRPA_HIP1011/controlActProcess/subject/encounterEvent/inpNo");
        String inpatientNoNodeTextContent = inpatientNoNode.getTextContent();
        String inpatientNo = Func.isBlank(inpatientNoNodeTextContent) ? "-1" : inpatientNoNodeTextContent;

        Node admissTimesNode = xmlUtil.getNode("/PRPA_HIP1011/controlActProcess/subject/encounterEvent/visitId");
        String admissTimesNodeTextContent = admissTimesNode.getTextContent();
        Integer admissTimes = Func.isBlank(admissTimesNodeTextContent) ? -1 : Integer.parseInt(admissTimesNodeTextContent);

        // 检查报告单号标识
        Node reportFlagNode = xmlUtil.getNode("/PRPA_HIP1011/controlActProcess/subject/encounterEvent/id[@root='2.16.156.10011.1.33']/@extension");
        String reportFlag = reportFlagNode.getNodeValue();
        //电子申请单编号
        Node eafNoNode = xmlUtil.getNode("/PRPA_HIP1011/controlActProcess/subject/encounterEvent/id[@root='2.16.156.10011.1.24']/@extension");
        String eafNo = eafNoNode.getNodeValue();
        String serialnum = reportFlag + "@" + eafNo;


        Node fileTitleNode = xmlUtil.getNode("/PRPA_HIP1011/controlActProcess/subject/encounterEvent/labReportName/@value");
        String fileTitle = fileTitleNode.getNodeValue();

        Node downUrlNode = xmlUtil.getNode("/PRPA_HIP1011/controlActProcess/subject/encounterEvent/component/structuredBody/component/section/entry/observationMedia/value");
        String downUrl = downUrlNode.getTextContent();

        ReportDto reportDto = new ReportDto();
        reportDto.setReportSn(reportFlag);
        reportDto.setAdmisstimes(admissTimes);
        reportDto.setInpatientNo(inpatientNo);
        reportDto.setSerialnum(serialnum);
        reportDto.setFileTitle(fileTitle);
        reportDto.setDownUrl(downUrl);
        reportDto.setAssortId(zdAssortId);
        reportDto.setSysFlag(sender);
        reportDto.setFileSource("1");
        reportDto.setFilestoragetype("1");
        return reportDto;
    }


    /**
     * 返回检查报告更新成功响应消息
     *
     * @param msgId    消息id
     * @param sender   发送路由
     * @param receiver 接收路由
     * @return 更新成功响应消息
     */
    public String updateSuccess(String msgId, String sender, String receiver) {
        String createTime = Func.format(new Date(), DateUtil.PATTERN_DATETIME_MINI);

        return "<MCCI_IN000002UV01 xmlns=\"urn:hl7-org:v3\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ITSVersion=\"XML_1.0\" xsi:schemaLocation=\"urn:hl7-org:v3  file:///E:/hl7/HL7/v3ballot_fullsite_2011MAY/v3ballot/html/processable/multicacheschemas/MCCI _IN000002UV01.xsd\">" +
                "<id extension=\"" + IdUtil.standardUUID() + "\"/>" +
                "<creationTime value=\"" + createTime + "\"/>" +
                "<interactionId root=\"2.16.840.1.113883.1.6\" extension=\"MCCI_IN000002UV01\"/>" +
                "<processingCode code=\"P\"/>" +
                "<processingModeCode/>" +
                "<acceptAckCode code=\"AL\"/>" +
                "<receiver typeCode=\"RCV\">" +
                "<device classCode=\"DEV\" determinerCode=\"INSTANCE\">" +
                "<id>" +
                "<item extension=\"Orion-001\"/>" +
                "</id>" +
                "</device>" +
                "</receiver>" +
                "<sender typeCode=\"SND\">" +
                "<device classCode=\"DEV\" determinerCode=\"INSTANCE\">" +
                "<id>" +
                "<item extension=\"PaperlessManagementMRIS-001\"/>" +
                "</id>" +
                "</device>" +
                "</sender>" +
                "<acknowledgement typeCode=\"AA\">" +
                "<targetMessage>" +
                "<id extension=\"" + msgId + "\"/>" +
                "</targetMessage>" +
                "<acknowledgementDetail>" +
                "<text value=\"成功\"/>" +
                "</acknowledgementDetail>" +
                "</acknowledgement>" +
                "</MCCI_IN000002UV01>";
    }

    /**
     * 检查报告更新失败响应
     *
     * @param msgId         消息id
     * @param sender        发送路由
     * @param receiver      接收路由
     * @param failedMessage 失败信息
     * @return 更新失败响应信息
     */
    public String updateFailed(String msgId, String sender, String receiver, String failedMessage) {
        String createTime = Func.format(new Date(), DateUtil.PATTERN_DATETIME_MINI);
        return "<MCCI_IN000002UV01 xmlns=\"urn:hl7-org:v3\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ITSVersion=\"XML_1.0\" xsi:schemaLocation=\"urn:hl7-org:v3  file:///E:/hl7/HL7/v3ballot_fullsite_2011MAY/v3ballot/html/processable/multicacheschemas/MCCI _IN000002UV01.xsd\">" +
                "<id extension=\"" + IdUtil.standardUUID() + "\"/>" +
                "<creationTime value=\"" + createTime + "\"/>" +
                "<interactionId root=\"2.16.840.1.113883.1.6\" extension=\"MCCI_IN000002UV01\"/>" +
                "<processingCode code=\"P\"/>" +
                "<processingModeCode/>" +
                "<acceptAckCode code=\"AL\"/>" +
                "<receiver typeCode=\"RCV\">" +
                "<device classCode=\"DEV\" determinerCode=\"INSTANCE\">" +
                "<id>" +
                "<item extension=\"Orion-001\"/>" +
                "</id>" +
                "</device>" +
                "</receiver>" +
                "<sender typeCode=\"SND\">" +
                "<device classCode=\"DEV\" determinerCode=\"INSTANCE\">" +
                "<id>" +
                "<item extension=\"PaperlessManagementMRIS-001\"/>" +
                "</id>" +
                "</device>" +
                "</sender>" +
                "<acknowledgement typeCode=\"AE\">" +
                "<targetMessage>" +
                "<id extension=\"" + msgId + "\"/>" +
                "</targetMessage>" +
                "<acknowledgementDetail>" +
                "<text value=\"" + failedMessage + "\"/>" +
                "</acknowledgementDetail>" +
                "</acknowledgement>" +
                "</MCCI_IN000002UV01>";
    }


}
