package org.dromara.web.service.impl;
import java.math.BigDecimal;
import java.util.Date;

import java.util.*;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.SysDept;
import org.dromara.system.domain.SysFoodIngredient;
import org.dromara.system.domain.SysRecipe;
import org.dromara.system.mapper.*;
import org.dromara.web.domain.*;
import org.dromara.web.domain.bo.*;
import org.dromara.web.domain.vo.*;
import org.dromara.web.mapper.*;
import org.dromara.web.service.ReportService;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

/**
 * @Author: Huanyi
 * @CreateTime: 2025-08-18
 * @Description:
 * @Version: 1.0
 */

@Service
@RequiredArgsConstructor
@Slf4j
public class ReportServiceImpl implements ReportService {

    private final DailyMealPlanMapper dailyMealPlanMapper;
    private final DailyMealRecipeMapper dailyMealRecipeMapper;
    private final HospitalMealPlanMapper hospitalMealPlanMapper;
    private final HospitalMealRecipeMapper hospitalMealRecipeMapper;
    private final SysRecipeMapper sysRecipeMapper;
    private final SysRecipeFoodIngredientMapper sysRecipeFoodIngredientMapper;
    private final SysFoodIngredientMapper sysFoodIngredientMapper;
    private final TreatmentUserMapper treatmentUserMapper;
    private final SysDeptMapper sysDeptMapper;
    private final SysUserMapper sysUserMapper;
    private final SettlementMapper settlementMapper;
    private final SysDictDataMapper sysDictDataMapper;
    private final ChargeRecordMapper chargeRecordMapper;
    private final EnteralNutritionMapper enteralNutritionMapper;
    private final ProductNutritionMapper productNutritionMapper;
    private final ProductCategoryMapper productCategoryMapper;
    private final ProductManufacturerMapper productManufacturerMapper;
    private final ProductSupplierMapper productSupplierMapper;
    private final EnteralNutritionConsumableMapper enteralNutritionConsumableMapper;
    private final SuppliesManageMapper suppliesManageMapper;
    private final SuppliesCategoryMapper suppliesCategoryMapper;
    private final NutritionScreeningMapper nutritionScreeningMapper;
    private final NutritionEvaluationMapper nutritionEvaluationMapper;
    private final NutritionDiagnosisMapper nutritionDiagnosisMapper;
    private final NutritionEducationMapper nutritionEducationMapper;
    private final SysScreeningAssessmentConfigMapper sysScreeningAssessmentConfigMapper;
    private final SysDiseaseLabelMapper sysDiseaseLabelMapper;

    @Override
    public R getNutritionalQualityControl(Timestamp start, Timestamp end) {
        return R.ok();
    }

