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.ORC;
import ca.uhn.hl7v2.model.v24.segment.PID;
import ca.uhn.hl7v2.model.v24.segment.PV1;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.web.work.domain.Patient;
import com.ruoyi.web.work.domain.Report;
import com.ruoyi.web.work.domain.Visit;
import com.ruoyi.web.work.hl7.service.HL7PatientService;
import com.ruoyi.web.work.hl7.service.HL7RequestService;
import com.ruoyi.web.work.hl7.service.HL7ReportService;
import com.ruoyi.web.work.hl7.service.HL7VisitService;
import com.ruoyi.web.work.mapper.ReportMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;

/**
 * 检查检测微生物报告单
 */
@Service
@Log4j2
@Transactional
public class HL7ReportServiceImpl extends ServiceImpl<ReportMapper, Report> implements HL7ReportService {

    @Autowired
    private HL7PatientService patientService;

    @Autowired
    private HL7VisitService visitService;

    @Autowired
    private HL7RequestService obrService;

    /**
     * 保存患者报告的检验数据
     * @param oruR01
     */
    @Override
    public void savePatientReport(ORU_R01 oruR01) throws HL7Exception, ParseException {
        //ORC段
        ORC orc = oruR01.getPATIENT_RESULT().getORDER_OBSERVATION().getORC();
        PV1 pv1 = oruR01.getPATIENT_RESULT().getPATIENT().getVISIT().getPV1();
        PID pid = oruR01.getPATIENT_RESULT().getPATIENT().getPID();
        String cardId = pv1.getVisitNumber().getID().getValue(); //推送过来的数据就诊卡号
        String wnPatId = pid.getPatientID().getID().getValue(); //卫宁患者ID
        String inspectionDeptName = orc.getOrderingFacilityName(0).getOrganizationName().getValue();//送检科室
        //根据卫宁患者标识符查询患者是否存在
        Patient entity = patientService.findPatientByWnPatId(wnPatId);
        if (entity != null){
            Long patId = entity.getId();//患者ID
            //根据患者id和送检科室查询是否本次就诊的报告
            Visit visitEntity = visitService.findVisitByPatIdAndDeptName(patId,inspectionDeptName);
            if (visitEntity != null){
                Long visitId = visitEntity.getId(); //就诊ID
                //根据就诊id查询申请报告单表 如果当前报告存在更新
                LambdaQueryWrapper<Report> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Report::getVisitId,visitId);
                Report orcReportEntity = baseMapper.selectOne(queryWrapper);
                if (orcReportEntity != null){
                    //报告存在,更新报告单表orc
                    log.info("开始更新报告单表>>>>>更新成功!");
                    //更新检查项目表obr
                    log.info("开始更新检查项目表>>>>>更新成功!");
                    //更新结果表obx
                    log.info("开始更新结果表>>>>>更新成功!");
                }else {
                    //保存本次就诊记录的检查报告orc
                    log.info("保存患者当前就诊的检查报告:{}",visitId);
                    Long orcId = this.saveReport(patId,visitEntity.getCardId(),orc,visitId);
                    //保存当前患者请求报告obr
                    obrService.saveRequestReportObr(oruR01,orcId);
                    log.info("保存当前存在的患者报告单完成!");
                }
            }
        }else {
            //保存当前没有患者的检查报告
            //保存申请报告单orc
            Long obcId = this.saveReport(null, Long.valueOf(cardId), orc,null);
            //保存请求报告obr
            obrService.saveRequestReportObr(oruR01,obcId);
            log.info("保存当前没有的患者报告单完成!");
        }
    }

    //保存患者的ORC报告单
    private Long saveReport(Long pid,Long cardId, ORC orc,Long visitId) {
        String reportNo = orc.getPlacerOrderNumber().getEntityIdentifier().getValue();//报告单号
        String originalApplicationNo = orc.getPlacerOrderNumber().getUniversalID().getValue();//原始申请号
        String orderNo = orc.getFillerOrderNumber().getEntityIdentifier().getValue();//医技单号
        String reportClassCode = orc.getPlacerGroupNumber().getEntityIdentifier().getValue();//报告单类别代码
        String reportClassName = orc.getPlacerGroupNumber().getUniversalID().getValue();//报告单类别名称
        String checkDoctorCode = orc.getEnteredBy(0).getIDNumber().getValue();//送检医生信息代码
        String applyDoctorName = orc.getEnteredBy(0).getGivenName().getValue();//申请医生信息
        String testingDoctorCode = orc.getActionBy(0).getIDNumber().getValue();//检验医生代码
        String testingDoctorName = orc.getActionBy(0).getGivenName().getValue();//检验医生名称
        String inspectionDepartmentName = orc.getOrderingFacilityName(0).getOrganizationName().getValue();//送检科室
        String applicationDepartmentCode = orc.getOrderingFacilityName(0).getNameRepresentationCode().getValue();//申请科室代码
        Report orcReportEntity = new Report();
        orcReportEntity.setReportNo(reportNo);
        orcReportEntity.setOriginalApplicationNo(originalApplicationNo);
        orcReportEntity.setOrderNo(orderNo);
        orcReportEntity.setReportClassCode(reportClassCode);
        orcReportEntity.setReportClassName(reportClassName);
        orcReportEntity.setCheckDoctorCode(checkDoctorCode);
        orcReportEntity.setApplyDoctorName(applyDoctorName);
        orcReportEntity.setTestingDoctorCode(testingDoctorCode);
        orcReportEntity.setTestingDoctorName(testingDoctorName);
        orcReportEntity.setInspectionDepartmentCode(applicationDepartmentCode);
        orcReportEntity.setInspectionDepartmentName(inspectionDepartmentName);
        orcReportEntity.setCardId(cardId);
        orcReportEntity.setPatId(pid);
        orcReportEntity.setVisitId(visitId);
        baseMapper.insert(orcReportEntity);
        return orcReportEntity.getId();
    }
}
