package com.ruoyi.os.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.healthcare.HealthcareOsDiagnosisStatus;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.inventory.domain.HealthcareDrugArchive;
import com.ruoyi.inventory.domain.HealthcareDrugFiling;
import com.ruoyi.inventory.service.IHealthcareDrugArchiveService;
import com.ruoyi.inventory.service.IHealthcareDrugFilingService;
import com.ruoyi.os.domain.CountDiagnosisVO;
import com.ruoyi.os.domain.DrugArchivesVO;
import com.ruoyi.os.domain.HealthcareOsPatientDiagnosis;
import com.ruoyi.os.domain.HealthcareOsPatientInfo;
import com.ruoyi.os.domain.HealthcareOsPrescriptionDetails;
import com.ruoyi.os.domain.PatientInsuranceInfo;
import com.ruoyi.os.domain.PatientMedicalRecordsVO;
import com.ruoyi.os.domain.PatientMedicalRecordsYesVO;
import com.ruoyi.os.mapper.DrugArchivesVoMapper;
import com.ruoyi.os.mapper.HealthcareOsPatientDiagnosisMapper;
import com.ruoyi.os.mapper.HealthcareOsPatientInfoMapper;
import com.ruoyi.os.mapper.HealthcareOsPrescriptionDetailsMapper;
import com.ruoyi.os.mapper.OsStatisticsMapper;
import com.ruoyi.os.service.IHealthcareOsPatientInfoService;
import com.ruoyi.os.service.IPatientDiagnosisService;
import com.ruoyi.os.service.IPatientInsuranceInfoService;

import lombok.extern.slf4j.Slf4j;

/**
 * 诊断信息Service业务处理
 *
 * @author 何顺
 * @date 2024-09-17
 */
@Slf4j
@Service
public class PatientDiagnosisServiceImpl implements IPatientDiagnosisService {

    @Autowired
    private HealthcareOsPatientDiagnosisMapper healthcareOsPatientDiagnosisMapper;

    @Autowired
    private HealthcareOsPrescriptionDetailsMapper healthcareOsPrescriptionDetailsMapper;

    @Autowired
    private HealthcareOsPatientInfoMapper healthcareOsPatientInfoMapper;

    @Autowired
    private IHealthcareDrugArchiveService iHealthcareDrugArchiveService;

    @Autowired
    private IHealthcareDrugFilingService iHealthcareDrugFilingService;

    @Autowired
    private DrugArchivesVoMapper drugArchivesVoMapper;

    @Autowired
    private OsStatisticsMapper osStatisticsMapper;

    @Autowired
    private IHealthcareOsPatientInfoService osPatientInfoService;

    @Autowired
    private IPatientInsuranceInfoService patientInsuranceInfoService;

    /**
     * 查询病历列表
     * 邵政文(修改功能)
     * 2025-05-14
     */
    @Override
    public List<HealthcareOsPatientDiagnosis> queryMedicalRecordList(
            HealthcareOsPatientDiagnosis healthcareOsPatientDiagnosis) {
        healthcareOsPatientDiagnosisMapper.updateHealthchcareOspatientDiagnoisDocitNameUtile();
        return healthcareOsPatientDiagnosisMapper.selectHealthcareOsPatientDiagnosisList(healthcareOsPatientDiagnosis);
    }

    /**
     * 获取患者诊断信息
     * 邵政文(修改功能)
     * 2025-05-14
     */
    @Override
    public PatientMedicalRecordsVO gainPatientDiagnosisInformation(Long id) {
        // 创建 诊断信息
        PatientMedicalRecordsVO patientMedicalRecordsVO = new PatientMedicalRecordsVO();
        HealthcareOsPatientDiagnosis patientDiagnosis = healthcareOsPatientDiagnosisMapper
                .selectHealthcareOsPatientDiagnosisById(id);
        // -----------------------------------------
        // 患者诊断信息字段空缺数据并修改
        if (patientDiagnosis.getPatientId() == null) {
            healthcareOsPatientDiagnosisMapper.updateHealthchcareOsPatientDiagnoisDataUtile();
            log.debug(" 患者信息为空的修改成功");
        } else {
            log.debug("患者信息不为空");
        }
        // ------------------------------------------
        // 获取诊断信息
        HealthcareOsPatientDiagnosis healthcareOsPatientDiagnosis = healthcareOsPatientDiagnosisMapper
                .selectHealthcareOsPatientDiagnosisById(id);
        BeanUtils.copyBeanProp(patientMedicalRecordsVO, healthcareOsPatientDiagnosis);
        // 获取患者信息
        HealthcareOsPatientInfo healthcareOsPatientInfo = healthcareOsPatientInfoMapper
                .selectOsPatientInfoById(healthcareOsPatientDiagnosis.getPatientId());
        BeanUtils.copyBeanProp(patientMedicalRecordsVO, healthcareOsPatientInfo);

        // 获取处方详情列表
        HealthcareOsPrescriptionDetails healthcareOsPrescriptionDetails = new HealthcareOsPrescriptionDetails();
        healthcareOsPrescriptionDetails.setPatientDiagnosisId(id);
        List<HealthcareOsPrescriptionDetails> prescriptionDetailsList = healthcareOsPrescriptionDetailsMapper
                .selectHealthcareOsPrescriptionDetailsList(healthcareOsPrescriptionDetails);
        // patientMedicalRecordsVO.setOsPrescriptionDetailsList(prescriptionDetailsList);

        // 处方详情集合
        List<List<HealthcareOsPrescriptionDetails>> prescriptionList = new ArrayList<>();
        // 获取 处方 id
        List<Long> singularIds = prescriptionDetailsList.stream()
                .map(HealthcareOsPrescriptionDetails::getSingular)
                .distinct()
                .collect(Collectors.toList());

        for (Long singularId : singularIds) {
            //
            List<HealthcareOsPrescriptionDetails> details = prescriptionDetailsList.stream()
                    .filter(detail -> detail.getSingular().equals(singularId))
                    .collect(Collectors.toList());
            prescriptionList.add(details);
        }

        patientMedicalRecordsVO.setPrescriptionDetailsList(prescriptionList);
        patientMedicalRecordsVO.setPatientDiagnosisId(id);

        return patientMedicalRecordsVO;
    }