    @Override
    public TableDataInfo listPageDietaryPrescription(DietaryPrescriptionBo bo, PageQuery pageQuery) {

//        hospitalMealPlanMapper.listPageMealPlan(
//            bo.getTradeDateEarliest(),
//            bo.getTradeDateLatest(),
//            bo.getCalculationDateEarliest(),
//            bo.getCalculationDateLatest(),
//            bo.getDoctorDepartmentId(),
//            bo.getPatientDepartmentId(),
//            bo.getName(),
//            bo.getConsultationType(),
//            pageQuery.getPageNum(),
//            pageQuery.getPageSize()
//        );

        Map<Long, String> patientMap = new HashMap<>();
        Map<Long, String> deptMap = new HashMap<>();
        Map<Long, String> userMap = new HashMap<>();
        List<Long> ids = new ArrayList<>();
        Map<String, String> payStatusMap = new HashMap<>();

        treatmentUserMapper.selectList().forEach(e -> patientMap.put(e.getId(), e.getTreatName()));
        sysDeptMapper.selectList().forEach(e -> deptMap.put(e.getDeptId(), e.getDeptName()));
        sysUserMapper.selectList().forEach(e -> userMap.put(e.getUserId(), e.getName()));
        treatmentUserMapper.selectList(
            Wrappers.lambdaQuery(TreatmentUser.class).like(TreatmentUser::getTreatName, bo.getName())
        ).forEach(e -> ids.add(e.getId()));
        sysDictDataMapper.selectDictDataByType("payment_status").forEach(e -> payStatusMap.put(e.getDictValue(), e.getDictLabel()));

        if (bo.getDietaryType() == 0) {

            Page<HospitalMealPlan> page = hospitalMealPlanMapper.selectPage(
                pageQuery.build(),
                Wrappers.lambdaQuery(HospitalMealPlan.class)
                    .ge(bo.getCalculationDateEarliest() != null, HospitalMealPlan::getCreateTime, bo.getCalculationDateEarliest())
                    .le(bo.getCalculationDateLatest() != null, HospitalMealPlan::getCreateTime, bo.getCalculationDateLatest())
                    .in(!ids.isEmpty(), HospitalMealPlan::getPatientId, ids)
                    .eq(bo.getConsultationType() != null, HospitalMealPlan::getType, bo.getConsultationType())
                    .eq(bo.getPatientDepartmentId() != null, HospitalMealPlan::getDeptId, bo.getPatientDepartmentId())
                    .eq(bo.getDoctorDepartmentId() != null, HospitalMealPlan::getCreateDept, bo.getDoctorDepartmentId())
                    .isNotNull(HospitalMealPlan::getSettlementId)
            );

            Map<Long, String> settlementMap = new HashMap<>();
            // 食谱 ID    食谱名称
            Map<Long, String> recipeMap = new HashMap<>();
            // 食谱 ID    所需食材 ID
            Map<Long, List<Long>> recipeToIngredientMap = new HashMap<>();
            // 食材 ID   食材名称
            Map<Long, String> ingredientMap = new HashMap<>();


            settlementMapper.selectList().forEach(e -> settlementMap.put(e.getId(), e.getPaymentStatus()));
            sysRecipeMapper.selectList().forEach(e -> recipeMap.put(e.getRecipeId(), e.getName()));
            sysRecipeFoodIngredientMapper.selectList().forEach(e -> {
                if (recipeToIngredientMap.containsKey(e.getRecipeId())) {
                    recipeToIngredientMap.get(e.getRecipeId()).add(e.getFoodIngredientId());
                } else {
                    recipeToIngredientMap.put(e.getRecipeId(), List.of(e.getFoodIngredientId()));
                }
            });
            sysFoodIngredientMapper.selectList().forEach(e -> ingredientMap.put(e.getFoodIngredientId(), e.getName()));

            Map<String, List<String>> foodMap = new HashMap<>();
            recipeToIngredientMap.forEach((k, v) -> {
                List<String> list = new ArrayList<>();
                v.forEach( e -> list.add(ingredientMap.get(e)));
                foodMap.put(recipeMap.get(k), list);
            });

            return TableDataInfo.build(page.convert(e -> {
                InHospitalDietaryPrescriptionVo vo = new InHospitalDietaryPrescriptionVo();
                vo.setId(e.getId());
                vo.setTradeDate(new Date());
                vo.setCalculationDate(e.getCreateTime());
                vo.setConsultationType(Objects.equals(e.getType(), "0") ? "门诊" : "住院");
                vo.setCalculationDoctorDepartment(deptMap.get(e.getDeptId()));
                vo.setCalculationDoctor(userMap.get(e.getCreateBy()));
                vo.setPatientDepartment(deptMap.get(e.getDeptId()));
                vo.setPatientName(patientMap.get(e.getPatientId()));
                vo.setPayStatus(payStatusMap.get(settlementMap.get(e.getSettlementId())));

                List<CookbookVo> breakfast = new ArrayList<>();
                List<CookbookVo> breakfastExtra = new ArrayList<>();
                List<CookbookVo> lunch = new ArrayList<>();
                List<CookbookVo> lunchExtra = new ArrayList<>();
                List<CookbookVo> dinner = new ArrayList<>();
                List<CookbookVo> dinnerExtra = new ArrayList<>();
                hospitalMealRecipeMapper.selectList(
                    Wrappers.lambdaQuery(HospitalMealRecipe.class).eq(HospitalMealRecipe::getPlanId, e.getId())
                ).forEach(t -> {
                    switch (t.getMealTime()) {
                        case "早餐" -> {
                            CookbookVo cookbook = new CookbookVo();
                            cookbook.setCookbookName(t.getFoodName());
                            cookbook.setTotal(t.getFoodWeight());
                            cookbook.setPrice(t.getPrice());
                            cookbook.setCount(t.getAmount());
                            cookbook.setRefundCount(0L);
                            cookbook.setRefundAmount(new BigDecimal("0"));
                            cookbook.setRefundDeductionAmount(new BigDecimal("0"));
                            cookbook.setIngredients(foodMap.get(t.getFoodName()));
                            breakfast.add(cookbook);
                        }
                        case "早中" -> {
                            CookbookVo cookbook = new CookbookVo();
                            cookbook.setCookbookName(t.getFoodName());
                            cookbook.setTotal(t.getFoodWeight());
                            cookbook.setPrice(t.getPrice());
                            cookbook.setCount(t.getAmount());
                            cookbook.setRefundCount(0L);
                            cookbook.setRefundAmount(new BigDecimal("0"));
                            cookbook.setRefundDeductionAmount(new BigDecimal("0"));
                            cookbook.setIngredients(foodMap.get(t.getFoodName()));
                            breakfastExtra.add(cookbook);
                        }
                        case "中餐" -> {
                            CookbookVo cookbook = new CookbookVo();
                            cookbook.setCookbookName(t.getFoodName());
                            cookbook.setTotal(t.getFoodWeight());
                            cookbook.setPrice(t.getPrice());
                            cookbook.setCount(t.getAmount());
                            cookbook.setRefundCount(0L);
                            cookbook.setRefundAmount(new BigDecimal("0"));
                            cookbook.setRefundDeductionAmount(new BigDecimal("0"));
                            cookbook.setIngredients(foodMap.get(t.getFoodName()));
                            lunch.add(cookbook);
                        }
                        case "中加" -> {
                            CookbookVo cookbook = new CookbookVo();
                            cookbook.setCookbookName(t.getFoodName());
                            cookbook.setTotal(t.getFoodWeight());
                            cookbook.setPrice(t.getPrice());
                            cookbook.setCount(t.getAmount());
                            cookbook.setRefundCount(0L);
                            cookbook.setRefundAmount(new BigDecimal("0"));
                            cookbook.setRefundDeductionAmount(new BigDecimal("0"));
                            cookbook.setIngredients(foodMap.get(t.getFoodName()));
                            lunchExtra.add(cookbook);
                        }
                        case "晚餐" -> {
                            CookbookVo cookbook = new CookbookVo();
                            cookbook.setCookbookName(t.getFoodName());
                            cookbook.setTotal(t.getFoodWeight());
                            cookbook.setPrice(t.getPrice());
                            cookbook.setCount(t.getAmount());
                            cookbook.setRefundCount(0L);
                            cookbook.setRefundAmount(new BigDecimal("0"));
                            cookbook.setRefundDeductionAmount(new BigDecimal("0"));
                            cookbook.setIngredients(foodMap.get(t.getFoodName()));
                            dinner.add(cookbook);
                        }
                        case "晚加" -> {
                            CookbookVo cookbook = new CookbookVo();
                            cookbook.setCookbookName(t.getFoodName());
                            cookbook.setTotal(t.getFoodWeight());
                            cookbook.setPrice(t.getPrice());
                            cookbook.setCount(t.getAmount());
                            cookbook.setRefundCount(0L);
                            cookbook.setRefundAmount(new BigDecimal("0"));
                            cookbook.setRefundDeductionAmount(new BigDecimal("0"));
                            cookbook.setIngredients(foodMap.get(t.getFoodName()));
                            dinnerExtra.add(cookbook);
                        }
                    }
                });

                vo.setBreakfast(breakfast);
                vo.setBreakfastExtra(breakfastExtra);
                vo.setLunch(lunch);
                vo.setLunchExtra(lunchExtra);
                vo.setDinner(dinner);
                vo.setDinnerExtra(dinnerExtra);
                vo.setDietaryExpenses(e.getTotalPrice());
                return vo;
            }));
        } else {

            Page<DailyMealPlan> page = dailyMealPlanMapper.selectPage(
                pageQuery.build(),
                Wrappers.lambdaQuery(DailyMealPlan.class)
                    .ge(bo.getCalculationDateEarliest() != null, DailyMealPlan::getCreateTime, bo.getCalculationDateEarliest())
                    .le(bo.getCalculationDateLatest() != null, DailyMealPlan::getCreateTime, bo.getCalculationDateLatest())
                    .eq(bo.getPatientDepartmentId() != null, DailyMealPlan::getDeptId, bo.getPatientDepartmentId())
                    .eq(bo.getDoctorDepartmentId() != null, DailyMealPlan::getCreateDept, bo.getDoctorDepartmentId())
                    .in(!ids.isEmpty(), DailyMealPlan::getPatientId, ids)
            );

            return TableDataInfo.build(page.convert(e -> {
                OtherDietaryPrescriptionVo vo = new OtherDietaryPrescriptionVo();
                vo.setId(e.getId());
                vo.setCreateTime(e.getCreateTime());
                vo.setConsultationType(Objects.equals(e.getType(), "0") ? "门诊" : "住院");
                vo.setDietaryType("日常膳食");
                vo.setDoctorDepartment(deptMap.get(e.getCreateDept()));
                vo.setDoctor(userMap.get(e.getCreateBy()));
                vo.setPatientDepartment(deptMap.get(e.getDeptId()));
                vo.setPatient(patientMap.get(e.getPatientId()));
                return vo;
            }));
        }
    }

