package com.openhis.administration.service.impl;

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

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.common.exception.ServiceException;
import com.openhis.administration.domain.Patient;
import com.openhis.administration.domain.PatientStudent;
import com.openhis.administration.mapper.PatientStudentMapper;
import com.openhis.administration.service.IPatientStudentService;
import com.openhis.common.enums.DelFlag;
import com.openhis.common.enums.PhysicalExamResult;

/**
 * 公费医疗学生名单管理表Service业务层处理
 *
 * @author system
 * @date 2025-02-20
 */
@Service
public class PatientStudentServiceImpl extends ServiceImpl<PatientStudentMapper, PatientStudent>
    implements IPatientStudentService {

    /**
     * 校验学生公费资格
     * 
     * @param patient
     */
    public void checkStatus(Patient patient) {

        String idCard = patient.getIdCard();
        Date date = new Date();

        List<PatientStudent> patientStudents = baseMapper.selectList(new LambdaQueryWrapper<PatientStudent>()
            .eq(PatientStudent::getIdNumber, idCard).eq(PatientStudent::getDeleteFlag, DelFlag.NO.getCode())
            .eq(PatientStudent::getPatientId, patient.getId()));

        if (patientStudents == null || patientStudents.isEmpty()) {
            throw new ServiceException("该患者不是学生，请更换费用性质类型！");
        }

        PatientStudent patientStudent = null;
        for (PatientStudent item : patientStudents) {
            if (date.after(item.getEnrollmentDate()) && date.before(item.getGraduationDate())) {
                patientStudent = item;
            }
        }

        if (patientStudent == null) {
            throw new ServiceException("该患者公费资格未生效或已失效！！不可以享受公费");
        }

        if (!PhysicalExamResult.EXAMINATION_PASSED.getValue().equals(patientStudent.getPhysicalExamResult())) {
            throw new ServiceException("该患者体检不合格不可以享受公费");
        }
    }
}