    /**
     * 修改 患者 诊断
     * 邵政文(修改功能)
     * 2025-05-14
     */
    @Override
    public int updateDiagnosis(PatientMedicalRecordsVO patientMedicalRecordsVO) {
        // 校验 诊断 基础
        // judgeDiagnosisFoundation(patientMedicalRecordsVO);
        // 判断 处方 药品 是否 重复
        // judgeDrugRepeat(patientMedicalRecordsVO.getPrescriptionDetailsList());
        // 库存 判断
        // modifyJudgeStock(patientMedicalRecordsVO.getPrescriptionDetailsList());
        if (patientMedicalRecordsVO.getPrescriptionDetailsList().size() != 0) {
            // 校验 诊断 基础
            judgeDiagnosisFoundation(patientMedicalRecordsVO);
            // 判断 处方 药品 是否 重复
            judgeDrugRepeat(patientMedicalRecordsVO.getPrescriptionDetailsList());
            // 库存 判断
            modifyJudgeStock(patientMedicalRecordsVO.getPrescriptionDetailsList());
        }
        // 获取 诊断信息 id
        Long diagnosisId = patientMedicalRecordsVO.getPatientDiagnosisId();
        // 修改 时间
        Date updateTime = DateUtils.getNowDate();
        // 获取用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 创建 诊断信息 实例
        HealthcareOsPatientDiagnosis patientDiagnosis = new HealthcareOsPatientDiagnosis();
        // 进行 复值诊断信息
        BeanUtils.copyBeanProp(patientDiagnosis, patientMedicalRecordsVO);
        patientDiagnosis.setId(diagnosisId); // 设置 诊断信息 id
        patientDiagnosis.setUpdateTime(updateTime); // 设置 修改时间
        patientDiagnosis.setUpdateBy(loginUser.getUsername()); // 设置 修改用户
        // 修改 诊断信息 基础信息
        healthcareOsPatientDiagnosisMapper.updateHealthcareOsPatientDiagnosis(patientDiagnosis);
        // 药品 修改 库存 信息
        removeDrugModifyInventory(patientMedicalRecordsVO);
        HealthcareOsPrescriptionDetails prescriptionDetails = new HealthcareOsPrescriptionDetails();
        prescriptionDetails.setPatientDiagnosisId(diagnosisId);
        List<HealthcareOsPrescriptionDetails> prescriptionDetailsList = healthcareOsPrescriptionDetailsMapper
                .selectHealthcareOsPrescriptionDetailsList(prescriptionDetails);
        // 删除 处方详情
        if (prescriptionDetailsList.size() > 0) {
            for (int i = 0; i < prescriptionDetailsList.size(); i++) {
                healthcareOsPrescriptionDetailsMapper
                        .deleteHealthcareOsPrescriptionDetailsById(prescriptionDetailsList.get(i).getId());
            }
        }
        // 添加 处方详情
        addDrugModifyInventory(patientMedicalRecordsVO, diagnosisId, loginUser, updateTime);
        return 1;
    }

    /**
     * 保存 修改 患者 诊断
     * 邵政文(修改功能)
     * 2025-05-14
     */
    @Override
    public int saveUpdateDiagnosis(PatientMedicalRecordsVO patientMedicalRecordsVO) {
        // 校验 诊断 基础
        // judgeDiagnosisFoundation(patientMedicalRecordsVO);
        // 判断 是否 处方 库存 判断
        // if (patientMedicalRecordsVO.getPrescriptionDetailsList().size() > 0) {
        // // 判断 处方 药品 是否 重复
        // judgeDrugRepeat(patientMedicalRecordsVO.getPrescriptionDetailsList());
        // // 库存 判断
        // modifyJudgeStock(patientMedicalRecordsVO.getPrescriptionDetailsList());
        // }
        if (patientMedicalRecordsVO.getPrescriptionDetailsList().size() != 0) {
            // 校验 诊断 基础
            judgeDiagnosisFoundation(patientMedicalRecordsVO);
            // 判断 处方 药品 是否 重复
            judgeDrugRepeat(patientMedicalRecordsVO.getPrescriptionDetailsList());
            // 库存 判断
            modifyJudgeStock(patientMedicalRecordsVO.getPrescriptionDetailsList());
        }
        // 获取 诊断信息 id
        Long diagnosisId = patientMedicalRecordsVO.getPatientDiagnosisId();
        // 修改 时间
        Date updateTime = DateUtils.getNowDate();
        // 获取用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 创建 诊断信息 实例
        HealthcareOsPatientDiagnosis patientDiagnosis = new HealthcareOsPatientDiagnosis();
        // 进行 复值诊断信息
        BeanUtils.copyBeanProp(patientDiagnosis, patientMedicalRecordsVO);
        //
        patientDiagnosis.setId(diagnosisId);
        //
        patientDiagnosis.setUpdateTime(updateTime);
        //
        patientDiagnosis.setUpdateBy(loginUser.getUsername());
        // 修改 诊断信息 基础信息
        healthcareOsPatientDiagnosisMapper.updateHealthcareOsPatientDiagnosis(patientDiagnosis);
        // 获取 处方详情列表 药品 列表
        HealthcareOsPrescriptionDetails prescriptionDetails = new HealthcareOsPrescriptionDetails();
        prescriptionDetails.setPatientDiagnosisId(diagnosisId);
        List<HealthcareOsPrescriptionDetails> prescriptionDetailsList = healthcareOsPrescriptionDetailsMapper
                .selectHealthcareOsPrescriptionDetailsList(prescriptionDetails);
        // 删除 处方详情
        if (prescriptionDetailsList.size() > 0) {
            for (int i = 0; i < prescriptionDetailsList.size(); i++) {
                healthcareOsPrescriptionDetailsMapper
                        .deleteHealthcareOsPrescriptionDetailsById(prescriptionDetailsList.get(i).getId());
            }
        }
        if (patientMedicalRecordsVO.getPrescriptionDetailsList().size() > 0) {
            // 添加 处方详情
            addDrugModify(patientMedicalRecordsVO.getPrescriptionDetailsList(), diagnosisId, loginUser, updateTime);
        }
        return 1;
    }