    @Override
    public TableDataInfo listPageDietaryInventory(DietaryInventoryBo bo, PageQuery pageQuery) {
        return null;
    }

    @Override
    public TableDataInfo listPageInventory(InventoryBo bo, PageQuery pageQuery) {
        return null;
    }

    @Override
    public TableDataInfo listPageInHospitalBillingReconciliation(InHospitalBillingReconciliationBo bo, PageQuery pageQuery) {
        Page<ChargeRecord> page = chargeRecordMapper.selectPage(
            pageQuery.build(),
            Wrappers.lambdaQuery(ChargeRecord.class)
                .ge(bo.getTradeDateEarliest() != null, ChargeRecord::getCreateTime, bo.getTradeDateEarliest())
                .le(bo.getTradeDateLatest() != null, ChargeRecord::getCreateTime, bo.getTradeDateLatest())
                .eq(bo.getPatientDepartmentId() != null, ChargeRecord::getDoorId, bo.getPatientDepartmentId())
                .eq(bo.getDepartmentId() != null, ChargeRecord::getCreateDept, bo.getDepartmentId())
                .eq(bo.getConsultationType() != null, ChargeRecord::getVisitType, bo.getConsultationType())
                .eq(bo.getPayStatus() != null, ChargeRecord::getPaymentStatus, bo.getPayStatus())
                .eq(bo.getPayMethod() != null, ChargeRecord::getPaymentMethod, bo.getPayMethod())
        );

        Map<Long, String> departmentMap = new HashMap<>();
        Map<Long, String> doctorMap = new HashMap<>();
        Map<Long, String> patientMap = new HashMap<>();
        Map<String, String> payStatusMap = new HashMap<>();
        Map<String, String> payMethodMap = new HashMap<>();
        Map<String, String> feeTypeMap = new HashMap<>();

        sysDeptMapper.selectList().forEach(e -> departmentMap.put(e.getDeptId(), e.getDeptName()));
        sysUserMapper.selectList().forEach(e -> doctorMap.put(e.getUserId(), e.getName()));
        treatmentUserMapper.selectList().forEach(e -> patientMap.put(e.getId(), e.getTreatName()));
        sysDictDataMapper.selectDictDataByType("payment_status").forEach(e -> payStatusMap.put(e.getDictValue(), e.getDictLabel()));
        sysDictDataMapper.selectDictDataByType("charge_way").forEach(e -> payMethodMap.put(e.getDictValue(), e.getDictLabel()));
        sysDictDataMapper.selectDictDataByType("fee_type").forEach(e -> feeTypeMap.put(e.getDictValue(), e.getDictLabel()));

        return TableDataInfo.build(page.convert(e -> {
            InHospitalBillingReconciliationVo vo = new InHospitalBillingReconciliationVo();
            vo.setCreateTime(e.getCreateTime());
            vo.setPatientDepartment(departmentMap.get(e.getDoorId()));
            vo.setPatient(patientMap.get(e.getPatientId()));
            vo.setCardId(e.getIdCard());
            vo.setConsultationType(Objects.equals(e.getVisitType(), "0") ? "门诊" : "住院");
            vo.setMedicalId(e.getPatientNo());
            vo.setOrderType(feeTypeMap.get(e.getChargeType()));
            vo.setDoctor(doctorMap.get(e.getCreateBy()));
            vo.setDepartment(departmentMap.get(e.getCreateDept()));
            vo.setAmount(e.getReceivableAmount());
            vo.setPayMethod(payMethodMap.get(e.getPaymentMethod()));
            vo.setActioner(doctorMap.get(e.getCreateBy()));
            vo.setTransactionId(settlementMapper.selectById(e.getSettlementId()).getTransactionId());
            return vo;
        }));
    }

