package com.openhis.web.charge.patientcardrenewal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.openhis.administration.domain.PatientIdentifier;
import com.openhis.administration.service.IPatientIdentifierService;
import com.openhis.common.enums.IdentifierStatusEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 患者换卡服务实现类
 * 
 * @author system
 * @date 2024-01-01
 */
@Service
@Slf4j
public class PatientCardRenewalServiceImpl implements PatientCardRenewalService {
    
    @Autowired
    private IPatientIdentifierService patientIdentifierService;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean renewCard(RenewalRequest request) {
        log.info("执行患者换卡操作: 患者ID={}, 旧卡号={}, 新卡号={}, 原因={}", 
                 request.getPatientId(), request.getOldCardNo(), request.getNewCardNo(), request.getReason());
        
        // 1. 验证参数合法性
        if (StringUtils.isEmpty(request.getPatientId())) {
            throw new IllegalArgumentException("患者ID不能为空");
        }

        if (StringUtils.isEmpty(request.getNewCardNo())) {
            throw new IllegalArgumentException("新卡号不能为空");
        }
        
        // 2. 检查新卡号是否已被使用
        LambdaQueryWrapper<PatientIdentifier> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PatientIdentifier::getIdentifierNo, request.getNewCardNo());
        List<PatientIdentifier> existingIdentifiers = patientIdentifierService.list(queryWrapper);
        if (existingIdentifiers != null && !existingIdentifiers.isEmpty()) {
            throw new IllegalArgumentException("新卡号已被其他患者使用，请更换新卡号");
        }
        
        // 3. 直接使用患者ID作为查询条件
        Long patientId = Long.parseLong(request.getPatientId());
        // 4. 通过患者ID查询现有标识信息
        PatientIdentifier patientIdentifier = patientIdentifierService.selectByPatientId(patientId);

        if (patientIdentifier != null) {
            // 5. 只更新就诊卡号这一个参数

            patientIdentifier.setIdentifierNo(request.getNewCardNo());
            patientIdentifierService.updateById(patientIdentifier);
            log.info("患者ID={} 换卡成功，已更新就诊卡号", patientId);
        } else {
            throw new IllegalArgumentException("未找到患者标识信息，无法进行换卡操作");
        }
        
        // 4. 记录换卡日志 - 可以根据需要扩展日志记录功能
        // 5. 处理相关业务系统的卡号更新 - 可以根据需要扩展
        
        return true;
    }
}