package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.dromara.common.core.constant.BizConst;
import org.dromara.common.core.enums.biz.PaymentStatus;
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.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.system.domain.SysScreeningAssessmentConfig;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.SysScreeningAssessmentConfigBo;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.mapper.SysScreeningAssessmentConfigMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysDictDataService;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.NutritionEvaluationBo;
import org.dromara.system.domain.vo.NutritionEvaluationVo;
import org.dromara.system.domain.NutritionEvaluation;
import org.dromara.system.mapper.NutritionEvaluationMapper;
import org.dromara.system.service.INutritionEvaluationService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 营养评估Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-17
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class NutritionEvaluationServiceImpl implements INutritionEvaluationService {

    private final NutritionEvaluationMapper baseMapper;
    private final SysScreeningAssessmentConfigMapper configMapper;
    private final ISysDictDataService dataService;
    private final SysUserMapper userMapper;

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

    /**
     * 分页查询营养评估列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 营养评估分页列表
     */
    @Override
    public TableDataInfo<NutritionEvaluationVo> queryPageList(NutritionEvaluationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<NutritionEvaluation> lqw = buildQueryWrapper(bo);
        Page<NutritionEvaluationVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        if (CollUtil.isNotEmpty(result.getRecords())) {
            Set<Long> userList = CollUtil.newHashSet();
            Set<Long> configList = CollUtil.newHashSet();
            result.getRecords().forEach(v -> {
                userList.add(v.getCreateBy());
                configList.add(v.getConfigId());
            });

            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<Long, String> configMap = configMapper.selectList(Wrappers.lambdaQuery(SysScreeningAssessmentConfig.class)
                    .select(SysScreeningAssessmentConfig::getConfigId, SysScreeningAssessmentConfig::getName)
                    .in(SysScreeningAssessmentConfig::getConfigId, configList))
                .stream().collect(Collectors.toMap(k1 -> k1.getConfigId(), k2 -> k2.getName(), (k1, k2) -> k1));
            Map<String, List<SysDictDataVo>> dictMap = dataService.selectGroupByType(List.of(BizConst.PAYMENT_STATUS, BizConst.TREATMENT_USER_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> checkMap = dictMap.get(BizConst.TREATMENT_USER_TYPE).stream().collect(Collectors.toMap(k1 -> k1.getDictValue(), k2 -> k2.getDictLabel(), (k1, k2) -> k1));
            result.getRecords().forEach(v -> {
                v.setVisitType(checkMap.get(v.getVisitType()));
                v.setPaymentStatus(paymentMap.get(v.getPaymentStatus()));
                v.setConfigName(configMap.get(v.getConfigId()));
                v.setCreateByName(userMap.get(v.getCreateBy()));
            });
        }

        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的营养评估列表
     *
     * @param bo 查询条件
     * @return 营养评估列表
     */
    @Override
    public List<NutritionEvaluationVo> queryList(NutritionEvaluationBo bo) {
        LambdaQueryWrapper<NutritionEvaluation> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NutritionEvaluation> buildQueryWrapper(NutritionEvaluationBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<NutritionEvaluation> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(NutritionEvaluation::getId);
        lqw.eq(bo.getPatientId() != null, NutritionEvaluation::getPatientId, bo.getPatientId());
        lqw.eq(bo.getConfigId() != null, NutritionEvaluation::getConfigId, bo.getConfigId());
        lqw.eq(bo.getScreeningTime() != null, NutritionEvaluation::getScreeningTime, bo.getScreeningTime());
        lqw.eq(StringUtils.isNotBlank(bo.getVisitType()), NutritionEvaluation::getVisitType, bo.getVisitType());
        lqw.eq(StringUtils.isNotBlank(bo.getPatientNo()), NutritionEvaluation::getPatientNo, bo.getPatientNo());
        lqw.eq(StringUtils.isNotBlank(bo.getPaymentStatus()), NutritionEvaluation::getPaymentStatus, bo.getPaymentStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), NutritionEvaluation::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), NutritionEvaluation::getStatus, bo.getStatus());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
            NutritionEvaluation::getScreeningTime, params.get("beginTime"), params.get("endTime"));
        return lqw;
    }

    /**
     * 新增营养评估
     *
     * @param bo 营养评估
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(NutritionEvaluationBo bo) {
        if (StrUtil.isBlank(bo.getContent())) {
            throw new ServiceException("提交的“营养评估”不能为空！");
        }
        SysScreeningAssessmentConfigBo configBo = JSON.parseObject(bo.getContent(), new TypeReference<SysScreeningAssessmentConfigBo>() {
        });
        if (CollUtil.isEmpty(configBo.getOtherInfo()) && ObjUtil.isEmpty(configBo.getBaseInfo())) {
            throw new ServiceException("没有任何“营养评估”！");
        }

        NutritionEvaluation add = MapstructUtils.convert(bo, NutritionEvaluation.class);
        add.setScreeningTime(new Date());
        add.setPaymentStatus(PaymentStatus.PAID.getCode());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改营养评估
     *
     * @param bo 营养评估
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(NutritionEvaluationBo bo) {
        NutritionEvaluation update = MapstructUtils.convert(bo, NutritionEvaluation.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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