    @Override
    public R listCost(CostBo bo) {
        if (bo.getType() == 1) {

            List<FoodVo> voList = new ArrayList<>();

            Map<Long, List<Long>> recipeToIngredientMap = new HashMap<>();
            sysRecipeFoodIngredientMapper.selectList().forEach(e -> {
                if (recipeToIngredientMap.containsKey(e.getRecipeId())) {
                    recipeToIngredientMap.get(e.getRecipeId()).add(e.getFoodIngredientId());
                } else {
                    recipeToIngredientMap.put(e.getRecipeId(), List.of(e.getFoodIngredientId()));
                }
            });
            List<SysRecipe> recipes = sysRecipeMapper.selectList();
            List<SysFoodIngredient> ingredients = sysFoodIngredientMapper.selectList();
            List<HospitalMealRecipe> list = hospitalMealRecipeMapper.selectList();

            for (SysRecipe recipe : recipes) {
                int count = 0;
                for (HospitalMealRecipe element : list) if (Objects.equals(element.getFoodId(), recipe.getRecipeId())) count++;

                if (count != 0) {
                    FoodVo foodVo = new FoodVo();
                    foodVo.setFoodName(recipe.getName());

                    BigDecimal cost = new BigDecimal("0");

                    List<String> ingredientNames = new ArrayList<>();
                    for (Long ingredientId : recipeToIngredientMap.get(recipe.getRecipeId()))
                        for (SysFoodIngredient e : ingredients) {
                            if (Objects.equals(ingredientId, e.getFoodIngredientId())) ingredientNames.add(e.getName());
                            if (e.getPurchasePrice() != null) cost = cost.add(e.getPurchasePrice());
                        }

                    foodVo.setIngredients(ingredientNames);
                    foodVo.setAccount(count);
                    foodVo.setCost(cost);
                    foodVo.setAmount(recipe.getPrice());
                    voList.add(foodVo);
                }

            }

            return R.ok(voList);
        } else {
            List<CostPrescriptionVo> result = new ArrayList<>();

            List<EnteralNutrition> enteralNutritionList = enteralNutritionMapper.selectList(
                Wrappers.lambdaQuery(EnteralNutrition.class)
                    .eq(EnteralNutrition::getPrescriptionType, String.valueOf(bo.getType()))
            );
            List<ProductNutrition> productNutritionList = productNutritionMapper.selectList();
            List<SysDept> deptList = sysDeptMapper.selectList();

            for (SysDept dept : deptList) {
                int deptCount = 0;
                Long deptId = dept.getDeptId();
                List<ProductVo> productList = new ArrayList<>();
                for (ProductNutrition productNutrition : productNutritionList) {

                    if (Objects.equals(productNutrition.getCreateDept(), deptId)) deptCount++;

                    int count = 0;
                    for (EnteralNutrition enteralNutrition : enteralNutritionList) {

                        if (!Objects.equals(enteralNutrition.getNutritionProductId(), productNutrition.getId())) continue;
                        if (Objects.isNull(enteralNutrition.getQuantity())) continue;

                        count += enteralNutrition.getQuantity();
                    }

                    if (count == 0) continue;

                    ProductVo vo = new ProductVo();
                    vo.setId(productNutrition.getId());
                    vo.setName(productNutrition.getProductName());
                    vo.setSalesQuantity(count);
                    vo.setSalesCost(productNutrition.getPurchasePrice().multiply(new BigDecimal(count)));
                    vo.setSalesAmount(productNutrition.getConfigSalePrice().multiply(new BigDecimal(count)));
                    productList.add(vo);
                }

                if (deptCount == 0) continue;

                CostPrescriptionVo vo = new CostPrescriptionVo();
                vo.setId(deptId);
                vo.setName(dept.getDeptName());
                vo.setProductList(productList);
                result.add(vo);
            }

            CostPrescriptionVo vo = new CostPrescriptionVo();
            vo.setId(null);
            vo.setName("合计");
            List<ProductVo> productVoList = new ArrayList<>();

            for (CostPrescriptionVo costPrescriptionVo : result) {
                for (ProductVo prescriptionVo : costPrescriptionVo.getProductList()) {

                    int count = productVoList.stream()
                        .filter(e -> Objects.equals(e.getId(), prescriptionVo.getId()))
                        .toList().size();

                    if (count == 0)
                        productVoList.add(prescriptionVo);
                    else
                        productVoList = productVoList.stream()
                            .filter(e -> Objects.equals(e.getId(), prescriptionVo.getId()))
                            .peek(e -> {
                                e.setSalesQuantity(e.getSalesQuantity() + prescriptionVo.getSalesQuantity());
                                e.setSalesCost(e.getSalesCost().add(prescriptionVo.getSalesCost()));
                                e.setSalesAmount(e.getSalesAmount().add(prescriptionVo.getSalesAmount()));
                            }).toList();
                }
            }

            vo.setProductList(productVoList);
            result.add(vo);

            return R.ok(result);
        }
    }

    @Override
    public TableDataInfo listPageProgressNote(ProgressNoteBo bo, PageQuery pageQuery) {

        List<Long> ids = new ArrayList<>();
        treatmentUserMapper.selectList(
            Wrappers.lambdaQuery(TreatmentUser.class).like(TreatmentUser::getTreatName, bo.getPatient())
        ).forEach(e -> ids.add(e.getId()));

        Map<Long, String> departmentMap = new HashMap<>();
        Map<Long, String> doctorMap = new HashMap<>();
        Map<Long, String> patientMap = new HashMap<>();
        Map<String, String> payStatusMap = new HashMap<>();
        Map<String, String> payMethodMap = new HashMap<>();
        Map<String, String> feeTypeMap = new HashMap<>();

        sysDeptMapper.selectList().forEach(e -> departmentMap.put(e.getDeptId(), e.getDeptName()));
        sysUserMapper.selectList().forEach(e -> doctorMap.put(e.getUserId(), e.getName()));
        treatmentUserMapper.selectList().forEach(e -> patientMap.put(e.getId(), e.getTreatName()));
        sysDictDataMapper.selectDictDataByType("payment_status").forEach(e -> payStatusMap.put(e.getDictValue(), e.getDictLabel()));
        sysDictDataMapper.selectDictDataByType("charge_way").forEach(e -> payMethodMap.put(e.getDictValue(), e.getDictLabel()));
        sysDictDataMapper.selectDictDataByType("fee_type").forEach(e -> feeTypeMap.put(e.getDictValue(), e.getDictLabel()));

        List<ChargeRecord> records = chargeRecordMapper.selectList(Wrappers.lambdaQuery(ChargeRecord.class).in(!ids.isEmpty(), ChargeRecord::getPatientId, ids));

        Page<TreatmentUser> page = treatmentUserMapper.selectPage(
            pageQuery.build(),
            Wrappers.lambdaQuery(TreatmentUser.class)
                .ge(bo.getCreateTimeEarliest() != null, TreatmentUser::getCreateTime, bo.getCreateTimeEarliest())
                .le(bo.getCreateTimeLatest() != null, TreatmentUser::getCreateTime, bo.getCreateTimeLatest())
                .eq(bo.getPatientDepartmentId() != null, TreatmentUser::getDoorId, bo.getPatientDepartmentId())
                .eq(!ids.isEmpty(), TreatmentUser::getId, ids)
        );

        return TableDataInfo.build(page.convert(e -> {
            ProgressNoteVo vo = new ProgressNoteVo();
            vo.setPatientName(e.getTreatName());
            vo.setHeight(e.getHeight());
            vo.setWeight(e.getWeight());
            vo.setBmi(e.getBmi());
            vo.setIdCard(e.getIdCard());
            vo.setConsultationType(Objects.equals(e.getType(), "0") ? "门诊" : "住院");
            vo.setPatientDepartment(departmentMap.get(e.getDoorId()));
            vo.setMedicalId(e.getTreatNum());
            vo.setCreateTime(e.getCreateTime());

            int screeningCount = 0, assessmentCount = 0;
            BigDecimal amount = new BigDecimal("0");
            for (ChargeRecord record : records) {
                if (!Objects.equals(record.getPatientId(), e.getId()) || Objects.isNull(record.getFundsReceived())) continue;
                if (Objects.equals(record.getChargeType(), "0")) {
                    screeningCount++;
                    amount = amount.add(record.getFundsReceived());
                }
                if (Objects.equals(record.getChargeType(), "1")) {
                    assessmentCount++;
                    amount = amount.add(record.getFundsReceived());
                }
            }
            vo.setNutritionScreeningCount(screeningCount);
            vo.setNutritionAssessmentCount(assessmentCount);

            vo.setNutritionDiagnosesCount(0);
            vo.setNutritionInterventionCount(0);
            vo.setNutritionMealCount(0);
            vo.setNutritionEducationCount(0);
            vo.setAmount(amount);
            return vo;
        }));
    }