    /**
     * 添加 患者 诊断
     */
    @Override
    public int addDiagnosis(PatientMedicalRecordsVO patientMedicalRecordsVO) {
        // 校验 诊断 基础
        judgeDiagnosisFoundation(patientMedicalRecordsVO);
        // 判断 处方 药品 是否 重复
        judgeDrugRepeat(patientMedicalRecordsVO.getPrescriptionDetailsList());
        // 库存 判断
        judgeStock(patientMedicalRecordsVO.getPrescriptionDetailsList());
        // 创建 诊断信息
        HealthcareOsPatientDiagnosis healthcareOsPatientDiagnosis = new HealthcareOsPatientDiagnosis();
        BeanUtils.copyBeanProp(healthcareOsPatientDiagnosis, patientMedicalRecordsVO);

        // 添加 时间
        Date addTime = DateUtils.getNowDate();

        // 获取用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        healthcareOsPatientDiagnosis.setDoctorName(loginUser.getUsername()); // 设置 医生姓名
        // healthcareOsPatientDiagnosis.setDoctorName(SysUser.getNickName()); // 设置 医生姓名
        healthcareOsPatientDiagnosis.setOutpatientTime(addTime); // 设置 就诊时间
        healthcareOsPatientDiagnosis.setCreateBy(loginUser.getUsername()); // 设置 创建用户
        healthcareOsPatientDiagnosis.setCreateTime(addTime); // 设置 创建时间

        // 状态 0
        healthcareOsPatientDiagnosis.setStatus(HealthcareOsDiagnosisStatus.READY_TO_GO.getDescription());

        // 添加 诊断信息
        if (healthcareOsPatientDiagnosisMapper.insertHealthcareOsPatientDiagnosis(healthcareOsPatientDiagnosis) == 1) {

            // 参数
            Map<String, Object> map = new HashMap<>(2);
            // 获取当前时间前5秒
            Calendar calendarFront = Calendar.getInstance();
            calendarFront.setTime(addTime);
            calendarFront.add(Calendar.SECOND, -5);
            map.put("outpatientTimeFront", calendarFront.getTime());
            // 获取当前时间后5秒
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(addTime);
            calendar.add(Calendar.SECOND, 5);
            map.put("outpatientTimeAfter", calendar.getTime());
            healthcareOsPatientDiagnosis.setParams(map);
            List<HealthcareOsPatientDiagnosis> diagnosisList = healthcareOsPatientDiagnosisMapper
                    .selectHealthcareOsPatientDiagnosisList(healthcareOsPatientDiagnosis);
            // 获取诊断id
            if (diagnosisList.size() == 1) {
                Long diagnosisId = diagnosisList.get(0).getId();
                // 添加处方详情
                if (patientMedicalRecordsVO.getPrescriptionDetailsList() != null && diagnosisId != null) {
                    // 添加 处方 药品 修改 库存
                    addDrugModifyInventory(patientMedicalRecordsVO, diagnosisId, loginUser, addTime);
                }
            } else if (diagnosisList.size() > 1) {
                return 2;
            }
            return 1;
        }
        return 0;
    }

