package org.dromara.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.core.enums.biz.*;
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.mapper.SysUserMapper;
import org.dromara.web.domain.*;
import org.dromara.web.domain.bo.EnteralNutritionBo;
import org.dromara.web.domain.bo.HospitalMealPlanBo;
import org.dromara.web.domain.vo.*;
import org.dromara.web.mapper.HospitalMealPlanMapper;
import org.dromara.web.mapper.HospitalMealRecipeMapper;
import org.dromara.web.mapper.SettlementMapper;
import org.dromara.web.mapper.TreatmentUserMapper;
import org.dromara.web.service.IHospitalMealPlanService;
import org.springframework.stereotype.Service;

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-23
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HospitalMealPlanServiceImpl implements IHospitalMealPlanService {

    private final HospitalMealPlanMapper baseMapper;

    private final SysUserMapper userMapper;

    private final SettlementMapper settlementMapper;

    private final TreatmentUserMapper treatmentUserMapper;

    private final HospitalMealRecipeMapper mealRecipeMapper;

    /**
     * 查询院内膳食主
     *
     * @param id 主键
     * @return 院内膳食主
     */
    @Override
    public HospitalMealPlanVo queryById(Long id) {
        HospitalMealPlanVo hospitalMealPlanVo = baseMapper.selectVoById(id);
        if (ObjUtil.isNotNull(hospitalMealPlanVo)) {
            List<HospitalMealRecipeVo> voList = mealRecipeMapper.selectVoList(Wrappers.lambdaQuery(HospitalMealRecipe.class).eq(HospitalMealRecipe::getPlanId, hospitalMealPlanVo.getId()));
            hospitalMealPlanVo.setMealRecipeList(voList);
        }
        return hospitalMealPlanVo;
    }

    /**
     * 分页查询院内膳食主列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 院内膳食主分页列表
     */
    @Override
    public TableDataInfo<HospitalMealPlanVo> queryPageList(HospitalMealPlanBo bo, PageQuery pageQuery) {

        LambdaQueryWrapper<HospitalMealPlan> lqw = buildQueryWrapper(bo);
        Page<HospitalMealPlanVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<HospitalMealPlanVo> records = result.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            Set<Long> userList = CollUtil.newHashSet();
            records.forEach(v -> {
                userList.add(v.getCreateBy());
            });
            Map<Long, String> userMap = userMapper.selectList(Wrappers.lambdaQuery(SysUser.class).select(SysUser::getUserId, SysUser::getUserName).in(SysUser::getUserId, userList)).stream().collect(Collectors.toMap(k1 -> k1.getUserId(), k2 -> k2.getUserName(), (k1, k2) -> k1));
            records.forEach(v -> {
                v.setCreateByUser(userMap.get(v.getCreateBy()));
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的院内膳食主列表
     *
     * @param bo 查询条件
     * @return 院内膳食主列表
     */
    @Override
    public List<HospitalMealPlanVo> queryList(HospitalMealPlanBo bo) {
        LambdaQueryWrapper<HospitalMealPlan> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HospitalMealPlan> buildQueryWrapper(HospitalMealPlanBo bo) {
        List<Date> dateRange = bo.getDateRange();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        List<SysUser> userList = userMapper.selectList(Wrappers.lambdaQuery(SysUser.class).select(SysUser::getUserId, SysUser::getUserName));
        Map<String, Long> userMap = userList.stream().collect(Collectors.toMap(k1 -> String.valueOf(k1.getUserName()), k2 -> k2.getUserId(), (k1, k2) -> k1));
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HospitalMealPlan> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HospitalMealPlan::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getType()), HospitalMealPlan::getType, bo.getType());
        lqw.eq(bo.getPatientId() != null, HospitalMealPlan::getPatientId, bo.getPatientId());
        if (StringUtils.isNotBlank(bo.getSearchValue())) {
            lqw.and(wrapper -> wrapper.like(HospitalMealPlan::getCreateBy, userMap.get(bo.getSearchValue())).or().like(HospitalMealPlan::getOutpatientNo, bo.getSearchValue()));
        }
        if (dateRange != null && dateRange.size() == 2) {
            String startTime = sdf.format(dateRange.get(0)) + " 00:00:00";  // 开始时间
            String endTime = sdf.format(dateRange.get(1)) + " 23:59:59";    // 结束时间
            if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
                lqw.between(HospitalMealPlan::getCreateTime, startTime, endTime);

            }
        }
        return lqw;
    }

    /**
     * 新增院内膳食主
     *
     * @param bo 院内膳食主
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HospitalMealPlanBo bo) {
        log.info(bo.toString());
        /*新增院内膳食时新增一条结算管理的待收费订单*/
        TreatmentUser treatmentUser = treatmentUserMapper.selectById(bo.getPatientId());
        Settlement settlement = new Settlement();
        settlement.setOrderTime(new Date());
        settlement.setPatientId(bo.getPatientId());
        settlement.setVisitType(bo.getType());
        settlement.setChargeType(FeeType.IN_HOSPITAL_MEALS.getCode());
        settlement.setPatientNo(bo.getOutpatientNo());
        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.setReceivableAmount(bo.getTotalPrice());
        settlement.setPaymentStatus(PaymentStatus.UNPAID.getCode());
        settlement.setCheckStatus(CheckStatus.STATUS_TWO.getCode());
        settlement.setStatus(bo.getStatus());
        settlement.setTreatNum(treatmentUser.getTreatNum());
        boolean flag = settlementMapper.insert(settlement) > 0;
        if (flag) {
            bo.setSettlementId(settlement.getId());
            HospitalMealPlan add = MapstructUtils.convert(bo, HospitalMealPlan.class);
            validEntityBeforeSave(add);
            flag = baseMapper.insert(add) > 0;
            if (flag) {
                List<HospitalMealRecipe> hList = bo.getMealRecipeList().stream().map(mealRecipe -> {
                    HospitalMealRecipe hospitalMealRecipe = MapstructUtils.convert(mealRecipe, HospitalMealRecipe.class);
                    hospitalMealRecipe.setPlanId(add.getId());
                    return hospitalMealRecipe;
                }).collect(Collectors.toList());
                mealRecipeMapper.insertBatch(hList);
                bo.setId(add.getId());
            }
        }
        log.info("{}", flag);
        return flag;
    }

    /**
     * 修改院内膳食主
     *
     * @param bo 院内膳食主
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HospitalMealPlanBo bo) {
        HospitalMealPlan update = MapstructUtils.convert(bo, HospitalMealPlan.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

    /**
     * 校验并批量删除院内膳食主信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public TableDataInfo<HospitalMealPlanQueryVo> queryHospitalMealPlanList(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.getMakeStatus(), bo.getPaymentStatus(), bo.getExecuteStatus(), bo.getDoorId(), bo.getWardId(), bo.getSearchValue(), startExecuteDate, endExecuteDate, startTime, endTime);

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

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

    }

    @Override
    public List<HospitalMealRecipeVo> queryBySettlementId(Long id) {
        List<HospitalMealRecipeVo> hospitalMealRecipes =null;
        SettlementVo selectVoById = settlementMapper.selectVoById(id);

        List<HospitalMealPlan> mealPlanList = baseMapper.selectList(new LambdaQueryWrapper<HospitalMealPlan>().eq(HospitalMealPlan::getSettlementId, selectVoById.getId()));
        if (CollUtil.isNotEmpty(mealPlanList)) {

             hospitalMealRecipes = mealRecipeMapper.selectVoList(new LambdaQueryWrapper<HospitalMealRecipe>().eq(HospitalMealRecipe::getPlanId, mealPlanList.get(0).getId()));


        if (CollUtil.isNotEmpty(hospitalMealRecipes)) {
            Set<Long> userList = CollUtil.newHashSet();
            hospitalMealRecipes.forEach(v -> {
                userList.add(v.getMakeBy());
                userList.add(v.getExecuteBy());
            });
            // 按settlementId和groupNo分组
            Map<String, List<HospitalMealRecipeVo>> listMap = hospitalMealRecipes.stream().collect(Collectors.groupingBy(r -> r.getPlanId() + "_" + r.getRecipeNo()+"_"+r.getEatTime(), 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<HospitalMealRecipeVo> group : listMap.values()) {
                if (CollUtil.isEmpty(group)) continue;
                // 拼接id
                String ids = group.stream().map(HospitalMealRecipeVo::getId).filter(Objects::nonNull).distinct().map(String::valueOf).collect(Collectors.joining(","));
                for (HospitalMealRecipeVo record : group) {
                    // 设置用户信息
                    record.setIdStr(ids);
                    record.setCreateByName(userMap.get(record.getCreateBy()));
                    record.setMakeByName(userMap.get(record.getMakeBy()));
                    record.setExecuteByName(userMap.get(record.getExecuteBy()));
                }
            }
        }

        }
        return hospitalMealRecipes;
    }

    @Override
    public R<List<HospitalMealRecipeVo>> queryById(String ids) {
        List<HospitalMealRecipeVo> mealRecipeVoList = new ArrayList<>();
        if (StringUtils.isNotBlank(ids)) {
            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);
                        HospitalMealRecipeVo mealRecipeVo = mealRecipeMapper.selectVoById(parsedId);
                        mealRecipeVoList.add(mealRecipeVo);
                    } catch (NumberFormatException e) {
                        log.error("Invalid ID format: {}", id, e); // 记录错误日志
                    }
                });
        }
        return R.ok(mealRecipeVoList);
    }

    @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);
                        HospitalMealRecipe mealRecipe = mealRecipeMapper.selectById(parsedId);
                        if (mealRecipe != null) {
                            mealRecipe.setMakeStatus(MakeStatus.ONE.getCode()); // 设置状态
                            mealRecipe.setMakeTime(new Date()); // 设置更新时间
                            mealRecipe.setMakeBy(userId); // 设置操作人（需替换成实际方法）
                            mealRecipeMapper.updateById(mealRecipe); // 执行更新
                        }
                    } 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);
                        HospitalMealRecipe mealRecipe = mealRecipeMapper.selectById(parsedId);
                        if (mealRecipe != null) {
                            mealRecipe.setExecuteStatus(ExecuteStatus.ONE.getCode()); // 设置状态
                            mealRecipe.setExecuteDate(LocalDate.now()); // 更新执行时间
                            mealRecipe.setExecuteTime(LocalTime.now());
                            mealRecipe.setExecuteBy(userId); // 设置操作人（需替换成实际方法）
                            mealRecipeMapper.updateById(mealRecipe); // 执行更新
                        }
                    } 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);
                        HospitalMealRecipe mealRecipe = mealRecipeMapper.selectById(parsedId);
                        if (mealRecipe != null) {
                            mealRecipe.setTagPrintNum(mealRecipe.getTagPrintNum() + 1);
                            mealRecipeMapper.updateById(mealRecipe); // 执行更新
                        }
                    } catch (NumberFormatException e) {
                        log.error("Invalid ID format: {}", id, e); // 记录错误日志
                    }
                });
        }
        return R.ok();
    }


    @Override
    public List<HospitalMealRecipeVo> queryList(EnteralNutritionBo bo) {
        return null;
    }
}