    @Override
    public R getIntraHospitalData(Timestamp start, Timestamp end, Long id) {
        return R.ok();
    }

    @Override
    public TableDataInfo<PrescriptionVo> getEnteralNutrition(EnteralNutritionPrescriptionBo bo, PageQuery pageQuery) {

        Map<Long, String> patientMap = new HashMap<>();
        Map<Long, String> deptMap = new HashMap<>();
        Map<Long, String> userMap = new HashMap<>();
        List<Long> ids = new ArrayList<>();
        Map<String, String> payStatusMap = new HashMap<>();
        Map<String, String> consultationMap = new HashMap<>();

        treatmentUserMapper.selectList().forEach(e -> patientMap.put(e.getId(), e.getTreatName()));
        sysDeptMapper.selectList().forEach(e -> deptMap.put(e.getDeptId(), e.getDeptName()));
        sysUserMapper.selectList().forEach(e -> userMap.put(e.getUserId(), e.getName()));
        treatmentUserMapper.selectList().forEach(e -> ids.add(e.getId()));
        sysDictDataMapper.selectDictDataByType("payment_status").forEach(e -> payStatusMap.put(e.getDictValue(), e.getDictLabel()));
        sysDictDataMapper.selectDictDataByType("fee_type").forEach(e -> consultationMap.put(e.getDictValue(), e.getDictLabel()));
        List<ProductNutrition> productNutritionList = productNutritionMapper.selectList();

        List<EnteralNutrition> enteralNutritionList = enteralNutritionMapper.selectList();
        IPage<Settlement> settlementPage = settlementMapper.selectPage(
            pageQuery.build(),
            Wrappers.lambdaQuery(Settlement.class)
                .ge(bo.getCreateDateEarliest() != null, Settlement::getCreateTime, bo.getCreateDateEarliest())
                .le(bo.getCreateDateLatest() != null, Settlement::getCreateTime, bo.getCreateDateLatest())
                .eq(bo.getPatientDepartmentId() != null, Settlement::getDoorId, bo.getPatientDepartmentId())
                .eq(bo.getDoctorDepartmentId() != null, Settlement::getCreateDept, bo.getDoctorDepartmentId())
        );
        List<Long> settlementIds = new ArrayList<>();
        settlementPage.getRecords().forEach(e -> settlementIds.add(e.getId()));
        List<ChargeRecord> records = chargeRecordMapper.selectList(
            Wrappers.lambdaQuery(ChargeRecord.class)
                .in(!settlementIds.isEmpty(), ChargeRecord::getSettlementId, settlementIds)
        );

        List<PrescriptionVo> list = new ArrayList<>();

        for (Settlement settlement : settlementPage.getRecords()) {
            PrescriptionVo vo = new PrescriptionVo();
            vo.setPrescriptionId(settlement.getId());

            ChargeRecord record = null;
            for (ChargeRecord element : records)
                if (Objects.equals(element.getSettlementId(), settlement.getId()))
                    record = element;

            vo.setTradeTime(Objects.nonNull(record) ? record.getCreateTime() : null);
            vo.setOpeningDate(settlement.getOrderTime());
            vo.setPatientVisitTypeName(Objects.equals(settlement.getVisitType(), "0") ? "门诊" : "住院");
            vo.setPatientName(patientMap.get(settlement.getPatientId()));
            vo.setModelTypeName(consultationMap.get(settlement.getChargeType()));
            vo.setDoctorDeptName(deptMap.get(settlement.getCreateDept()));
            vo.setDoctorUserName(userMap.get(settlement.getCreateBy()));
            vo.setDoctorWorkNo(null);
            vo.setPayStatusName(payStatusMap.get(settlement.getPaymentStatus()));
            vo.setRealPrice(Objects.nonNull(record) ? record.getFundsReceived() : null);
            vo.setRealRefundPrice(Objects.nonNull(record) ? record.getRefundAmount() : null);
            vo.setRealLossPrice(new BigDecimal("0"));
            vo.setPatientDeptName(deptMap.get(settlement.getDoorId()));

            List<PrescriptionDetailVo> detailList = new ArrayList<>();

            for (EnteralNutrition enteralNutrition : enteralNutritionList) {
                if (!Objects.equals(settlement.getId(), enteralNutrition.getSettlementId())) continue;

                ProductNutrition productNutrition = null;
                for (ProductNutrition element : productNutritionList)
                    if (Objects.equals(element.getId(), enteralNutrition.getNutritionProductId()))
                        productNutrition = element;

                PrescriptionDetailVo detailVo = new PrescriptionDetailVo();
                detailVo.setName(enteralNutrition.getNutritionProduct());
                detailVo.setSpecsName(enteralNutrition.getSpecification());
                detailVo.setUnitDosage(enteralNutrition.getTotalDose());
                detailVo.setUnitPrice(enteralNutrition.getAmount());
                detailVo.setProductNo(Objects.nonNull(productNutrition) ? productNutrition.getProductCode() : null);
                detailVo.setSpecsUnitName(Objects.nonNull(productNutrition) ? productNutrition.getMinUnit() : null);
                detailVo.setRefundDosage("0");
                detailVo.setLossDosage("0");
                detailVo.setGroupNo(Integer.valueOf(enteralNutrition.getGroupNo()));
                detailVo.setTotalNum(enteralNutrition.getQuantity() != null ? enteralNutrition.getQuantity().intValue() : null);
                detailVo.setConfigNum(0);
                detailVo.setConfigRefundNum(0);
                detailVo.setConfigAmount(Objects.nonNull(productNutrition) ? productNutrition.getConfigSalePrice() : null);
                detailList.add(detailVo);
            }

            vo.setDetailList(detailList);
            list.add(vo);
        }

//        EnteralNutritionPrescriptionVo vo = new EnteralNutritionPrescriptionVo();
//        vo.setList(list);
//        vo.setCount(settlementPage.getSize());
        IPage<PrescriptionVo> page = new Page<>();
        page.setPages(settlementPage.getPages());
        page.setRecords(list);
        page.setTotal(settlementPage.getTotal());
        page.setSize(settlementPage.getSize());
        page.setCurrent(settlementPage.getCurrent());

        return TableDataInfo.build(page);
    }

