package com.openhis.web.doctorstation.utils;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.core.common.exception.ServiceException;
import com.core.common.utils.AgeCalculatorUtil;
import com.openhis.administration.domain.Organization;
import com.openhis.administration.domain.Patient;
import com.openhis.administration.domain.Practitioner;
import com.openhis.administration.service.IOrganizationService;
import com.openhis.administration.service.IPatientService;
import com.openhis.administration.service.IPractitionerService;
import com.openhis.common.enums.ActivityType;
import com.openhis.common.enums.AdministrativeGender;
import com.openhis.crosssystem.dto.LisApplyDto;
import com.openhis.crosssystem.dto.LisApplyGroupDto;
import com.openhis.crosssystem.dto.PacsApplyDto;
import com.openhis.crosssystem.enums.*;
import com.openhis.crosssystem.utils.CrossSystemSendApplyUtil;
import com.openhis.web.doctorstation.dto.AdviceSaveDto;
import com.openhis.workflow.domain.ActivityDefinition;
import com.openhis.workflow.domain.ServiceRequest;
import com.openhis.workflow.service.IActivityDefinitionService;
import com.openhis.workflow.service.IServiceRequestService;

import lombok.extern.slf4j.Slf4j;

/**
 * 跨系统发送申请工具类
 *
 * @author Thanking
 * @date 2025-06-27
 */
@Slf4j
@Component
public class DoctorStationSendApplyUtil {

    @Autowired
    private CrossSystemSendApplyUtil crossSystemSendApplyUtil;
    @Autowired
    private IActivityDefinitionService activityDefinitionService;
    @Autowired
    private IOrganizationService organizationService;
    @Autowired
    private IServiceRequestService serviceRequestService;
    @Autowired
    private IPatientService patientService;
    @Autowired
    private IPractitionerService practitionerService;

    /**
     * 发送跨系统申请
     *
     * @param adviceSaveDto 申请参数
     * @param organizationId 科室ID
     * @param curDate 当前时间
     */
    public void sendCrossSystemApply(AdviceSaveDto adviceSaveDto, Long organizationId, Date curDate) {
        // 查询诊疗定义
        ActivityDefinition activityDefinition =
            activityDefinitionService.getById(adviceSaveDto.getAdviceDefinitionId());
        if (activityDefinition == null) {
            throw new ServiceException("发起LIS或PACS请求失败：诊疗信息不存在");
        }
        // 查询挂号科室
        Organization organization = organizationService.getById(organizationId);
        if (organization == null) {
            throw new ServiceException("发起LIS或PACS请求失败：挂号科室信息不存在");
        }
        // 查询服务请求
        ServiceRequest serviceRequest = serviceRequestService.getById(adviceSaveDto.getRequestId());
        if (serviceRequest == null) {
            throw new ServiceException("发起LIS或PACS请求失败：服务请求信息不存在");
        }
        // 查询患者
        Patient patient = patientService.getById(adviceSaveDto.getPatientId());
        if (patient == null) {
            throw new ServiceException("发起LIS或PACS请求失败：患者信息不存在");
        }
        // 查询开方医生
        Practitioner practitioner = practitionerService.getById(adviceSaveDto.getPractitionerId());
        if (practitioner == null) {
            throw new ServiceException("发起LIS或PACS请求失败：开方医生信息不存在");
        }
        // 查询执行科室
        Organization organizationExec = organizationService.getById(adviceSaveDto.getPositionId());
        if (organizationExec == null) {
            throw new ServiceException("发起LIS或PACS请求失败：执行科室信息不存在");
        }

        // 检验，发送LIS申请
        if (ActivityType.PROOF.getValue().equals(activityDefinition.getTypeEnum())) {
            // LIS性别转换
            LisPatientSex lisPatientSex;
            if (patient.getGenderEnum() == null) {
                lisPatientSex = LisPatientSex.UNKNOWN;
            } else {
                if (AdministrativeGender.MALE.getValue().equals(patient.getGenderEnum())) {
                    lisPatientSex = LisPatientSex.MALE;
                } else if (AdministrativeGender.FEMALE.getValue().equals(patient.getGenderEnum())) {
                    lisPatientSex = LisPatientSex.FEMALE;
                } else {
                    lisPatientSex = LisPatientSex.UNKNOWN;
                }
            }
            // 作成LIS申请参数
            LisApplyDto lisApplyDto = new LisApplyDto().setApplyNo(serviceRequest.getBusNo())
                .setPatientNo(patient.getBusNo()).setPatientType(LisPatientType.OUTPATIENT)
                .setPatientName(patient.getName()).setPatientSex(lisPatientSex).setPatientMobile(patient.getPhone())
                .setApplyDate(curDate).setApplyDoctor(practitioner.getName()).setApplyDept(organization.getName())
                .setAge(AgeCalculatorUtil.calculateAge(patient.getBirthDate()))
                .setExecDeptCode(organizationExec.getBusNo()).setExecDeptName(organizationExec.getName())
                .setIdCard(patient.getIdCard()).setWardId("").setRoomNo("").setBedNo("").setEmergency("")
                .setDiagnose("").setOutsideFlg(LisOutsideFlg.NO).setApplyDeptCode(organization.getBusNo())
                .setApplyDeptName(organization.getName()).setGroupList(List.of(new LisApplyGroupDto()
                    .setGroupCode(activityDefinition.getBusNo()).setGroupName(activityDefinition.getName())));
            // 发送LIS申请
            crossSystemSendApplyUtil.sendApplyToLis(lisApplyDto);

            // 检查，发送PACS申请
        } else if (ActivityType.TEST.getValue().equals(activityDefinition.getTypeEnum())) {
            // PACS性别转换
            PacsPatientSex pacsPatientSex;
            if (patient.getGenderEnum() == null) {
                pacsPatientSex = PacsPatientSex.UNKNOWN;
            } else {
                if (AdministrativeGender.MALE.getValue().equals(patient.getGenderEnum())) {
                    pacsPatientSex = PacsPatientSex.MALE;
                } else if (AdministrativeGender.FEMALE.getValue().equals(patient.getGenderEnum())) {
                    pacsPatientSex = PacsPatientSex.FEMALE;
                } else {
                    pacsPatientSex = PacsPatientSex.UNKNOWN;
                }
            }
            // 作成PACS申请参数
            PacsApplyDto pacsApplyDto =
                new PacsApplyDto().setApplyNo(serviceRequest.getBusNo()).setPatientNo(patient.getBusNo())
                    .setPatientType(PacsPatientType.OUTPATIENT).setPatientName(patient.getName())
                    .setPatientSex(pacsPatientSex).setPatientMobile(patient.getPhone()).setApplyDate(curDate)
                    .setApplyDoctorName(practitioner.getName()).setApplyDoctorCode(practitioner.getBusNo())
                    .setApplyDeptName(organization.getName()).setApplyDeptCode(organization.getBusNo())
                    .setAge(AgeCalculatorUtil.calculateAge(patient.getBirthDate()))
                    .setExecDeptCode(organizationExec.getBusNo()).setExecDeptName(organizationExec.getName())
                    .setExamPart("").setIdCard(patient.getIdCard()).setWardId("").setRoomNo("").setBedNo("")
                    .setEmergency("").setDiagnose("").setGroupCode(activityDefinition.getBusNo())
                    .setGroupName(activityDefinition.getName());
            // 发送PACS申请
            crossSystemSendApplyUtil.sendApplyToPacs(pacsApplyDto);
        }
    }
}
