package org.dromara.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.BizConst;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.enums.biz.*;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysDictDataService;
import org.dromara.web.domain.*;
import org.dromara.web.domain.bo.EnteralNutritionBo;
import org.dromara.web.domain.bo.EnteralNutritionConsumableBo;
import org.dromara.web.domain.bo.EnteralNutritionSaveBo;
import org.dromara.web.domain.bo.SettlementBo;
import org.dromara.web.domain.vo.*;
import org.dromara.web.mapper.*;
import org.dromara.web.service.IEnteralNutritionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 肠内营养Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-22
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class EnteralNutritionServiceImpl implements IEnteralNutritionService {

    private final EnteralNutritionMapper baseMapper;
    private final SettlementMapper settlementMapper;
    private final EnteralNutritionConsumableMapper consumableMapper;
    private final TreatmentUserMapper treatmentUserMapper;
    private final ProductNutritionMapper productNutritionMapper;
    private final SuppliesManageMapper suppliesManageMapper;
    private final SysUserMapper userMapper;
    private final ISysDictDataService dataService;

    private final SysDeptMapper deptMapper;


    /**
     * 查询肠内营养
     *
     * @param id 主键
     * @return 肠内营养
     */
    @Override
    public EnteralNutritionVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    public List<EnteralNutritionVo> queryBySettlementId(Long settlementId) {
        SettlementVo selectVoById = settlementMapper.selectVoById(settlementId);

        List<EnteralNutritionVo> nutritionVoList = baseMapper.selectVoList(new LambdaQueryWrapper<EnteralNutrition>().eq(EnteralNutrition::getSettlementId, selectVoById.getId()));
        if (CollUtil.isNotEmpty(nutritionVoList)) {
            Set<Long> userList = CollUtil.newHashSet();
            nutritionVoList.forEach(v -> {
                userList.add(v.getConfigBy());
                userList.add(v.getExecuteBy());
            });
            // 按settlementId和groupNo分组
            Map<String, List<EnteralNutritionVo>> groupedRecords = nutritionVoList.stream().collect(Collectors.groupingBy(r -> r.getSettlementId() + "_" + r.getGroupNo(), Collectors.toList()));

            Map<Long, String> userMap = userMapper.selectList(Wrappers.lambdaQuery(SysUser.class).select(SysUser::getUserId, SysUser::getNickName).in(SysUser::getUserId, userList)).stream().collect(Collectors.toMap(k1 -> k1.getUserId(), k2 -> k2.getNickName(), (k1, k2) -> k1));
            for (List<EnteralNutritionVo> group : groupedRecords.values()) {
                if (CollUtil.isEmpty(group)) continue;
                // 拼接id
                String enteralNutritionIds = group.stream().map(EnteralNutritionVo::getId).filter(Objects::nonNull).distinct().map(String::valueOf).collect(Collectors.joining(","));

                for (EnteralNutritionVo record : group) {
                    // 设置用户信息
                    record.setIdStr(enteralNutritionIds);
                    record.setCreateByName(userMap.get(record.getCreateBy()));
                    record.setConfigByName(userMap.get(record.getConfigBy()));
                    record.setExecuteByName(userMap.get(record.getExecuteBy()));

                }
            }

        }
        return nutritionVoList;
    }

    @Override
    public R<List<EnteralNutritionVo>> queryById(String ids) {
        List<EnteralNutritionVo> nutritionVoList = new ArrayList<>();
        if (StringUtils.isNotBlank(ids)) {
            // 获取当前登录用户的ID，并填充更新人信息
            Long userId = LoginHelper.getUserId();
            Optional.ofNullable(ids) // 处理ids可能为null的情况
                .map(str -> Arrays.stream(str.split(","))) // 按逗号分割
                .orElseGet(Stream::empty) // 如果ids为null，返回空流
                .map(String::trim) // 去除空格
                .filter(StringUtils::isNotBlank) // 过滤空字符串
                .forEach(id -> {
                    try {
                        Long parsedId = Long.parseLong(id);
                        EnteralNutritionVo enteralNutritionVo = baseMapper.selectVoById(parsedId);
                        nutritionVoList.add(enteralNutritionVo);
                    } catch (NumberFormatException e) {
                        log.error("Invalid ID format: {}", id, e); // 记录错误日志
                    }
                });
        }
        return R.ok(nutritionVoList);
    }

    //手动配置
    @Override
    public R manualConfig(String ids) {
        if (StringUtils.isNotBlank(ids)) {
            // 获取当前登录用户的ID，并填充更新人信息
            Long userId = LoginHelper.getUserId();
            Optional.ofNullable(ids) // 处理ids可能为null的情况
                .map(str -> Arrays.stream(str.split(","))) // 按逗号分割
                .orElseGet(Stream::empty) // 如果ids为null，返回空流
                .map(String::trim) // 去除空格
                .filter(StringUtils::isNotBlank) // 过滤空字符串
                .forEach(id -> {
                    try {
                        Long parsedId = Long.parseLong(id);
                        EnteralNutrition vo = baseMapper.selectById(parsedId);
                        if (vo != null) {
                            vo.setConfigStatus(ConfigStatus.ONE.getCode()); // 设置状态
                            vo.setConfigTime(new Date()); // 设置更新时间
                            vo.setConfigBy(userId); // 设置操作人（需替换成实际方法）
                            baseMapper.updateById(vo); // 执行更新
                        }
                    } catch (NumberFormatException e) {
                        log.error("Invalid ID format: {}", id, e); // 记录错误日志
                    }
                });
        }
        return R.ok();
    }

    @Override
    public R execute(String ids) {
        if (StringUtils.isNotBlank(ids)) {
            // 获取当前登录用户的ID，并填充更新人信息
            Long userId = LoginHelper.getUserId();
            Optional.ofNullable(ids) // 处理ids可能为null的情况
                .map(str -> Arrays.stream(str.split(","))) // 按逗号分割
                .orElseGet(Stream::empty) // 如果ids为null，返回空流
                .map(String::trim) // 去除空格
                .filter(StringUtils::isNotBlank) // 过滤空字符串
                .forEach(id -> {
                    try {
                        Long parsedId = Long.parseLong(id);
                        EnteralNutrition vo = baseMapper.selectById(parsedId);
                        if (vo != null) {
                            vo.setExecuteStatus(ExecuteStatus.ONE.getCode()); // 设置状态
                            vo.setExecuteDate(LocalDate.now()); // 更新执行时间
                            vo.setExecuteTime(LocalTime.now());
                            vo.setExecuteBy(userId); // 设置操作人（需替换成实际方法）
                            baseMapper.updateById(vo); // 执行更新
                        }
                    } catch (NumberFormatException e) {
                        log.error("Invalid ID format: {}", id, e); // 记录错误日志
                    }
                });
        }
        return R.ok();
    }

    @Override
    public R tagPrint(String ids) {
        if (StringUtils.isNotBlank(ids)) {
            System.err.println("当前打印 ids : " + ids);
            // 获取当前登录用户的ID，并填充更新人信息
            Long userId = LoginHelper.getUserId();
            Optional.ofNullable(ids) // 处理ids可能为null的情况
                .map(str -> Arrays.stream(str.split(","))) // 按逗号分割
                .orElseGet(Stream::empty) // 如果ids为null，返回空流
                .map(String::trim) // 去除空格
                .filter(StringUtils::isNotBlank) // 过滤空字符串
                .forEach(id -> {
                    System.err.println("当前打印:"+id);
                    try {
                        Long parsedId = Long.parseLong(id);
                        EnteralNutrition vo = baseMapper.selectById(parsedId);
                        if (vo != null) {
                            vo.setTagPrintNum(vo.getTagPrintNum() + 1);
                            baseMapper.updateById(vo); // 执行更新
                        }
                    } catch (NumberFormatException e) {
                        log.error("Invalid ID format: {}", id, e); // 记录错误日志
                    }
                });
        }
        return R.ok();
    }

    @Override
    public R<EnteralNutritionQueryVo> detail(Long id) {
        if (ObjUtil.isNull(id)) {
            throw new ServiceException("id不能为空！");
        }

        List<EnteralNutrition> nutritionList = baseMapper.selectList(Wrappers.lambdaQuery(EnteralNutrition.class).eq(EnteralNutrition::getSettlementId, id));
        List<EnteralNutritionConsumable> consumableList = consumableMapper.selectList(Wrappers.lambdaQuery(EnteralNutritionConsumable.class).eq(EnteralNutritionConsumable::getSettlementId, id));

        EnteralNutritionQueryVo queryVo = new EnteralNutritionQueryVo();
        queryVo.setNutritionList(MapstructUtils.convert(nutritionList, EnteralNutritionVo.class));
        queryVo.setConsumableList(MapstructUtils.convert(consumableList, EnteralNutritionConsumableVo.class));

        if (CollUtil.isNotEmpty(nutritionList)) {
            queryVo.setProductNutritionMap(productNutritionMapper.selectByIds(nutritionList.stream().map(EnteralNutrition::getNutritionProductId).collect(Collectors.toSet())).stream().map(v -> MapstructUtils.convert(v, ProductNutritionVo.class)).collect(Collectors.toMap(k1 -> k1.getId(), k2 -> k2, (k1, k12) -> k1)));

            queryVo.getNutritionList().forEach(nutrition -> {
                nutrition.setMealTime(Arrays.stream(nutrition.getMealTime().split(",")).filter(StrUtil::isNotBlank).collect(Collectors.joining(",")));
            });
        }

        return R.ok(queryVo);
    }

    @Override
    public TableDataInfo<EnteralNutritionQueryVo> listHistory(SettlementBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Settlement> lqw = Wrappers.lambdaQuery();
        lqw.eq(Settlement::getPatientId, bo.getPatientId());
        List<Settlement> settlementList = settlementMapper.selectList(lqw);

        Map<String, List<SysDictDataVo>> dictMap = dataService.selectGroupByType(List.of(BizConst.PAYMENT_STATUS, BizConst.FEE_TYPE)).getData();
        Map<String, String> feeTypeMap = dictMap.get(BizConst.FEE_TYPE).stream().collect(Collectors.toMap(k1 -> k1.getDictValue(), k2 -> k2.getDictLabel(), (k1, k2) -> k1));
        List<EnteralNutritionQueryVo> nutritionQueryVoList = new ArrayList<>(settlementList.size());
        String today = DateUtil.today();
        settlementList.forEach(settlement -> {
            EnteralNutritionQueryVo queryVo = new EnteralNutritionQueryVo();

            queryVo.setPaymentStatus(settlement.getPaymentStatus());
            queryVo.setChargeType(settlement.getChargeType());
            queryVo.setChargeTypeMame(feeTypeMap.get(settlement.getChargeType()));
            queryVo.setOrderTime(settlement.getOrderTime());
            queryVo.setSettlementId(settlement.getId());
            String stopDate = DateUtil.formatDate(settlement.getStopDate());
            queryVo.setStopFlag(stopDate.compareTo(today) < 0);
            queryVo.setDelFlag(DelFlag.YES.getCode().equals(settlement.getDelFlag()));

            nutritionQueryVoList.add(queryVo);
        });

        return TableDataInfo.build(nutritionQueryVoList);
    }

    /**
     * 分页查询肠内营养列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 肠内营养分页列表
     */
    @Override
    public TableDataInfo<EnteralNutritionQueryVo> queryPageList(SettlementBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Settlement> lqw = Wrappers.lambdaQuery();
        lqw.eq(Settlement::getPatientId, bo.getPatientId());

        String today = DateUtil.today();
        String beginTime = today + " 00:00:00";
        String endTime = today + " 23:59:59";

        lqw.and(lqw2 -> {
            lqw2.eq(Settlement::getStatus, "2");
            lqw2.or();
            lqw2.between(Settlement::getCreateTime, beginTime, endTime);
        });
        List<Settlement> settlementList = settlementMapper.selectList(lqw);
        Map<Long, Settlement> settlementMap = MapUtil.newHashMap();
        Set<Long> userList = CollUtil.newHashSet();
        settlementList.forEach(sm -> {
            settlementMap.put(sm.getId(), sm);
            userList.add(sm.getCreateBy());
        });

        Set<Long> settlementIdList = settlementMap.keySet();
        Map<Long, List<EnteralNutrition>> nutritionGroupMap = baseMapper.selectList(Wrappers.lambdaQuery(EnteralNutrition.class).in(EnteralNutrition::getSettlementId, settlementIdList)).stream().collect(Collectors.groupingBy(EnteralNutrition::getSettlementId));

        Map<Long, List<EnteralNutritionConsumable>> consumableGroupMap = consumableMapper.selectList(Wrappers.lambdaQuery(EnteralNutritionConsumable.class).in(EnteralNutritionConsumable::getSettlementId, settlementIdList)).stream().collect(Collectors.groupingBy(EnteralNutritionConsumable::getSettlementId));

        Map<Long, String> userMap = userMapper.selectList(Wrappers.lambdaQuery(SysUser.class).select(SysUser::getUserId, SysUser::getNickName).in(SysUser::getUserId, userList)).stream().collect(Collectors.toMap(k1 -> k1.getUserId(), k2 -> k2.getNickName(), (k1, k2) -> k1));

        Map<String, List<SysDictDataVo>> dictMap = dataService.selectGroupByType(List.of(BizConst.PAYMENT_STATUS, BizConst.FEE_TYPE)).getData();
        Map<String, String> paymentMap = dictMap.get(BizConst.PAYMENT_STATUS).stream().collect(Collectors.toMap(k1 -> k1.getDictValue(), k2 -> k2.getDictLabel(), (k1, k2) -> k1));
        Map<String, String> feeTypeMap = dictMap.get(BizConst.FEE_TYPE).stream().collect(Collectors.toMap(k1 -> k1.getDictValue(), k2 -> k2.getDictLabel(), (k1, k2) -> k1));

        List<EnteralNutritionQueryVo> nutritionQueryVoList = new ArrayList<>(settlementList.size());
        settlementList.forEach(settlement -> {
            EnteralNutritionQueryVo queryVo = new EnteralNutritionQueryVo();
            nutritionQueryVoList.add(queryVo);
            List<EnteralNutrition> nutritionList = nutritionGroupMap.get(settlement.getId());
            if (CollUtil.isNotEmpty(nutritionList)) {
                queryVo.setNutritionList(MapstructUtils.convert(nutritionList, EnteralNutritionVo.class));
            }

            List<EnteralNutritionConsumable> consumableList = consumableGroupMap.get(settlement.getId());
            if (CollUtil.isNotEmpty(consumableList)) {
                queryVo.setConsumableList(MapstructUtils.convert(consumableList, EnteralNutritionConsumableVo.class));
            }

            queryVo.setPaymentStatus(paymentMap.get(settlement.getPaymentStatus()));
            queryVo.setStatus(settlement.getStatus());
            queryVo.setChargeType(feeTypeMap.get(settlement.getChargeType()));
            queryVo.setOrderTime(settlement.getOrderTime());
            queryVo.setSettlementId(settlement.getId());
            queryVo.setCreateByName(userMap.get(settlement.getCreateBy()));
        });

        return TableDataInfo.build(nutritionQueryVoList);
    }

    /**
     * 查询符合条件的肠内营养列表
     *
     * @param bo 查询条件
     * @return 肠内营养列表
     */
    @Override
    public List<EnteralNutritionVo> queryList(EnteralNutritionBo bo) {
        LambdaQueryWrapper<EnteralNutrition> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }


    private LambdaQueryWrapper<EnteralNutrition> buildQueryWrapper(EnteralNutritionBo bo) {
        LambdaQueryWrapper<EnteralNutrition> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(EnteralNutrition::getId);
        lqw.eq(bo.getSettlementId() != null, EnteralNutrition::getSettlementId, bo.getSettlementId());
        return lqw;
    }

    /**
     * 新增肠内营养
     *
     * @param bo 肠内营养
     * @return 是否新增成功
     */
    @Override
    @Transactional
    public Boolean insertByBo(EnteralNutritionSaveBo bo) {
        if (CollUtil.isEmpty(bo.getNutritionList())) {
            throw new ServiceException("请至少选择一个营养产品");
        }

        TreatmentUser treatmentUser = treatmentUserMapper.selectById(bo.getPatientId());
        Settlement settlement = new Settlement();
        settlement.setOrderTime(new Date());
        settlement.setPatientId(bo.getPatientId());
        settlement.setVisitType(bo.getVisitType());
        settlement.setChargeType(bo.getChargeType());
        settlement.setPatientNo(bo.getPatientNo());
        settlement.setPatientName(treatmentUser.getTreatName());
        settlement.setDoorId(treatmentUser.getDoorId());
        settlement.setPhone(treatmentUser.getPhoneNum());
        settlement.setIdCard(treatmentUser.getIdCard());
        settlement.setBedNo(treatmentUser.getBedNo());
        settlement.setWardId(treatmentUser.getWardId());
        settlement.setWardName(treatmentUser.getWardName());
        settlement.setPaymentStatus(PaymentStatus.UNPAID.getCode());
        settlement.setStatus(bo.getStatus());
        settlement.setTreatNum(treatmentUser.getTreatNum());

        saveOrUpdateData(bo, settlement);
        return Boolean.TRUE;
    }

    private void saveOrUpdateData(EnteralNutritionSaveBo bo, Settlement settlement) {
        Map<String, List<SysDictDataVo>> dictMap = dataService.selectGroupByType(List.of(BizConst.PRODUCT_SPEC_UNIT, BizConst.PRODUCT_PACKAGE_UNIT)).getData();
        Map<String, String> specUnitMap = dictMap.get(BizConst.PRODUCT_SPEC_UNIT).stream().collect(Collectors.toMap(k1 -> k1.getDictValue(), k2 -> k2.getDictLabel(), (k1, k2) -> k1));
        Map<String, String> packageUnitMap = dictMap.get(BizConst.PRODUCT_PACKAGE_UNIT).stream().collect(Collectors.toMap(k1 -> k1.getDictValue(), k2 -> k2.getDictLabel(), (k1, k2) -> k1));

        Set<Long> idList = CollUtil.newHashSet();
        bo.getNutritionList().forEach(nutritionBo -> {
            if (FeeType.PRE_PACKAGED_PRESCRIPTION.getCode().equalsIgnoreCase(bo.getChargeType())) {
                idList.add(nutritionBo.getNutritionProductId());
            } else {
                if (CollUtil.isEmpty(nutritionBo.getProducts())) {
                    throw new ServiceException("营养产品不能为空");
                }
                nutritionBo.getProducts().forEach(nutritionProductBo -> {
                    idList.add(nutritionProductBo.getNutritionProductId());
                });
            }
        });

        Map<Long, ProductNutrition> nutritionMap = productNutritionMapper.selectByIds(idList).stream().collect(Collectors.toMap(k1 -> k1.getId(), k2 -> k2, (k1, k2) -> k1));
        BigDecimal total = BigDecimal.ZERO;
        Map<String, EnteralNutritionBo> groupNoMap = MapUtil.newHashMap(bo.getNutritionList().size());
        for (EnteralNutritionBo nutritionBo : bo.getNutritionList()) {
            if (ObjUtil.isNull(nutritionBo.getPrescriptionDate())) {
                throw new ServiceException("开方日期不能为空");
            }
            if (StrUtil.isBlank(nutritionBo.getPrescriptionType())) {
                throw new ServiceException("处方类型不能为空");
            }
            if (StrUtil.isBlank(nutritionBo.getMealTime())) {
                throw new ServiceException("餐次时间不能为空");
            }

            Set<String> mealTimeSet = Arrays.stream(nutritionBo.getMealTime().split(",")).map(String::trim).filter(StrUtil::isNotBlank).collect(Collectors.toSet());
            nutritionBo.setFrequency(Long.valueOf(mealTimeSet.size()));

            if (FeeType.PRE_PACKAGED_PRESCRIPTION.getCode().equalsIgnoreCase(bo.getChargeType())) {
                nutritionBo.setPrescriptionType(bo.getChargeType());

                ProductNutrition nutrition = nutritionMap.get(nutritionBo.getNutritionProductId());
                nutrition.setCalorie(ObjUtil.isNull(nutrition.getCalorie()) ? 0L : nutrition.getCalorie());
                if (ObjUtil.isNull(nutrition.getPackagePrice())) {
                    throw new ServiceException("预包装销售价不能为空");
                }
                if (StrUtil.isBlank(nutrition.getProductSpec())) {
                    throw new ServiceException("商品规格不能为空");
                }
                if (ObjUtil.isNull(nutritionBo.getQuantity())) {
                    throw new ServiceException("数量不能为空");
                }

                nutritionBo.setAmount(nutrition.getPackagePrice().multiply(new BigDecimal(nutritionBo.getQuantity())).multiply(new BigDecimal(nutrition.getProductSpec())).multiply(nutritionBo.getDosePerTime()));

                nutritionBo.setDailyCalories(BigDecimal.valueOf(nutrition.getCalorie() * nutritionBo.getFrequency() / 100.0).multiply(nutritionBo.getDosePerTime()));

                settlement.setStopDate(DateUtil.offsetDay(nutritionBo.getPrescriptionDate(), nutritionBo.getUsageDays().intValue() - 1));
                nutritionBo.setStopDate(settlement.getStopDate());
                continue;
            }


            for (EnteralNutritionBo product : nutritionBo.getProducts()) {
                if (ObjUtil.isNull(product.getDosePerTime())) {
                    throw new ServiceException("用量/次不能为空");
                }
                if (StrUtil.isBlank(product.getGroupNo())) {
                    throw new ServiceException("组号不能为空");
                }
                groupNoMap.put(product.getGroupNo(), nutritionBo);

                ProductNutrition nutrition = nutritionMap.get(product.getNutritionProductId());
                nutrition.setCalorie(ObjUtil.isNull(nutrition.getCalorie()) ? 0L : nutrition.getCalorie());
                product.setNutritionProduct(nutrition.getProductName());
                if (ObjUtil.isNull(nutrition)) {
                    continue;
                }

                product.setFrequency(nutritionBo.getFrequency());
                product.setUsageDays(nutritionBo.getUsageDays());
                product.setFirstDay(nutritionBo.getFirstDay());
                product.setPrescriptionDate(nutritionBo.getPrescriptionDate());
                product.setPrescriptionType(bo.getChargeType());
                product.setMealTime(nutritionBo.getMealTime());
                product.setStopDate(nutritionBo.getStopDate());

                if (FeeType.CONFIGURE_PRESCRIPTION.getCode().equalsIgnoreCase(bo.getChargeType())) {
                    if (ObjUtil.isNull(nutrition.getConfigSalePrice())) {
                        throw new ServiceException("配置销售价格不能为空");
                    }
                    if (ObjUtil.isNull(nutritionBo.getUsageDays())) {
                        throw new ServiceException("使用天数不能为空");
                    }
                    if (ObjUtil.isNull(nutritionBo.getFirstDay())) {
                        throw new ServiceException("首日不能为空");
                    }

                    product.setAmount(nutrition.getConfigSalePrice().multiply(new BigDecimal(nutritionBo.getFrequency() * (nutritionBo.getUsageDays() - 1) + nutritionBo.getFirstDay())).multiply(product.getDosePerTime()));
                    product.setAmount(BigDecimal.ZERO.compareTo(product.getAmount()) > 0 ? BigDecimal.ZERO : product.getAmount());

                    product.setDailyCalories(BigDecimal.valueOf(nutrition.getCalorie() * nutritionBo.getFrequency() / 100.0).multiply(product.getDosePerTime()));

                    product.setTotalDose(BigDecimal.valueOf((nutritionBo.getFrequency() * (nutritionBo.getUsageDays() - 1) + nutritionBo.getFirstDay())).multiply(product.getDosePerTime()));

                    settlement.setStopDate(DateUtil.offsetDay(nutritionBo.getPrescriptionDate(), product.getUsageDays().intValue() - 1));
                    product.setStopDate(settlement.getStopDate());
                } else if (FeeType.LONG_TERM_PRESCRIPTION.getCode().equalsIgnoreCase(bo.getChargeType())) {
                    if (ObjUtil.isNull(product.getStopDate())) {
                        throw new ServiceException("停嘱日期不能为空");
                    }
                    if (ObjUtil.isNull(product.getStopDate())) {
                        throw new ServiceException("停嘱日期不能为空");
                    }
                    if (ObjUtil.isNull(product.getFirstDay())) {
                        throw new ServiceException("首日不能为空");
                    }
                    if (ObjUtil.isNull(nutrition.getConfigSalePrice())) {
                        throw new ServiceException("配置销售价格不能为空");
                    }
                    long days = DateUtil.between(nutritionBo.getPrescriptionDate(), product.getStopDate(), DateUnit.DAY) + 1;
                    product.setUsageDays(days);

                    product.setAmount(nutrition.getConfigSalePrice().multiply(new BigDecimal((days - 1) * nutritionBo.getFrequency() + nutritionBo.getFirstDay())).multiply(product.getDosePerTime()));
                    product.setAmount(BigDecimal.ZERO.compareTo(product.getAmount()) > 0 ? BigDecimal.ZERO : product.getAmount());

                    product.setDailyCalories(BigDecimal.valueOf(nutrition.getCalorie() * nutritionBo.getFrequency() / 100.0).multiply(product.getDosePerTime()));

                    settlement.setStopDate(product.getStopDate());
                }
                product.setDosePerDay(BigDecimal.valueOf(nutritionBo.getFrequency()).multiply(product.getDosePerTime()));

                String packageUnit = StrUtil.emptyToDefault(packageUnitMap.get(nutrition.getPackageUnit()), StrUtil.EMPTY);
                String productSpecUnit = StrUtil.emptyToDefault(specUnitMap.get(nutrition.getProductSpecUnit()), StrUtil.EMPTY);
                product.setSpecification(nutrition.getProductSpec() + productSpecUnit + "/" + packageUnit);
                total = total.add(product.getAmount());
            }
        }

        if (CollUtil.isNotEmpty(bo.getConsumableList())) {
            Set<Long> consumableIds = CollUtil.newHashSet();
            bo.getConsumableList().forEach(v -> {
                if (ObjUtil.isNull(v.getDosePerTime())) {
                    throw new ServiceException("耗材[用量/次]不能为空");
                }
                if (ObjUtil.isNull(v.getQuantity())) {
                    throw new ServiceException("耗材[数量]不能为空");
                }
                consumableIds.add(v.getConsumableId());
            });

            Map<Long, SuppliesManage> suppliesManageMap = suppliesManageMapper.selectByIds(consumableIds).stream().collect(Collectors.toMap(k1 -> k1.getId(), k2 -> k2, (k1, k2) -> k1));

            bo.getConsumableList().forEach(v -> {
                SuppliesManage suppliesManage = suppliesManageMap.get(v.getConsumableId());
                EnteralNutritionBo nutritionBo = groupNoMap.get(v.getGroupNo());
                if (ObjUtil.isNotNull(nutritionBo)) {
                    v.setFrequency(nutritionBo.getFrequency());
                    v.setDosePerDay(v.getDosePerTime().multiply(BigDecimal.valueOf(v.getFrequency())));
                    v.setFirstDay(nutritionBo.getFirstDay());

                    long days = 0L;

                    if (FeeType.LONG_TERM_PRESCRIPTION.getCode().equalsIgnoreCase(nutritionBo.getPrescriptionType())) {
                        days = DateUtil.between(nutritionBo.getPrescriptionDate(), nutritionBo.getStopDate(), DateUnit.DAY) + 1;
                    } else {
                        days = nutritionBo.getUsageDays();
                    }

                    v.setQuantity(BigDecimal.valueOf(days - 1).multiply(BigDecimal.valueOf(v.getFrequency())).add(BigDecimal.valueOf(v.getFirstDay())).multiply(v.getDosePerTime()).longValue());
                    v.setQuantity(Math.max(v.getQuantity(), 0L));
                }

                if (ObjUtil.isNotNull(suppliesManage)) {
                    v.setConsumable(suppliesManage.getSuppliesName());
                    String packageUnit = StrUtil.emptyToDefault(packageUnitMap.get(suppliesManage.getSuppliesUnit()), StrUtil.EMPTY);
                    String productSpecUnit = StrUtil.emptyToDefault(specUnitMap.get(suppliesManage.getSuppliesSpecUnit()), StrUtil.EMPTY);
                    v.setSpecification(suppliesManage.getSuppliesSpec() + productSpecUnit + "/" + packageUnit);

                    Optional<Long> quantity = Optional.ofNullable(v.getQuantity());
                    v.setAmount(BigDecimal.valueOf(quantity.orElse(0L)).multiply(suppliesManage.getSellPrice()));
                }

                if (ObjUtil.isNotNull(suppliesManage) && ObjUtil.isNotNull(nutritionBo)) {
                    nutritionBo.setNutritionProduct(nutritionBo.getNutritionProduct() + "," + suppliesManage.getSuppliesName());
                }

            });
        }


        if (CollUtil.isNotEmpty(bo.getConsumableList())) {
            total = total.add(BigDecimal.valueOf(bo.getConsumableList().size()));
            for (EnteralNutritionConsumableBo enteralNutritionConsumableBo : bo.getConsumableList()) {
                total = total.add(enteralNutritionConsumableBo.getAmount());
            }
        }
        settlement.setReceivableAmount(total);
        if (ObjUtil.isNull(settlement.getId())) {
            settlementMapper.insert(settlement);
        } else {
            settlementMapper.updateById(settlement);
        }

        if (CollUtil.isNotEmpty(bo.getConsumableList())) {
            bo.getConsumableList().forEach(v -> {
                v.setSettlementId(settlement.getId());
            });
            consumableMapper.insertBatch(MapstructUtils.convert(bo.getConsumableList(), EnteralNutritionConsumable.class));
        }

        bo.setSettlementId(settlement.getId());

        if (FeeType.PRE_PACKAGED_PRESCRIPTION.getCode().equalsIgnoreCase(bo.getChargeType())) {
            bo.getNutritionList().forEach(v -> {
                v.setSettlementId(settlement.getId());
            });
            baseMapper.insertBatch(MapstructUtils.convert(bo.getNutritionList(), EnteralNutrition.class));
        } else {
            List<EnteralNutritionBo> productList = CollUtil.newArrayList();
            bo.getNutritionList().forEach(v -> {
                v.getProducts().forEach(p -> {
                    productList.add(p);
                    p.setSettlementId(settlement.getId());
                });
            });

            baseMapper.insertBatch(MapstructUtils.convert(productList, EnteralNutrition.class));
        }
    }


    /**
     * 修改肠内营养
     *
     * @param bo 肠内营养
     * @return 是否修改成功
     */
    @Override
    @Transactional
    public Boolean updateByBo(EnteralNutritionSaveBo bo) {
        baseMapper.delete(Wrappers.lambdaQuery(EnteralNutrition.class).eq(EnteralNutrition::getSettlementId, bo.getSettlementId()));
        consumableMapper.delete(Wrappers.lambdaQuery(EnteralNutritionConsumable.class).eq(EnteralNutritionConsumable::getSettlementId, bo.getSettlementId()));

        Settlement settlement = new Settlement();
        settlement.setId(bo.getSettlementId());
        saveOrUpdateData(bo, settlement);

        return Boolean.TRUE;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(EnteralNutrition entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除肠内营养信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        int cnt = settlementMapper.update(Wrappers.lambdaUpdate(Settlement.class).set(Settlement::getDelFlag, DelFlag.YES.getCode()).in(Settlement::getId, ids));
        return cnt > 0;
    }

    @Override
    public TableDataInfo<EnteralNutritionQueryOneVo> queryEnteralNutritionPageList(EnteralNutritionBo bo, PageQuery pageQuery) {
        Map<String, Object> params = bo.getParams();
        List<Date> executeDateRange = bo.getExecuteDateRange();
        List<Date> prescriptionDateRange = bo.getPrescriptionDateRange();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startExecuteDate = null;
        String endExecuteDate = null;
        String startTime = null;
        String endTime = null;
        if (executeDateRange != null && executeDateRange.size() == 2) {
            startExecuteDate = sdf.format(executeDateRange.get(0)) + " 00:00:00";  // 开始时间
            endExecuteDate = sdf.format(executeDateRange.get(1)) + " 23:59:59";    // 结束时间
        }
        if (prescriptionDateRange != null && prescriptionDateRange.size() == 2) {
            startTime = sdf.format(prescriptionDateRange.get(0)) + " 00:00:00";  // 开始时间
            endTime = sdf.format(prescriptionDateRange.get(1)) + " 23:59:59";    // 结束时间
        }
        // 计算正确的offset
        int offset = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        Integer total = baseMapper.queryPageVoCount(bo.getPrescriptionType(), bo.getVisitType(), bo.getConfigStatus(), bo.getPaymentStatus(), bo.getExecuteStatus(), bo.getDoorId(), bo.getWardId(), bo.getSearchValue(), startExecuteDate, endExecuteDate, startTime, endTime);

        List<EnteralNutritionQueryOneVo> enteralNutritionVoList = baseMapper.queryPageVoList(bo.getPrescriptionType(), bo.getVisitType(), bo.getConfigStatus(), bo.getPaymentStatus(), bo.getExecuteStatus(), bo.getDoorId(), bo.getWardId(), bo.getSearchValue(), startExecuteDate, endExecuteDate, startTime, endTime, offset, pageQuery.getPageSize());

        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(enteralNutritionVoList);
        tableDataInfo.setTotal(total);
        return tableDataInfo;

    }

}
