package com.ruoyi.web.work.hl7.service.impl;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.v24.message.ORU_R01;
import ca.uhn.hl7v2.model.v24.segment.OBR;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.web.work.hl7.util.DateTimeConverter;
import com.ruoyi.web.work.domain.Request;
import com.ruoyi.web.work.hl7.service.HL7RequestService;
import com.ruoyi.web.work.hl7.service.HL7ResultService;
import com.ruoyi.web.work.mapper.RequestMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 检查检测微生物项目
 */
@Service
@Transactional
@Log4j2
public class HL7RequestServiceImpl extends ServiceImpl<RequestMapper, Request> implements HL7RequestService {

    @Autowired
    HL7ResultService obxService;

    /**
     * 保存当前患者请求报告obr
     *
     * @param
     * @param oruR01
     */
    @Override
    public void saveRequestReportObr(ORU_R01 oruR01, Long obcId) throws HL7Exception {
        // 提取OBR段的信息
        OBR obr = oruR01.getPATIENT_RESULT().getORDER_OBSERVATION().getOBR();
        if (obr.isEmpty()) {
            return;
        }

        // 初始化ObrEntity对象
        Request obrEntity = new Request();

        // 提取并设置医技项目名称
        String medTechProName = obr.getUniversalServiceIdentifier().getIdentifier().getValue();
        if ("MR".equals(obr.getUniversalServiceIdentifier().getNameOfAlternateCodingSystem().getValue()) ||
                "CT".equals(obr.getUniversalServiceIdentifier().getNameOfAlternateCodingSystem().getValue()) ||
                "CC".equals(obr.getUniversalServiceIdentifier().getNameOfAlternateCodingSystem().getValue()) ||
                "DX".equals(obr.getUniversalServiceIdentifier().getNameOfAlternateCodingSystem().getValue()) ||
                "DSA".equals(obr.getUniversalServiceIdentifier().getNameOfAlternateCodingSystem().getValue())) {
            // 如果报告单类别名称是特定值之一，则使用它作为医技项目名称
            medTechProName = obr.getUniversalServiceIdentifier().getNameOfAlternateCodingSystem().getValue();
        }
        obrEntity.setMedTechProName(medTechProName);

        // 提取并设置其他字段
        obrEntity.setReportClass(obr.getUniversalServiceIdentifier().getNameOfAlternateCodingSystem().getValue());
        String reportCompleteTime = obr.getObservationDateTime().getTimeOfAnEvent().getValue();
        obrEntity.setReportCompleteTime(DateTimeConverter.convertToUnifiedFormat(reportCompleteTime));
        obrEntity.setSigns(obr.getDangerCode().getIdentifier().getValue());
        String sampleReceivedDate = obr.getSpecimenReceivedDateTime().getTimeOfAnEvent().getValue();
        obrEntity.setSampleReceivedDate(DateTimeConverter.convertToUnifiedFormat(sampleReceivedDate));
        obrEntity.setCheckpoint(obr.getSpecimenSource().getBodySite().getIdentifier().getValue());
        obrEntity.setExecuteDepartmentCode(obr.getFillerField1().getValue());
        obrEntity.setExecuteDepartmentName(obr.getFillerField2().getValue());
        obrEntity.setIsFlag(obr.getResultStatus().getValue());
        obrEntity.setReviewDoctorCode(obr.getPrincipalResultInterpreter().getOPName().getIDNumber().getValue());
        obrEntity.setReviewDoctorName(obr.getPrincipalResultInterpreter().getOPName().getGivenName().getValue());
        String reportDate = obr.getScheduledDateTime().getTimeOfAnEvent().getValue();
        obrEntity.setReportDate(DateTimeConverter.convertToUnifiedFormat(reportDate));
        obrEntity.setReportNo(obr.getPlacerSupplementalServiceInformation(0).getIdentifier().getValue());
        obrEntity.setOrcId(obcId);

        try {
            // 保存检查项目obr
            baseMapper.insert(obrEntity);
            log.info("保存检查项目obr完成!");

            Long obrId = obrEntity.getId();

            // 保存请求报告结果obx
            obxService.saveReportResult(obrId, oruR01);
        } catch (Exception e) {
            // 记录错误日志
            log.error("保存检查项目obr或结果obx失败: ", e);
            throw new RuntimeException("保存失败", e);
        }
    }
}
