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

import com.docus.infrastructure.core.exception.BaseException;
import com.docus.server.report.api.dto.ReportDto;
import com.docus.server.report.service.ReportService;
import com.docus.server.report.util.JSXMLResult;
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;

/**
 * 检验报告接收
 *
 * @author wyb
 */
@Service(WebserviceMessageType.LABORATORY)
@Slf4j
public class JsLaboratoryReportHandler implements WebserviceReceiveServerHandler {
    @Resource
    private ReportService reportService;

    @Override
    public String handle(String receiveMessage) {
        log.info("收到检验报告消息：{}", receiveMessage);
        String msgId = "";
        try {
            XmlUtil xmlUtil = XmlUtil.of(receiveMessage);
            Node msgNode = xmlUtil.getNode("/Request/Msg/ID");
            msgId = msgNode.getTextContent();
            ReportDto reportDto =   convert(xmlUtil);
            verifyReportDto(reportDto);
            reportService.report(reportDto);
            return JSXMLResult.success(msgId);
        } catch (BaseException baseException) {
            log.error(baseException.getMessage(), baseException);
            return JSXMLResult.failed(msgId, baseException.getMessage());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return JSXMLResult.failed(msgId, "系统故障！");
        }
    }
}