    @Override
    public TableDataInfo<ListProductVo> listProduct(ListProductBo bo, PageQuery pageQuery) {

        Map<Long, String> typeMap = new HashMap<>();
        Map<Long, String> manufacturerMap = new HashMap<>();
        Map<Long, String> providerMap = new HashMap<>();
        Map<String, String> unitMap = new HashMap<>();

        productManufacturerMapper.selectList().forEach(e -> manufacturerMap.put(e.getId(), e.getName()));
        productSupplierMapper.selectList().forEach(e -> providerMap.put(e.getId(), e.getName()));
        sysDictDataMapper.selectDictDataByType("product_package_unit").forEach(e -> unitMap.put(e.getDictValue(), e.getDictLabel()));

        if (bo.getProductType() == 0) {

            productCategoryMapper.selectList().forEach(e -> typeMap.put(e.getCategoryId(), e.getCategoryName()));

            IPage<ProductNutrition> page = productNutritionMapper.selectPage(
                pageQuery.build(),
                Wrappers.lambdaQuery(ProductNutrition.class)
                    .ge(bo.getTradeDateEarliest() != null, ProductNutrition::getCreateTime, bo.getTradeDateEarliest())
                    .le(bo.getTradeDateLatest() != null, ProductNutrition::getCreateTime, bo.getTradeDateLatest())
                    .eq(bo.getManufacturerId() != null, ProductNutrition::getManufacturer, bo.getManufacturerId())
                    .eq(bo.getProviderId() != null, ProductNutrition::getSupplier, bo.getProviderId())
                    .like(bo.getProductName() != null, ProductNutrition::getProductName, bo.getProductName())
            );
            List<EnteralNutrition> enteralNutritionList = enteralNutritionMapper.selectList();

            return TableDataInfo.build(page.convert(e -> {
                ListProductVo vo = new ListProductVo();
                vo.setTradeDate(e.getCreateTime());
                vo.setHospitalSystemCode(e.getHospitalSystemCode());
                if (Objects.nonNull(e.getProductCategory())) {
                    String[] types = e.getProductCategory().split(",");
                    String productType = "";
                    for (String type : types) {
                        Long typeId = Long.valueOf(type);
                        productType += typeMap.get(typeId) + ",";
                    }
                    vo.setProductClassification(productType);
                }

                String minUnit = unitMap.get(e.getMinUnit());

                vo.setProductType("营养产品");
                vo.setProductName(e.getProductName());
                vo.setProductSpecification(e.getProductSpec() + minUnit);
                vo.setProviderName(Objects.nonNull(e.getSupplier()) && !e.getSupplier().isEmpty() ? providerMap.get(Long.valueOf(e.getSupplier())) : null);
                vo.setManufacturerName(Objects.nonNull(e.getManufacturer()) && !e.getManufacturer().isEmpty() ? manufacturerMap.get(Long.valueOf(e.getManufacturer())) : null);

                String prePackageUnit = unitMap.get(e.getPackageUnit());
                String configureUnit = unitMap.get(e.getMinUnit());

                int prePackageCount = 0, configureCount = 0, longTermCount = 0;
                for (EnteralNutrition enteralNutrition : enteralNutritionList) {
                    if (!Objects.equals(e.getId(), enteralNutrition.getNutritionProductId())) continue;

                    switch (enteralNutrition.getPrescriptionType()) {
                        case "2" -> prePackageCount++;
                        case "3" -> {
                            if (enteralNutrition.getUsageDays() <= 90) configureCount++;
                            else longTermCount++;
                        }
                    }
                }


                vo.setPrePackageSalesVolume(prePackageCount + ".00" + prePackageUnit);
                vo.setPrePackageSalesAmount(e.getPackagePrice().multiply(new BigDecimal(prePackageCount)));
                vo.setPrePackagePurchaseUnitPrice(new BigDecimal("0.00"));
                vo.setPrePackagePurchaseAmount(new BigDecimal("0.00"));
                vo.setConfigureSalesVolume(configureCount + ".00" + configureUnit);
                vo.setConfigureSalesAmount(e.getConfigSalePrice().multiply(new BigDecimal(configureCount)));
                vo.setLongTermPrescriptionSalesVolume(longTermCount + ".00" + configureUnit);
                vo.setLongTermPrescriptionSalesAmount(e.getConfigSalePrice().multiply(new BigDecimal(longTermCount)));
                vo.setPrePackageRefundVolume("0.00" + prePackageUnit);
                vo.setPrePackageRefundAmount(new BigDecimal("0.00"));
                vo.setConfigureRefundVolume("0.00" + configureUnit);
                vo.setConfigureRefundAmount(new BigDecimal("0.00"));
                vo.setLongTermPrescriptionRefundVolume("0.00" + configureUnit);
                vo.setLongTermPrescriptionRefundAmount(new BigDecimal("0.00"));
                return vo;
            }));
        } else {

            IPage<SuppliesManage> page = suppliesManageMapper.selectPage(
                pageQuery.build(),
                Wrappers.lambdaQuery(SuppliesManage.class)
            );
            suppliesCategoryMapper.selectList().forEach(e -> typeMap.put(e.getCategoryId(), e.getCategoryName()));
            List<EnteralNutritionConsumable> enteralNutritionConsumableList = enteralNutritionConsumableMapper.selectList();

            return TableDataInfo.build(page.convert(e -> {
                ListProductVo vo = new ListProductVo();
                vo.setTradeDate(e.getCreateTime());
                vo.setHospitalSystemCode(e.getHospitalSystemCode());
                vo.setProductType("耗材");

                if (Objects.nonNull(e.getSuppliesCategoryId())) {
                    String[] classifications = e.getSuppliesCategoryId().split(",");
                    String productClassification = "";
                    for (String classification : classifications) {
                        Long classificationId = Long.valueOf(classification);
                        productClassification += typeMap.get(classificationId) + ",";
                    }
                    vo.setProductClassification(productClassification);
                }

                String specificationUnit = unitMap.get(e.getSuppliesSpecUnit());

                vo.setProductName(e.getSuppliesName());
                vo.setProductSpecification(e.getSuppliesSpec() + specificationUnit);
                vo.setProviderName(Objects.nonNull(e.getSupplier()) && !e.getSupplier().isEmpty() ? providerMap.get(Long.valueOf(e.getSupplier())) : null);
                vo.setManufacturerName(Objects.nonNull(e.getManufacturer()) && !e.getManufacturer().isEmpty() ? manufacturerMap.get(Long.valueOf(e.getManufacturer())) : null);

                String prePackageUnit = unitMap.get(e.getSuppliesUnit());
                String configureUnit = unitMap.get(e.getSuppliesSpecUnit());

                int configureCount = 0, longTermCount = 0;
                for (EnteralNutritionConsumable enteralNutritionConsumable : enteralNutritionConsumableList) {
                    if (Objects.equals(e.getId(), enteralNutritionConsumable.getConsumableId())) continue;
                    if (enteralNutritionConsumable.getUsageDays() <= 90) configureCount++;
                    else longTermCount++;
                }

                vo.setPrePackageSalesVolume("0.00" + prePackageUnit);
                vo.setPrePackageSalesAmount(new BigDecimal("0.00"));
                vo.setPrePackagePurchaseUnitPrice(new BigDecimal("0.00"));
                vo.setPrePackagePurchaseAmount(new BigDecimal("0.00"));
                vo.setConfigureSalesVolume(configureCount + ".00" + configureUnit);
                vo.setConfigureSalesAmount(e.getSellPrice().multiply(new BigDecimal(configureCount)));
                vo.setLongTermPrescriptionSalesVolume(longTermCount + ".00" + configureUnit);
                vo.setLongTermPrescriptionSalesAmount(e.getSellPrice().multiply(new BigDecimal(longTermCount)));
                vo.setPrePackageRefundVolume("0.00" + prePackageUnit);
                vo.setPrePackageRefundAmount(new BigDecimal("0.00"));
                vo.setConfigureRefundVolume("0.00" + configureUnit);
                vo.setConfigureRefundAmount(new BigDecimal("0.00"));
                vo.setLongTermPrescriptionRefundVolume("0.00" + configureUnit);
                vo.setLongTermPrescriptionRefundAmount(new BigDecimal("0.00"));
                return vo;
            }));
        }
    }