    /**
     * 保存 变成 待发 修改 库存
     * 邵政文(修改功能)
     * 2025-05-14
     */
    @Override
    public int saveAddDiagnosis(PatientMedicalRecordsVO patientMedicalRecordsVO) {
        // 校验 诊断 基础
        // judgeDiagnosisFoundation(patientMedicalRecordsVO);
        // 判断 处方 药品 是否 重复
        // judgeDrugRepeat(patientMedicalRecordsVO.getPrescriptionDetailsList());
        // 库存 判断 judgeStock
        // judgeStock(patientMedicalRecordsVO.getPrescriptionDetailsList());
        if (patientMedicalRecordsVO.getPrescriptionDetailsList().size() != 0) {
            // 校验 诊断 基础
            judgeDiagnosisFoundation(patientMedicalRecordsVO);
            // 判断 处方 药品 是否 重复
            judgeDrugRepeat(patientMedicalRecordsVO.getPrescriptionDetailsList());
            // 库存 判断
            judgeStock(patientMedicalRecordsVO.getPrescriptionDetailsList());
        }
        // 获取 诊断信息 id
        Long diagnosisId = patientMedicalRecordsVO.getPatientDiagnosisId();
        // 修改 时间
        Date updateTime = DateUtils.getNowDate();
        // 获取用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 创建 诊断信息 实例
        HealthcareOsPatientDiagnosis patientDiagnosis = new HealthcareOsPatientDiagnosis();
        // 进行 复值诊断信息
        BeanUtils.copyBeanProp(patientDiagnosis, patientMedicalRecordsVO);
        //
        patientDiagnosis.setId(diagnosisId);
        //
        patientDiagnosis.setUpdateTime(updateTime);
        //
        patientDiagnosis.setUpdateBy(loginUser.getUsername());
        // 修改 状态为待发 0
        patientDiagnosis.setStatus(HealthcareOsDiagnosisStatus.READY_TO_GO.getDescription());
        // 修改 诊断信息 基础信息
        healthcareOsPatientDiagnosisMapper.updateHealthcareOsPatientDiagnosis(patientDiagnosis);
        //
        HealthcareOsPrescriptionDetails prescriptionDetails = new HealthcareOsPrescriptionDetails();
        prescriptionDetails.setPatientDiagnosisId(diagnosisId);
        List<HealthcareOsPrescriptionDetails> prescriptionDetailsList = healthcareOsPrescriptionDetailsMapper
                .selectHealthcareOsPrescriptionDetailsList(prescriptionDetails);
        // 删除 处方详情
        if (prescriptionDetailsList.size() > 0) {
            for (int i = 0; i < prescriptionDetailsList.size(); i++) {
                healthcareOsPrescriptionDetailsMapper
                        .deleteHealthcareOsPrescriptionDetailsById(prescriptionDetailsList.get(i).getId());
            }
        }
        // 添加 处方详情
        addDrugModifyInventory(patientMedicalRecordsVO, diagnosisId, loginUser, updateTime);
        return 1;
    }

    /**
     * 保存 患者 诊断
     * 邵政文(修改功能)
     * 2025-05-14
     */
    @Override
    public int saveDiagnosis(PatientMedicalRecordsVO patientMedicalRecordsVO) {
        // 校验 诊断 基础
        // judgeDiagnosisFoundation(patientMedicalRecordsVO);
        // 判断 处方 药品 是否 重复
        // judgeDrugRepeat(patientMedicalRecordsVO.getPrescriptionDetailsList());
        // 库存 判断(保存)
        // judgeStock(patientMedicalRecordsVO.getPrescriptionDetailsList());
        if (patientMedicalRecordsVO.getPrescriptionDetailsList().size() != 0) {
            // 校验 诊断 基础
            judgeDiagnosisFoundation(patientMedicalRecordsVO);
            // 判断 处方 药品 是否 重复
            judgeDrugRepeat(patientMedicalRecordsVO.getPrescriptionDetailsList());
            // 库存 判断(保存)
            judgeStock(patientMedicalRecordsVO.getPrescriptionDetailsList());
        }
        //
        HealthcareOsPatientDiagnosis healthcareOsPatientDiagnosis = new HealthcareOsPatientDiagnosis();
        BeanUtils.copyBeanProp(healthcareOsPatientDiagnosis, patientMedicalRecordsVO);

        // 添加 时间
        Date addTime = DateUtils.getNowDate();

        // 获取用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        healthcareOsPatientDiagnosis.setDoctorName(loginUser.getUsername()); // 设置 医生姓名
        // healthcareOsPatientDiagnosis.setDoctorName(SysUser.getNickName()); // 设置 医生姓名
        healthcareOsPatientDiagnosis.setOutpatientTime(addTime);
        healthcareOsPatientDiagnosis.setCreateBy(loginUser.getUsername());
        healthcareOsPatientDiagnosis.setCreateTime(addTime);

        // 状态 3
        healthcareOsPatientDiagnosis.setStatus(HealthcareOsDiagnosisStatus.SAVE.getDescription());

        // 添加 诊断信息
        if (healthcareOsPatientDiagnosisMapper.insertHealthcareOsPatientDiagnosis(healthcareOsPatientDiagnosis) == 1) {
            // 参数
            Map<String, Object> map = new HashMap<>(2);
            // 获取当前时间前5秒
            Calendar calendarFront = Calendar.getInstance();
            calendarFront.setTime(addTime);
            calendarFront.add(Calendar.SECOND, -5);
            map.put("outpatientTimeFront", calendarFront.getTime());
            // 获取当前时间后5秒
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(addTime);
            calendar.add(Calendar.SECOND, 5);
            map.put("outpatientTimeAfter", calendar.getTime());
            healthcareOsPatientDiagnosis.setParams(map);
            // 获取诊断id 列表
            List<HealthcareOsPatientDiagnosis> diagnosisList = healthcareOsPatientDiagnosisMapper
                    .selectHealthcareOsPatientDiagnosisList(healthcareOsPatientDiagnosis);
            // 获取诊断id
            if (diagnosisList.size() == 1) {
                // 创建 id
                Long diagnosisId = diagnosisList.get(0).getId();
                // 添加处方详情
                if (patientMedicalRecordsVO.getPrescriptionDetailsList() != null && diagnosisId != null) {
                    // 添加 处方 药品
                    addDrugModify(patientMedicalRecordsVO.getPrescriptionDetailsList(), diagnosisId, loginUser,
                            addTime);
                }
            } else if (diagnosisList.size() > 1) {
                return 2;
            }
            return 1;
        }
        return 0;
    }

