package com.openhis.clinical.service.impl;

import com.openhis.common.enums.ClinicalStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.openhis.clinical.domain.AllergyIntolerance;
import com.openhis.clinical.mapper.AllergyIntoleranceMapper;
import com.openhis.clinical.service.IAllergyIntoleranceService;
import com.openhis.common.enums.VerificationStatus;
import com.openhis.workflow.mapper.ServiceRequestMapper;

/**
 * 过敏与不耐受Service业务层处理
 *
 * @author system
 * @date 2025-03-07
 */
@Service
public class AllergyIntoleranceServiceImpl extends ServiceImpl<AllergyIntoleranceMapper, AllergyIntolerance>
    implements IAllergyIntoleranceService {

    @Autowired
    ServiceRequestMapper serviceRequestMapper;

    /**
     * 更新或者保存过敏与不耐受
     *
     * @param allergyIntolerance 过敏与不耐受实体
     */
    @Override
    public boolean saveOrUpdateAllergyIntolerance(AllergyIntolerance allergyIntolerance) {

        // 创建 LambdaQueryWrapper
        LambdaQueryWrapper<AllergyIntolerance> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AllergyIntolerance::getId, allergyIntolerance.getId()).eq(AllergyIntolerance::getPatientId,
            allergyIntolerance.getPatientId());

        // 查询是否存在记录
        AllergyIntolerance existingEncounter = baseMapper.selectOne(queryWrapper);
        if (existingEncounter != null) {
            // 如果记录存在，更新记录
            allergyIntolerance.setId(existingEncounter.getId()); // 设置主键
            return baseMapper.updateById(allergyIntolerance) > 0;
        } else {
            // 如果记录不存在，插入新记录
            return baseMapper.insert(allergyIntolerance) > 0;
        }
    }

    /**
     * 根据药品请求id,获取皮试结果
     *
     * @param serviceRequestId 服务请求id
     * @return 皮试结果
     */
    @Override
    public Integer getPsResultByRequestId(Long serviceRequestId) {

        // 创建 LambdaQueryWrapper
        LambdaQueryWrapper<AllergyIntolerance> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AllergyIntolerance::getRequestId, serviceRequestId)
            // 皮试结果是已确认的
            .eq(AllergyIntolerance::getVerificationStatusEnum, VerificationStatus.CONFIRMED)
            .eq(AllergyIntolerance::getDeleteFlag, '0');
        // 根据服务请求id,获取皮试结果
        AllergyIntolerance allergyIntolerance = baseMapper.selectOne(queryWrapper);
        if (allergyIntolerance == null) {
            //没查到默认返回 未知
            return ClinicalStatus.UNKNOWN.getValue();
        }
        return allergyIntolerance.getVerificationStatusEnum();
    }
}