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

import com.docus.core.util.Func;
import com.docus.infrastructure.core.exception.BaseException;
import com.docus.server.api.HospitalSubmitNodeServiceApi;
import com.docus.server.api.dto.HospitalSubmitNodeLogAddDTO;
import com.docus.server.api.enums.HospitalSubmitNodeEnum;
import com.docus.server.collection.mapper.TBasicMapper;
import com.docus.server.report.api.dto.ReportDto;
import com.docus.server.report.config.SystemAssortConfig;
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;
import java.util.List;

/**
 * 重症症接收
 *
 * @author wyb
 */
@Service(WebserviceMessageType.ICU)
@Slf4j
public class JsIcuReportHandler implements WebserviceReceiveServerHandler {
    @Resource
    private ReportService reportService;
    @Resource
    private TBasicMapper tBasicMapper;
    @Resource
    private HospitalSubmitNodeServiceApi hospitalSubmitNodeServiceApi;

    @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);
            setAssortId(reportDto);
            reportService.report(reportDto);
            saveSubmitNodeLog(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, "系统故障！");
        }
    }

    /**
     * 从配置额外重新设置分段id
     *
     * @param reportDto 上报文件信息
     */
    private void setAssortId(ReportDto reportDto) {
        SystemAssortConfig systemAssortConfig = SystemAssortConfig.getSystemAssortConfig(reportDto.getSysFlag());
        if (systemAssortConfig == null) {
            return;
        }
        String fileTitle = reportDto.getFileTitle();
        // 有配置，没有配置其他的条件，取默认
        SystemAssortConfig.Assort configAssort = systemAssortConfig.getAssort();
        String assortId = configAssort.getDefaultAssortId();
        List<SystemAssortConfig.AssortObj> configAssortOther = configAssort.getOther();
        if (configAssortOther != null) {
            // 有配置其它的，匹配文件标题
            for (SystemAssortConfig.AssortObj assortObj : configAssortOther) {
                if (Func.isNotBlank(assortObj.getTitle()) && fileTitle.contains(assortObj.getTitle())) {
                    assortId = assortObj.getAssortId();
                    break;
                }
            }
        }
        reportDto.setAssortId(assortId);
    }

    public static void main(String[] args) {
        JsIcuReportHandler icuReportHandler = new JsIcuReportHandler();
        ReportDto reportDto = new ReportDto();
        reportDto.setSysFlag("icu");
        reportDto.setFileTitle("血气哈哈哈");
        reportDto.setAssortId("1008611");
        icuReportHandler.setAssortId(reportDto);
        System.out.println(reportDto);
    }

    private void saveSubmitNodeLog(ReportDto reportDto) {
        try {
            // 如果出现多条出错的情况，还是得保存收到的信息，人工干预处理
            String patientId = tBasicMapper.getPatientIdByInpatientNoAndAdminssTimes(reportDto.getInpatientNo(), reportDto.getAdmisstimes());
            if (Func.isNotBlank(patientId)) {
                HospitalSubmitNodeLogAddDTO dto = new HospitalSubmitNodeLogAddDTO();
                dto.setPatientId(patientId);
                dto.setContent(new String[]{reportDto.getFileTitle()});
                dto.setCreaterName("重症提交");
                dto.setCreater("重症提交");
                dto.setSubmitNodeEnum(HospitalSubmitNodeEnum.ICU);
                hospitalSubmitNodeServiceApi.addLog(dto);
            }
        } catch (Exception ex) {
            log.error("保存icu提交记录出错，病案号：" + reportDto.getInpatientNo() + " ，住院次数：" + reportDto.getAdmisstimes(), ex);
        }

    }
}