    /**
     * 添加 药品 详情 添加 处方 详情 药品 库存 对应 药品 库存
     * prescriptionDetailsList 处方详情信息 diagnosisId 诊断id loginUser 登录用户 addTime 添加时间
     */
    private void addDrugModify(List<List<HealthcareOsPrescriptionDetails>> prescriptionDetailsList, Long diagnosisId,
            LoginUser loginUser, Date addTime) {
        for (int i = 0; i < prescriptionDetailsList.size(); i++) {
            // 序号
            Long singular = (long) i;
            //
            prescriptionDetailsList.get(i).forEach(model -> {
                //
                model.setSingular(singular);
                // 诊断id
                model.setPatientDiagnosisId(diagnosisId);
                // 创建者
                model.setCreateBy(loginUser.getUsername());
                // 时间
                model.setCreateTime(addTime);
                // 添加药品详情
                healthcareOsPrescriptionDetailsMapper.insertHealthcareOsPrescriptionDetails(model);
            });
        }
    }

    /**
     * 添加 处方 信息 并 修改 药品 修改 库存
     *
     * @param patientMedicalRecordsVO 处方详情信息
     * @param diagnosisId             诊断id
     * @param loginUser               登录用户
     * @param addTime                 添加时间
     */
    private void addDrugModifyInventory(PatientMedicalRecordsVO patientMedicalRecordsVO, Long diagnosisId,
            LoginUser loginUser, Date addTime) {
        // 添加 药品
        for (int i = 0; i < patientMedicalRecordsVO.getPrescriptionDetailsList().size(); i++) {
            Long singular = (long) i;
            patientMedicalRecordsVO.getPrescriptionDetailsList().get(i).forEach(model -> {
                // 诊断 id
                model.setPatientDiagnosisId(diagnosisId);
                // 序号
                model.setSingular(singular);
                // 创建者
                model.setCreateBy(loginUser.getUsername());
                // 创建时间
                model.setCreateTime(addTime);
                // 添加药品详情
                healthcareOsPrescriptionDetailsMapper.insertHealthcareOsPrescriptionDetails(model);
                // 获取 药品 库存
                HealthcareDrugFiling healthcareDrugFiling = iHealthcareDrugFilingService
                        .selectHealthcareDrugFilingById(model.getMedicineId());
                if (healthcareDrugFiling != null) {
                    HealthcareDrugFiling updateHealthcareDrugFiling = new HealthcareDrugFiling();
                    updateHealthcareDrugFiling.setId(model.getMedicineId());
                    BeanUtils.copyBeanProp(updateHealthcareDrugFiling, healthcareDrugFiling);

                    int totalQty = model.getTotalQuantity() == null ? 0 : model.getTotalQuantity();
                    int packCount = healthcareDrugFiling.getPackCount() == null ? 0 : healthcareDrugFiling.getPackCount();
                    int boxCount = healthcareDrugFiling.getBoxCount() == null ? 0 : healthcareDrugFiling.getBoxCount();
                    int unitQty = model.getUnitQuantity() == null || model.getUnitQuantity() == 0 ? 1 : model.getUnitQuantity();

                    if ("Y".equals(model.getIsSplit())) {
                        if (packCount >= totalQty) {
                            updateHealthcareDrugFiling.setPackCount(packCount - totalQty);
                            iHealthcareDrugFilingService.updateHealthcareDrugFiling(updateHealthcareDrugFiling);
                        } else {
                            int boxUnt = totalQty / unitQty;
                            int packUnt = totalQty % unitQty;
                            if (packUnt <= packCount) {
                                updateHealthcareDrugFiling.setPackCount(packCount - packUnt);
                            } else {
                                boxUnt = boxUnt + 1;
                                updateHealthcareDrugFiling.setPackCount(packCount + unitQty - packUnt);
                            }
                            updateHealthcareDrugFiling.setBoxCount(boxCount - boxUnt);
                            iHealthcareDrugFilingService.updateHealthcareDrugFiling(updateHealthcareDrugFiling);
                        }
                    } else if ("N".equals(model.getIsSplit())) {
                        updateHealthcareDrugFiling.setBoxCount(boxCount - totalQty);
                        iHealthcareDrugFilingService.updateHealthcareDrugFiling(updateHealthcareDrugFiling);
                    }
                }
            });
        }
    }

    /**
     * 处理 诊断 信息 的删除 药品 修改 库存
     */
    @Override
    public void removeDrugModifyInventory(PatientMedicalRecordsVO patientMedicalRecordsVO) {
        // 药品 盒子
        HealthcareOsPrescriptionDetails prescriptionDetails = new HealthcareOsPrescriptionDetails();
        prescriptionDetails.setPatientDiagnosisId(patientMedicalRecordsVO.getPatientDiagnosisId());
        // 获取 药品 数组
        List<HealthcareOsPrescriptionDetails> prescriptionDetailsList = healthcareOsPrescriptionDetailsMapper
                .selectHealthcareOsPrescriptionDetailsList(prescriptionDetails);
        if (prescriptionDetailsList != null) {
            prescriptionDetailsList.forEach(model -> {
                HealthcareDrugFiling healthcareDrugFiling = iHealthcareDrugFilingService
                        .selectHealthcareDrugFilingById(model.getMedicineId());
                if (healthcareDrugFiling != null) {
                    HealthcareDrugFiling updateHealthcareDrugFiling = new HealthcareDrugFiling();
                    updateHealthcareDrugFiling.setId(model.getMedicineId());
                    BeanUtils.copyBeanProp(updateHealthcareDrugFiling, healthcareDrugFiling);

                    int totalQty = model.getTotalQuantity() == null ? 0 : model.getTotalQuantity();
                    int packCount = healthcareDrugFiling.getPackCount() == null ? 0 : healthcareDrugFiling.getPackCount();
                    int boxCount = healthcareDrugFiling.getBoxCount() == null ? 0 : healthcareDrugFiling.getBoxCount();

                    if ("Y".equals(model.getIsSplit())) {
                        int newPackCount = packCount + totalQty;
                        updateHealthcareDrugFiling.setPackCount(newPackCount);
                        if (updateHealthcareDrugFiling.getMinNumber() > 0 && newPackCount >= updateHealthcareDrugFiling.getMinNumber()) {
                            updateHealthcareDrugFiling.setBoxCount(boxCount + 1);
                            updateHealthcareDrugFiling
                                    .setPackCount((int) (newPackCount - updateHealthcareDrugFiling.getMinNumber()));
                        }
                        iHealthcareDrugFilingService.updateHealthcareDrugFiling(updateHealthcareDrugFiling);
                    } else if ("N".equals(model.getIsSplit())) {
                        updateHealthcareDrugFiling.setBoxCount(boxCount + totalQty);
                        iHealthcareDrugFilingService.updateHealthcareDrugFiling(updateHealthcareDrugFiling);
                    }
                }
            });
        }
    }