    @Override
    public TableDataInfo listPageScreeningOrAssessment(ScreeningOrAssessmentBo bo, PageQuery pageQuery) {

        List<Long> ids = new ArrayList<>();

        treatmentUserMapper.selectList(
            Wrappers.lambdaQuery(TreatmentUser.class)
                .like(bo.getPatientName() != null, TreatmentUser::getTreatName, bo.getPatientName())
        ).forEach(e -> ids.add(e.getId()));


        Map<Long, String> deptMap = new HashMap<>();
        Map<Long, String> doctorMap = new HashMap<>();

        List<TreatmentUser> patientList = treatmentUserMapper.selectList();
        sysDeptMapper.selectList().forEach(e -> deptMap.put(e.getDeptId(), e.getDeptName()));
        sysUserMapper.selectList().forEach(e -> doctorMap.put(e.getUserId(), e.getName()));

        switch (bo.getType()) {
            case 1 -> {

                Map<Long, String> screeningTypeMap = new HashMap<>();
                sysScreeningAssessmentConfigMapper.selectList().forEach(e -> screeningTypeMap.put(e.getConfigId(), e.getName()));

                IPage<NutritionScreening> page = nutritionScreeningMapper.selectPage(
                    pageQuery.build(),
                    Wrappers.lambdaQuery(NutritionScreening.class)
                        .ge(bo.getCreateTimeEarliest() != null, NutritionScreening::getCreateTime, bo.getCreateTimeEarliest())
                        .le(bo.getCreateTimeLatest() != null, NutritionScreening::getCreateTime, bo.getCreateTimeLatest())
                        .eq(bo.getDoctorDepartmentId() != null, NutritionScreening::getCreateDept, bo.getDoctorDepartmentId())
                        .eq(bo.getConsultationType() != null, NutritionScreening::getVisitType, bo.getConsultationType())
                        .in(!ids.isEmpty(), NutritionScreening::getPatientId, ids)
                );

                return TableDataInfo.build(page.convert(e -> {
                    NutritionalScreeningVo vo = new NutritionalScreeningVo();
                    vo.setCreateTime(e.getScreeningTime());
                    vo.setDoctorName(doctorMap.get(e.getCreateBy()));
                    vo.setDoctorDepartment(deptMap.get(e.getCreateDept()));
                    patientList.forEach(patient -> {
                        if (patient.getId().equals(e.getPatientId())) {
                            vo.setSicknessArea(patient.getWardName());
                            vo.setPatientName(patient.getTreatName());
                            vo.setBmi(patient.getBmi());
                            vo.setVisitType(Objects.equals(e.getVisitType(), "0") ? "门诊" : "住院");
                            vo.setPatientDepartment(deptMap.get(patient.getDoorId()));
                            vo.setMedicalId(patient.getTreatNum());
                            vo.setHeight(patient.getHeight());
                            vo.setWeight(patient.getWeight());
                        }
                    });
                    vo.setScreeningType(screeningTypeMap.get(e.getConfigId()));
                    vo.setScreeningScore(e.getScreeningScore());
                    vo.setScreeningConclusion(e.getScreeningConclusion());
                    return vo;
                }));
            }
            case 2 -> {

                Map<Long, String> configMap = new HashMap<>();
                sysScreeningAssessmentConfigMapper.selectList().forEach(e -> configMap.put(e.getConfigId(), e.getName()));

                IPage<NutritionEvaluation> page = nutritionEvaluationMapper.selectPage(
                    pageQuery.build(),
                    Wrappers.lambdaQuery(NutritionEvaluation.class)
                        .ge(bo.getCreateTimeEarliest() != null, NutritionEvaluation::getCreateTime, bo.getCreateTimeEarliest())
                        .le(bo.getCreateTimeLatest() != null, NutritionEvaluation::getCreateTime, bo.getCreateTimeLatest())
                        .eq(bo.getDoctorDepartmentId() != null, NutritionEvaluation::getCreateDept, bo.getDoctorDepartmentId())
                        .eq(bo.getConsultationType() != null, NutritionEvaluation::getVisitType, bo.getConsultationType())
                        .in(!ids.isEmpty(), NutritionEvaluation::getPatientId, ids)
                );

                return TableDataInfo.build(page.convert(e -> {
                    NutritionalEvaluationVo vo = new NutritionalEvaluationVo();
                    vo.setCreateTime(e.getCreateTime());
                    vo.setDoctor(doctorMap.get(e.getCreateBy()));
                    vo.setDoctorDepartment(deptMap.get(e.getCreateDept()));

                    patientList.forEach(patient -> {
                        if (e.getPatientId().equals(patient.getId())) {
                            vo.setConsultationType(Objects.equals(e.getVisitType(), "0") ? "门诊" : "住院");
                            vo.setSicknessArea(patient.getWardName());
                            vo.setPatientName(patient.getTreatName());
                            vo.setBmi(patient.getBmi());
                            vo.setPatientDepartment(deptMap.get(patient.getDoorId()));
                            vo.setMedicalId(patient.getTreatNum());
                            vo.setHeight(patient.getHeight());
                            vo.setWeight(patient.getWeight());
                            vo.setAdmissionId(patient.getOutpatientNo());
                        }
                    });

                    vo.setEvaluationType(configMap.get(e.getConfigId()));
                    vo.setEvaluationScore(new BigDecimal("0"));
                    vo.setEvaluationConclusion(e.getContent());
                    return vo;
                }));
            }
            case 3 -> {

                Map<Long, String> configMap = new HashMap<>();
                Map<Long, String> screeningTypeMap = new HashMap<>();
                Map<Long, String> diseaseLabelMap = new HashMap<>();

                sysScreeningAssessmentConfigMapper.selectList().forEach(e -> configMap.put(e.getConfigId(), e.getName()));
                sysScreeningAssessmentConfigMapper.selectList().forEach(e -> screeningTypeMap.put(e.getConfigId(), e.getName()));
                sysDiseaseLabelMapper.selectList().forEach(e -> diseaseLabelMap.put(e.getLabelId(), e.getLabelName()));

                IPage<NutritionDiagnosis> page = nutritionDiagnosisMapper.selectPage(
                    pageQuery.build(),
                    Wrappers.lambdaQuery(NutritionDiagnosis.class)
                        .ge(bo.getCreateTimeEarliest() != null, NutritionDiagnosis::getCreateTime, bo.getCreateTimeEarliest())
                        .le(bo.getCreateTimeLatest() != null, NutritionDiagnosis::getCreateTime, bo.getCreateTimeLatest())
                        .eq(bo.getDoctorDepartmentId() != null, NutritionDiagnosis::getCreateDept, bo.getDoctorDepartmentId())
                        .eq(bo.getConsultationType() != null, NutritionDiagnosis::getType, bo.getConsultationType())
                        .in(!ids.isEmpty(), NutritionDiagnosis::getTreatmentUserId, ids)
                );

                return TableDataInfo.build(page.convert(e -> {
                    NutritionalDiagnosisVo vo = new NutritionalDiagnosisVo();
                    vo.setCreateTime(e.getCreateTime());
                    vo.setDoctor(doctorMap.get(e.getCreateBy()));
                    vo.setDoctorDepartment(deptMap.get(e.getCreateDept()));

                    patientList.forEach(patient -> {
                        if (e.getTreatmentUserId().equals(patient.getId())) {
                            vo.setConsultationType(Objects.equals(e.getType(), "0") ? "门诊" : "住院");
                            vo.setPatientName(patient.getTreatName());
                            vo.setBmi(patient.getBmi());
                            vo.setPatientDepartment(deptMap.get(patient.getDoorId()));
                            vo.setMedicalId(patient.getTreatNum());
                            vo.setHeight(patient.getHeight());
                            vo.setWeight(patient.getWeight());
                            vo.setAdmissionId(patient.getOutpatientNo());
                        }
                    });

                    List<Long> diagnosisBasisIds = new ArrayList<>();
                    if (e.getDiagnosisBasisId() != null && !e.getDiagnosisBasisId().isEmpty()) {
                        String[] diagnosisBasisIdsInString = e.getDiagnosisBasisId().split(",");
                        for (String diagnosisBasisId : diagnosisBasisIdsInString) diagnosisBasisIds.add(Long.valueOf(diagnosisBasisId));
                        String diagnosisBasis = "";

                        List<NutritionScreening> nutritionScreeningList = nutritionScreeningMapper.selectList(
                            Wrappers.lambdaQuery(NutritionScreening.class)
                                .in(!diagnosisBasisIds.isEmpty(), NutritionScreening::getId, diagnosisBasisIds)
                        );
                        List<NutritionEvaluation> nutritionEvaluationList = nutritionEvaluationMapper.selectList(
                            Wrappers.lambdaQuery(NutritionEvaluation.class)
                                .in(!diagnosisBasisIds.isEmpty(), NutritionEvaluation::getId, diagnosisBasisIds)
                        );

                        for (NutritionScreening nutritionScreening : nutritionScreeningList)
                            diagnosisBasis += screeningTypeMap.get(nutritionScreening.getConfigId()) + ",";
                        for (NutritionEvaluation nutritionEvaluation : nutritionEvaluationList)
                            diagnosisBasis += configMap.get(nutritionEvaluation.getConfigId()) + ",";

                        vo.setDiagnosisBasis(diagnosisBasis);
                    }

                    if (e.getDiagnosisLableId() != null && !e.getDiagnosisLableId().isEmpty()) {
                        String[] diagnosisLabelIds = e.getDiagnosisLableId().split(",");
                        String nutritionDiagnosis = "";

                        for (String diagnosisLabelIdStr : diagnosisLabelIds)
                            nutritionDiagnosis += diseaseLabelMap.get(Long.valueOf(diagnosisLabelIdStr)) + ",";

                        vo.setNutritionDiagnosis(nutritionDiagnosis);
                    }

                    return vo;
                }));
            }
            case 4 -> {

                IPage<NutritionEducation> page = nutritionEducationMapper.selectPage(
                    pageQuery.build(),
                    Wrappers.lambdaQuery(NutritionEducation.class)
                        .ge(bo.getCreateTimeEarliest() != null, NutritionEducation::getCreateTime, bo.getCreateTimeEarliest())
                        .le(bo.getCreateTimeLatest() != null, NutritionEducation::getCreateTime, bo.getCreateTimeLatest())
                        .eq(bo.getDoctorDepartmentId() != null, NutritionEducation::getCreateDept, bo.getDoctorDepartmentId())
                        .eq(bo.getConsultationType() != null, NutritionEducation::getType, bo.getConsultationType())
                        .in(!ids.isEmpty(), NutritionEducation::getPatientId, ids)
                );

                return TableDataInfo.build(page.convert(e -> {
                    NutritionalEducationVo vo = new NutritionalEducationVo();
                    vo.setCreateTime(e.getCreateTime());
                    vo.setEducationTitle(e.getEducationTitle());
                    vo.setDoctor(doctorMap.get(e.getCreateBy()));
                    vo.setDoctorDepartment(deptMap.get(e.getCreateDept()));

                    for (TreatmentUser patient : patientList) {
                        if (e.getPatientId().equals(patient.getId())) {
                            vo.setConsultationType(Objects.equals(e.getType(), "0") ? "门诊" : "住院");
                            vo.setPatientName(patient.getTreatName());
                            vo.setPatientDepartment(deptMap.get(patient.getDoorId()));
                            vo.setAdmissionId(patient.getOutpatientNo());
                            vo.setSicknessArea(patient.getWardName());
                        }
                    }

                    return vo;
                }));
            }
            default -> throw new RuntimeException("位置报表类型!");
        }

    }

}
