package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
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.enums.biz.QuestionsList;
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.bo.SysScreeningAssessmentQuestionBo;
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.NutritionScreeningBo;
import org.dromara.system.domain.vo.NutritionScreeningVo;
import org.dromara.system.domain.NutritionScreening;
import org.dromara.system.mapper.NutritionScreeningMapper;
import org.dromara.system.service.INutritionScreeningService;

import java.math.BigDecimal;
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-14
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class NutritionScreeningServiceImpl implements INutritionScreeningService {

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

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

    /**
     * 分页查询营养筛查列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 营养筛查分页列表
     */
    @Override
    public TableDataInfo<NutritionScreeningVo> queryPageList(NutritionScreeningBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<NutritionScreening> lqw = buildQueryWrapper(bo);
        Page<NutritionScreeningVo> 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<NutritionScreeningVo> queryList(NutritionScreeningBo bo) {
        LambdaQueryWrapper<NutritionScreening> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NutritionScreening> buildQueryWrapper(NutritionScreeningBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<NutritionScreening> lqw = Wrappers.lambdaQuery();
        lqw.select(NutritionScreening::getId, NutritionScreening::getConfigId, NutritionScreening::getScreeningTime,
            NutritionScreening::getVisitType, NutritionScreening::getPatientNo, NutritionScreening::getScreeningScore,
            NutritionScreening::getScreeningConclusion, NutritionScreening::getPaymentStatus, NutritionScreening::getCreateBy);
        lqw.orderByDesc(NutritionScreening::getId);
        lqw.eq(bo.getPatientId() != null, NutritionScreening::getPatientId, bo.getPatientId());
        lqw.eq(bo.getConfigId() != null, NutritionScreening::getConfigId, bo.getConfigId());
        lqw.eq(bo.getScreeningTime() != null, NutritionScreening::getScreeningTime, bo.getScreeningTime());
        lqw.eq(StringUtils.isNotBlank(bo.getVisitType()), NutritionScreening::getVisitType, bo.getVisitType());
        lqw.like(StringUtils.isNotBlank(bo.getPatientNo()), NutritionScreening::getPatientNo, bo.getPatientNo());
        lqw.eq(bo.getScreeningScore() != null, NutritionScreening::getScreeningScore, bo.getScreeningScore());
        lqw.eq(StringUtils.isNotBlank(bo.getScreeningConclusion()), NutritionScreening::getScreeningConclusion, bo.getScreeningConclusion());
        lqw.eq(StringUtils.isNotBlank(bo.getPaymentStatus()), NutritionScreening::getPaymentStatus, bo.getPaymentStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), NutritionScreening::getStatus, bo.getStatus());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
            NutritionScreening::getScreeningTime, params.get("beginTime"), params.get("endTime"));
        return lqw;
    }

    /**
     * 新增营养筛查
     *
     * @param bo 营养筛查
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(NutritionScreeningBo 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("没有任何“营养筛查”！");
        }

        BigDecimal total = BigDecimal.ZERO;
        if (CollUtil.isNotEmpty(configBo.getOtherInfo())) {
            for (SysScreeningAssessmentQuestionBo questionBo : configBo.getOtherInfo()) {
                if (ObjUtil.isNull(questionBo.getValue())) {
                    continue;
                }

                List<Integer> valueList = CollUtil.newArrayList();
                boolean pass = QuestionsList.QUESTION_TYPE_SELECTION.getCode().equals(questionBo.getQuestionType()) ||
                    (QuestionsList.ANTHROPOMETRY.getCode().equals(questionBo.getQuestionType()) && QuestionsList.ANTHROPOMETRY_CHILD_FOUR.getCode().equals(questionBo.getLastType())) ||
                    (QuestionsList.DIETARY_STATUS.getCode().equals(questionBo.getQuestionType()) && QuestionsList.DIETARY_STATUS_CHILD_TWO.getCode().equals(questionBo.getLastType()));
                if (!pass) {
                    continue;
                }
                String obj = String.valueOf(questionBo.getValue());
                if (NumberUtil.isNumber(obj)) {
                    valueList.add(Integer.valueOf(obj));
                } else {
                    List objList = (List) questionBo.getValue();
                    objList.forEach(v -> valueList.add(Integer.valueOf(String.valueOf(v))));
                }

                for (Integer index : valueList) {
                    SysScreeningAssessmentQuestionBo.QuestionAttrBo attrBo = questionBo.getContentList().get(index);
                    if (StrUtil.isNotBlank(attrBo.getScore()) && NumberUtil.isNumber(attrBo.getScore())) {
                        total = total.add(new BigDecimal(attrBo.getScore()));
                    }
                }
            }
        }

        NutritionScreening add = MapstructUtils.convert(bo, NutritionScreening.class);
        add.setScreeningScore(NumberUtil.round(total.toString(), 2));
        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(NutritionScreeningBo bo) {
        NutritionScreening update = MapstructUtils.convert(bo, NutritionScreening.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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