    /**
     * 删除 患者 诊断
     */
    @Override
    public int removeDiagnosis(Long id) {
        // 获取 诊断信息
        HealthcareOsPatientDiagnosis healthcareOsPatientDiagnosis = healthcareOsPatientDiagnosisMapper
                .selectHealthcareOsPatientDiagnosisById(id);
        // 判断 诊断信息 是否 为 null
        if (healthcareOsPatientDiagnosis != null) {
            // 获取 药品 信息
            HealthcareOsPrescriptionDetails healthcareOsPrescriptionDetails = new HealthcareOsPrescriptionDetails();
            healthcareOsPrescriptionDetails.setPatientDiagnosisId(id);
            // 获取 药品 数组
            List<HealthcareOsPrescriptionDetails> prescriptionDetailsList = healthcareOsPrescriptionDetailsMapper
                    .selectHealthcareOsPrescriptionDetailsList(healthcareOsPrescriptionDetails);
            // 判断 药品 数组 是否 为 null
            if (prescriptionDetailsList != null) {
                // 循环 药品 数组
                prescriptionDetailsList.forEach(model -> {
                    HealthcareDrugFiling healthcareDrugFiling = iHealthcareDrugFilingService
                            .selectHealthcareDrugFilingById(model.getMedicineId());
                    if (healthcareDrugFiling != null) {
                        HealthcareDrugFiling updateHealthcareDrugFiling = new HealthcareDrugFiling();
                        updateHealthcareDrugFiling.setId(model.getMedicineId());
                        BeanUtils.copyBeanProp(updateHealthcareDrugFiling, healthcareDrugFiling);

                        int totalQty = model.getTotalQuantity() == null ? 0 : model.getTotalQuantity();
                        int packCount = healthcareDrugFiling.getPackCount() == null ? 0 : healthcareDrugFiling.getPackCount();
                        int boxCount = healthcareDrugFiling.getBoxCount() == null ? 0 : healthcareDrugFiling.getBoxCount();

                        if ("Y".equals(model.getIsSplit())) {
                            int newPackCount = packCount + totalQty;
                            updateHealthcareDrugFiling.setPackCount(newPackCount);
                            if (updateHealthcareDrugFiling.getMinNumber() > 0 && newPackCount >= updateHealthcareDrugFiling.getMinNumber()) {
                                updateHealthcareDrugFiling.setBoxCount(boxCount + 1);
                                updateHealthcareDrugFiling
                                        .setPackCount((int) (newPackCount - updateHealthcareDrugFiling.getMinNumber()));
                            }
                            iHealthcareDrugFilingService.updateHealthcareDrugFiling(updateHealthcareDrugFiling);
                        } else if ("N".equals(model.getIsSplit())) {
                            updateHealthcareDrugFiling.setBoxCount(boxCount + totalQty);
                            iHealthcareDrugFilingService.updateHealthcareDrugFiling(updateHealthcareDrugFiling);
                        }
                    }
                });
            }
            // 删除 诊断信息
            return healthcareOsPatientDiagnosisMapper.deleteHealthcareOsPatientDiagnosisById(id);
        }
        return 0;
    }

    /**
     * 判断 库存
     *
     * @param prescriptionDetailsList 参数
     *
     */
    @Override
    public void judgeStock(List<List<HealthcareOsPrescriptionDetails>> prescriptionDetailsList) {
        // 判断 药品 数组
        if (prescriptionDetailsList != null) {
            // 循环 药品 数组
            prescriptionDetailsList.forEach(list -> {
                list.forEach(model -> {
                    // 获取 药品 库存
                    HealthcareDrugFiling healthcareDrugFiling = iHealthcareDrugFilingService
                            .selectHealthcareDrugFilingById(model.getMedicineId());
                    if (healthcareDrugFiling != null) {
                        int boxCount = healthcareDrugFiling.getBoxCount() == null ? 0 : healthcareDrugFiling.getBoxCount();
                        int packCount = healthcareDrugFiling.getPackCount() == null ? 0 : healthcareDrugFiling.getPackCount();
                        int totalQty = model.getTotalQuantity() == null ? 0 : model.getTotalQuantity();
                        if ("Y".equals(model.getIsSplit())) {
                            if (boxCount == 0 && packCount < totalQty) {
                                throw new UtilException("【" + healthcareDrugFiling.getMedicineName() + "】药品库存不足");
                            }
                        } else if ("N".equals(model.getIsSplit())) {
                            if (boxCount < totalQty) {
                                throw new UtilException("【" + healthcareDrugFiling.getMedicineName() + "】药品库存不足");
                            }
                        }
                    }
                });
            });
        }
    }

