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.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.aspectj.weaver.ast.Or;
import org.dromara.common.core.constant.BizConst;
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.SysRecipe;
import org.dromara.system.domain.SysScreeningAssessmentQuestion;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.SysScreeningAssessmentQuestionBo;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.domain.vo.SysScreeningAssessmentQuestionVo;
import org.dromara.system.mapper.SysScreeningAssessmentQuestionMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysDictDataService;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.SysScreeningAssessmentConfigBo;
import org.dromara.system.domain.vo.SysScreeningAssessmentConfigVo;
import org.dromara.system.domain.SysScreeningAssessmentConfig;
import org.dromara.system.mapper.SysScreeningAssessmentConfigMapper;
import org.dromara.system.service.ISysScreeningAssessmentConfigService;
import org.springframework.transaction.annotation.Transactional;

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-08
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysScreeningAssessmentConfigServiceImpl implements ISysScreeningAssessmentConfigService {

    private final SysScreeningAssessmentConfigMapper baseMapper;
    private final SysScreeningAssessmentQuestionMapper questionMapper;
    private final ISysDictDataService dictDataService;
    private final SysUserMapper userMapper;

    @Override
    public int updateConfigStatus(List<Long> configIdIds, String status) {
        return baseMapper.update(null,
            new LambdaUpdateWrapper<SysScreeningAssessmentConfig>()
                .set(SysScreeningAssessmentConfig::getStatus, status)
                .in(SysScreeningAssessmentConfig::getConfigId, configIdIds));
    }

    /**
     * 查询筛查/评估配置
     *
     * @param configId 主键
     * @return 筛查/评估配置
     */
    @Override
    public SysScreeningAssessmentConfigVo queryById(Long configId) {
        SysScreeningAssessmentConfigVo vo = baseMapper.selectVoById(configId);
        if (ObjUtil.isNotNull(vo)) {
            List<SysScreeningAssessmentQuestionVo> voList = questionMapper.selectVoList(Wrappers.lambdaQuery(SysScreeningAssessmentQuestion.class)
                .eq(SysScreeningAssessmentQuestion::getConfigId, vo.getConfigId()));

            Map<String, List<SysScreeningAssessmentQuestionVo>> voMap = voList.stream().collect(Collectors.groupingBy(v -> {
                if (StrUtil.isNotBlank(v.getContent())) {
                    v.setContentList(JSON.parseArray(v.getContent(), SysScreeningAssessmentQuestionVo.QuestionAttrVo.class));
                }
                if (BizConst.QUESTION_BASE_INFO.equalsIgnoreCase(v.getQuestionType())) {
                    return BizConst.QUESTION_BASE_INFO;
                } else {
                    return BizConst.QUESTION_OTHER_INFO;
                }
            }));

            List<SysScreeningAssessmentQuestionVo> questionList = voMap.get(BizConst.QUESTION_BASE_INFO);
            if (CollUtil.isNotEmpty(questionList)) {
                vo.setBaseInfo(questionList.get(0));
            }

            questionList = voMap.get(BizConst.QUESTION_OTHER_INFO);
            if (CollUtil.isNotEmpty(questionList)) {
                vo.setOtherInfo(questionList);
            }
        }

        return vo;
    }

    /**
     * 分页查询筛查/评估配置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 筛查/评估配置分页列表
     */
    @Override
    public TableDataInfo<SysScreeningAssessmentConfigVo> queryPageList(SysScreeningAssessmentConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysScreeningAssessmentConfig> lqw = buildQueryWrapper(bo);
        Page<SysScreeningAssessmentConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollUtil.isNotEmpty(result.getRecords())) {
            Map<String, SysDictDataVo> dictMap = dictDataService.selectMapByType(BizConst.SCALE_TYPE).getData();
            Set<Long> userList = CollUtil.newHashSet();
            result.getRecords().forEach(v -> {
                userList.add(v.getCreateBy());
                SysDictDataVo dataVo = dictMap.get(v.getType());
                if (ObjUtil.isNotNull(dataVo)) {
                    v.setTypeName(dataVo.getDictLabel());
                }
            });

            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));

            result.getRecords().forEach(v -> {
                v.setCreateByName(userMap.get(v.getCreateBy()));
            });

        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的筛查/评估配置列表
     *
     * @param bo 查询条件
     * @return 筛查/评估配置列表
     */
    @Override
    public List<SysScreeningAssessmentConfigVo> queryList(SysScreeningAssessmentConfigBo bo) {
        LambdaQueryWrapper<SysScreeningAssessmentConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysScreeningAssessmentConfig> buildQueryWrapper(SysScreeningAssessmentConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysScreeningAssessmentConfig> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysScreeningAssessmentConfig::getConfigId);
        lqw.eq(StringUtils.isNotBlank(bo.getType()), SysScreeningAssessmentConfig::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getGender()), SysScreeningAssessmentConfig::getGender, bo.getGender());
        lqw.eq(StringUtils.isNotBlank(bo.getAge()), SysScreeningAssessmentConfig::getAge, bo.getAge());
        lqw.like(StringUtils.isNotBlank(bo.getName()), SysScreeningAssessmentConfig::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getDescription()), SysScreeningAssessmentConfig::getDescription, bo.getDescription());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysScreeningAssessmentConfig::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增筛查/评估配置
     *
     * @param bo 筛查/评估配置
     * @return 是否新增成功
     */
    @Override
    @Transactional
    public Boolean insertByBo(SysScreeningAssessmentConfigBo bo) {
        SysScreeningAssessmentConfig add = MapstructUtils.convert(bo, SysScreeningAssessmentConfig.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setConfigId(add.getConfigId());

            if (ObjUtil.isNotNull(bo.getBaseInfo())) {
                SysScreeningAssessmentQuestionBo questionBo = bo.getBaseInfo();
                questionBo.setConfigId(add.getConfigId());
                questionBo.setContent(JSON.toJSONString(questionBo.getContentList()));
                SysScreeningAssessmentQuestion question = MapstructUtils.convert(questionBo, SysScreeningAssessmentQuestion.class);
                questionMapper.insert(question);
            }
            if (CollUtil.isNotEmpty(bo.getOtherInfo())) {
                List<SysScreeningAssessmentQuestionBo> questionBoList = bo.getOtherInfo();
                questionBoList.forEach(questionBo -> {
                    questionBo.setConfigId(add.getConfigId());
                    questionBo.setContent(JSON.toJSONString(questionBo.getContentList()));
                });

                List<SysScreeningAssessmentQuestion> questionList = MapstructUtils.convert(questionBoList, SysScreeningAssessmentQuestion.class);
                questionMapper.insertBatch(questionList);
            }
        }
        return flag;
    }

    /**
     * 修改筛查/评估配置
     *
     * @param bo 筛查/评估配置
     * @return 是否修改成功
     */
    @Override
    @Transactional
    public Boolean updateByBo(SysScreeningAssessmentConfigBo bo) {
        SysScreeningAssessmentConfig update = MapstructUtils.convert(bo, SysScreeningAssessmentConfig.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;

        if (flag) {
            questionMapper.delete(Wrappers.lambdaQuery(SysScreeningAssessmentQuestion.class)
                .eq(SysScreeningAssessmentQuestion::getConfigId, update.getConfigId()));

            if (ObjUtil.isNotNull(bo.getBaseInfo())) {
                SysScreeningAssessmentQuestionBo questionBo = bo.getBaseInfo();
                questionBo.setConfigId(update.getConfigId());
                questionBo.setContent(JSON.toJSONString(questionBo.getContentList()));
                SysScreeningAssessmentQuestion question = MapstructUtils.convert(questionBo, SysScreeningAssessmentQuestion.class);
                questionMapper.insert(question);
            }
            if (CollUtil.isNotEmpty(bo.getOtherInfo())) {
                List<SysScreeningAssessmentQuestionBo> questionBoList = bo.getOtherInfo();
                questionBoList.forEach(questionBo -> {
                    questionBo.setConfigId(update.getConfigId());
                    questionBo.setContent(JSON.toJSONString(questionBo.getContentList()));
                });

                List<SysScreeningAssessmentQuestion> questionList = MapstructUtils.convert(questionBoList, SysScreeningAssessmentQuestion.class);
                questionMapper.insertBatch(questionList);
            }
        }

        return flag;
    }

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

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