    /**
     * 判断 库存 在 修改 处方
     *
     * @param prescriptionDetailsList 参数
     *
     */
    @Override
    public void modifyJudgeStock(List<List<HealthcareOsPrescriptionDetails>> prescriptionDetailsList) {
        // 判断 药品 数组
        if (prescriptionDetailsList != null) {
            // 循环 药品 数组
            prescriptionDetailsList.forEach(list -> {
                list.forEach(model -> {
                    // 获取 药品 库存
                    HealthcareDrugFiling healthcareDrugFiling = iHealthcareDrugFilingService
                            .selectHealthcareDrugFilingById(model.getMedicineId());
                    if (healthcareDrugFiling != null) {
                        int boxCount = healthcareDrugFiling.getBoxCount() == null ? 0 : healthcareDrugFiling.getBoxCount();
                        int packCount = healthcareDrugFiling.getPackCount() == null ? 0 : healthcareDrugFiling.getPackCount();
                        int totalQty = model.getTotalQuantity() == null ? 0 : model.getTotalQuantity();
                        if ("Y".equals(model.getIsSplit())) {
                            if (boxCount == 0 && packCount < totalQty) {
                                throw new UtilException("【" + healthcareDrugFiling.getMedicineName() + "】药品库存不足");
                            }
                        } else if ("N".equals(model.getIsSplit())) {
                            if (boxCount < totalQty) {
                                throw new UtilException("【" + healthcareDrugFiling.getMedicineName() + "】药品库存不足");
                            }
                        }
                    }
                });
            });
        }
    }

    /**
     * 修改患者状态
     *
     * @param id     患者id
     * @param status 状态
     * @return 返回 成功 提示信息
     */
    @Override
    public int updateStatus(Long id, Long status) {
        HealthcareOsPatientDiagnosis healthcareOsPatientDiagnosis = new HealthcareOsPatientDiagnosis();
        healthcareOsPatientDiagnosis.setId(id);
        healthcareOsPatientDiagnosis.setStatus(status);
        return healthcareOsPatientDiagnosisMapper.updateHealthcareOsPatientDiagnosis(healthcareOsPatientDiagnosis);
    }

    /**
     * @param drugArchivesVO 参数
     * @return 返回 药品 列表
     **/
    @Override
    public List<DrugArchivesVO> gainDrugList(DrugArchivesVO drugArchivesVO) {
        return drugArchivesVoMapper.selectDruyInventoryList(drugArchivesVO);
    }

    /**
     * @param healthcareDrugArchive 参数
     * @return 返回 药品 列表 价格
     **/
    @Override
    public List<DrugArchivesVO> gainDrugPriceList(HealthcareDrugArchive healthcareDrugArchive) {
        // TODO: 该方法在DrugArchivesVoMapper中未定义
        return new java.util.ArrayList<>();
    }

    /**
     * 获取 药品 名称 列表 gainMedicineArchiveList
     *
     * @param healthcareDrugArchive 参数
     * @return 返回 药品名称 列表
     */
    @Override
    public List<String> gainMedicineNameList(HealthcareDrugArchive healthcareDrugArchive) {
        // TODO: 该方法在DrugArchivesVoMapper中未定义
        return new java.util.ArrayList<>();
    }

    /**
     * 获取 药品 名称 列表
     *
     * @param drugArchivesVO 参数
     * @return 返回 药品 档案 列表
     */
    @Override
    public List<HealthcareDrugArchive> gainMedicineArchiveList(DrugArchivesVO drugArchivesVO) {
        // TODO: 该方法在DrugArchivesVoMapper中未定义
        return new java.util.ArrayList<>();
    }

    /**
     * 获取 药品 库存 列表
     *
     * @param drugArchivesVO 参数
     * @return 返回 药品库存 列表
     */
    @Override
    public List<DrugArchivesVO> gainDrugInventoryList(DrugArchivesVO drugArchivesVO) {
        return drugArchivesVoMapper.selectDruyInventoryList(drugArchivesVO);
    }

    /**
     * 获取 患者 诊断 详情 列表 没有 id 的
     *
     * @param patientMedicalRecordsVO 参数
     * @return 返回 列表
     */
    @Override
    public List<PatientMedicalRecordsVO> gainPrescriptionDetailsList(PatientMedicalRecordsVO patientMedicalRecordsVO) {
        List<PatientMedicalRecordsVO> list = osStatisticsMapper.obtainPatientDiagnosisList(patientMedicalRecordsVO);
        if (list == null || list.isEmpty()) {
            return list;
        }

        List<Long> diagnosisIds = list.stream()
                .map(PatientMedicalRecordsVO::getPatientDiagnosisId)
                .filter(id -> id != null)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, List<HealthcareOsPrescriptionDetails>> detailsByDiagnosisId = new HashMap<>();
        if (!diagnosisIds.isEmpty()) {
            List<HealthcareOsPrescriptionDetails> allDetails = healthcareOsPrescriptionDetailsMapper
                    .selectHealthcareOsPrescriptionDetailsByDiagnosisIds(diagnosisIds);
            if (allDetails != null && !allDetails.isEmpty()) {
                detailsByDiagnosisId = allDetails.stream()
                        .filter(detail -> detail.getPatientDiagnosisId() != null)
                        .collect(Collectors.groupingBy(HealthcareOsPrescriptionDetails::getPatientDiagnosisId));
            }
        }

        for (PatientMedicalRecordsVO record : list) {
            Long diagnosisId = record.getPatientDiagnosisId();
            if (diagnosisId == null) {
                record.setPrescriptionDetailsList(new ArrayList<>());
                continue;
            }

            List<HealthcareOsPrescriptionDetails> details = detailsByDiagnosisId.get(diagnosisId);
            if (details == null || details.isEmpty()) {
                record.setPrescriptionDetailsList(new ArrayList<>());
                continue;
            }

            Map<Long, List<HealthcareOsPrescriptionDetails>> grouped = new LinkedHashMap<>();
            for (HealthcareOsPrescriptionDetails detail : details) {
                Long singular = detail.getSingular();
                if (singular == null) {
                    singular = -1L;
                }
                grouped.computeIfAbsent(singular, key -> new ArrayList<>()).add(detail);
            }
            record.setPrescriptionDetailsList(new ArrayList<>(grouped.values()));
        }

        return list;
    }

    /**
     * 获取 症状 对应 的 数量
     *
     * @param countDiagnosisVO 参数
     * @return 返回 列表
     */
    @Override
    public List<CountDiagnosisVO> obtainSymptomStatisticsNumber(CountDiagnosisVO countDiagnosisVO) {
        return osStatisticsMapper.obtainSymptomCorrespondingNumber(countDiagnosisVO);
    }

    /**
     * 按患者ID统计历史医保报销累计金额(仅统计已发药)
     *
     * @param patientId 患者ID
     * @param yearDate  年份日期(用于过滤当年数据)
     * @return 历史医保报销累计金额
     */
    @Override
    public java.math.BigDecimal getHistoryReimbursementByPatientId(Long patientId, java.util.Date yearDate) {
        if (patientId == null) {
            return java.math.BigDecimal.ZERO;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("patientId", patientId);
        params.put("yearDate", yearDate != null ? yearDate : new java.util.Date());
        return osStatisticsMapper.getHistoryReimbursementByPatientId(params);
    }

    /**
     * 获取 症状 对应 的 数量 月份
     *
     * @param countDiagnosisVO 参数
     * @return 返回 列表
     */
    @Override
    public List<List<CountDiagnosisVO>> obtainSymptomStatisticsNumberMonth(CountDiagnosisVO countDiagnosisVO) {
        // TODO: 该方法在OsStatisticsMapper中未定义
        return new java.util.ArrayList<>();
    }

    /**
     * 导出是医保的数据列表
     * 邵政文
     * 2025-05-14
     */
    @Override
    public List<PatientMedicalRecordsYesVO> gainPrescriptionDetailsYesList(
            PatientMedicalRecordsVO patientMedicalRecordsVO) {
        return osStatisticsMapper.obtainPatientDiagnosisYesList(patientMedicalRecordsVO);
    }

    /**
     * 验证医保是否可用
     *
     * @param idCard 身份证
     * @param name   姓名
     * @return 0 可用 1 不可用
     */
    @Override
    public int verifyInsuranceStatus(String idCard, String name) {
        // 根据身份证号 + 姓名 + 当前年份查询 patient_insurance_info 表
        String currentYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        PatientInsuranceInfo query = new PatientInsuranceInfo();
        query.setIdNumber(idCard);
        query.setName(name);
        query.setPaymentYear(currentYear);
        List<PatientInsuranceInfo> list = patientInsuranceInfoService.selectPatientInsuranceInfoList(query);
        // 查到记录表示当年已缴费，返回0（可用）；否则返回1（不可用）
        if (list != null && !list.isEmpty()) {
            return 0;
        }
        return 1;
    }

    /**
     * 发药更正:仅调整基础字段(是否医保、报销比率等),不改处方明细与库存
     *
     * @param patientMedicalRecordsVO 入参包含 patientDiagnosisId、isInsured、value 等
     * @return 影响行数
     */
    @Override
    public int adjustBasicFields(PatientMedicalRecordsVO patientMedicalRecordsVO) {
        // TODO: adjustBasicFields方法在HealthcareOsPatientDiagnosisMapper中未定义
        return 0;
    }

    // 判断 处方 重复
    private void judgeDrugRepeat(List<List<HealthcareOsPrescriptionDetails>> prescriptionDetailsList) {
        if (prescriptionDetailsList != null) {
            for (int i = 0; i < prescriptionDetailsList.size(); i++) {
                for (int j = 0; j < prescriptionDetailsList.get(i).size(); j++) {
                    for (int k = 0; k < prescriptionDetailsList.get(i).size(); k++) {
                        if (j != k && prescriptionDetailsList.get(i).get(j).getMedicineId()
                                .equals(prescriptionDetailsList.get(i).get(k).getMedicineId())) {
                            throw new UtilException(
                                    "【" + prescriptionDetailsList.get(i).get(j).getMedicineName() + "】药品重复");
                        }
                    }
                }
            }
        }
    }

    // 判断 诊断 基础
    private void judgeDiagnosisFoundation(PatientMedicalRecordsVO patientMedicalRecordsVO) {
        if (patientMedicalRecordsVO.getPatientId() == null) {
            throw new UtilException("请选择患者信息");
        }
        if (patientMedicalRecordsVO.getDiagnosis() == null || patientMedicalRecordsVO.getDiagnosis().isEmpty()) {
            throw new UtilException("请输入诊断信息");
        }
    }
}
