package org.dromara.web.service.impl;

import cn.hutool.core.collection.CollUtil;
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.SysDept;
import org.dromara.system.domain.SysDiseaseLabel;
import org.dromara.system.domain.SysMenu;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysDiseaseLabelVo;
import org.dromara.system.domain.vo.SysMenuVo;
import org.dromara.system.mapper.SysDiseaseLabelMapper;
import org.dromara.system.mapper.SysMenuMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysDiseaseLabelService;
import org.dromara.web.domain.ConsultantResultTemplate;
import org.dromara.web.domain.ConsultantResultTemplateType;
import org.dromara.web.domain.NutritionDiagnosis;
import org.dromara.web.domain.bo.NutritionDiagnosisBo;
import org.dromara.web.domain.vo.ConsultantResultTemplateVo;
import org.dromara.web.domain.vo.NutritionDiagnosisVo;
import org.dromara.web.domain.vo.TreatmentUserVo;
import org.dromara.web.mapper.ConsultantResultTemplateMapper;
import org.dromara.web.mapper.ConsultantResultTemplateTypeMapper;
import org.dromara.web.mapper.NutritionDiagnosisMapper;
import org.dromara.web.service.INutritionDiagnosisService;
import org.dromara.web.service.ITreatmentUserService;
import org.springframework.stereotype.Service;


import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 营养诊断Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class NutritionDiagnosisServiceImpl implements INutritionDiagnosisService {

    private final NutritionDiagnosisMapper baseMapper;

    private final SysUserMapper userMapper;

    private final SysDiseaseLabelMapper labelMapper;

    private final ITreatmentUserService treatmentUserService;

    private final ConsultantResultTemplateMapper templateMapper;

    private final ISysDiseaseLabelService diseaseLabelService;

    private final ConsultantResultTemplateTypeMapper templateTypeMapper;

    /**
     * 查询营养诊断
     *
     * @param id 主键
     * @return 营养诊断
     */
    @Override
    public NutritionDiagnosisVo queryById(Long id) {

        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询营养诊断列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 营养诊断分页列表
     */
    @Override
    public TableDataInfo<NutritionDiagnosisVo> queryPageList(NutritionDiagnosisBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<NutritionDiagnosis> lqw = buildQueryWrapper(bo);
        Page<NutritionDiagnosisVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<SysUser> userList = userMapper.selectList(Wrappers.lambdaQuery(SysUser.class).select(SysUser::getUserId, SysUser::getUserName));
        Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(k1 -> k1.getUserId(), k2 -> String.valueOf(k2.getUserName()), (k1, k2) -> k1));


        List<NutritionDiagnosisVo> records = result.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            String labelIdsStr = null;
            List<String> labelNames = null;
            for (NutritionDiagnosisVo record : records) {
                record.setCreateByUser(userMap.get(record.getCreateBy()));
                labelIdsStr = record.getDiagnosisLableId();
                // 处理产品标签
                if (StringUtils.isNotBlank(labelIdsStr)) {
                    labelNames = Arrays.stream(labelIdsStr.split(",")).map(String::trim).filter(StringUtils::isNotBlank).map(labelid -> {
                        try {
                            return diseaseLabelService.queryById(Long.parseLong(labelid));
                        } catch (NumberFormatException e) {
                            return null;
                        }
                    }).filter(Objects::nonNull).map(SysDiseaseLabelVo::getLabelName).filter(StringUtils::isNotBlank).collect(Collectors.toList());

                    if (!labelNames.isEmpty()) {
                        record.setDiagnosisLabelStr(String.join(",", labelNames));
                    }
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的营养诊断列表
     *
     * @param bo 查询条件
     * @return 营养诊断列表
     */
    @Override
    public List<NutritionDiagnosisVo> queryList(NutritionDiagnosisBo bo) {
        LambdaQueryWrapper<NutritionDiagnosis> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NutritionDiagnosis> buildQueryWrapper(NutritionDiagnosisBo bo) {
        Map<String, Object> params = bo.getParams();
        List<Date> dateRange = bo.getDateRange();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        LambdaQueryWrapper<NutritionDiagnosis> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(NutritionDiagnosis::getId);
        lqw.eq(bo.getTreatmentUserId() != null, NutritionDiagnosis::getTreatmentUserId, bo.getTreatmentUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), NutritionDiagnosis::getType, bo.getType());
        lqw.like(StringUtils.isNotBlank(bo.getSearchValue()), NutritionDiagnosis::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(NutritionDiagnosis::getCreateTime, startTime, endTime);

            }
        }
        return lqw;
    }

    /**
     * 新增营养诊断
     *
     * @param bo 营养诊断
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(NutritionDiagnosisBo bo) {
        bo.setDiagnosisLableId(String.join(",", bo.getLabelList()));
        Long treatmentUserId = bo.getTreatmentUserId();
        if (null != treatmentUserId) {
            TreatmentUserVo treatmentUserVo = treatmentUserService.queryById(treatmentUserId);
            if (null != treatmentUserVo) {
                bo.setType(treatmentUserVo.getType());
                bo.setOutpatientNo(treatmentUserVo.getOutpatientNo());
            }
        }
        bo.setConsultantResult(URLDecoder.decode(new String(Base64.getDecoder().decode(bo.getConsultantResultStr()), StandardCharsets.UTF_8)));
        NutritionDiagnosis add = MapstructUtils.convert(bo, NutritionDiagnosis.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改营养诊断
     *
     * @param bo 营养诊断
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(NutritionDiagnosisBo bo) {
        bo.setDiagnosisLableId(String.join(",", bo.getLabelList()));
        bo.setConsultantResult(URLDecoder.decode(new String(Base64.getDecoder().decode(bo.getConsultantResultStr()), StandardCharsets.UTF_8)));
        NutritionDiagnosis update = MapstructUtils.convert(bo, NutritionDiagnosis.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(NutritionDiagnosis 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 Map<String, Object> queryTemplateList() {
        Map<String, Object> resultMap = new HashMap<>();

        List<Map<String, Object>> result = new ArrayList<>();
        // 1. 处理 "基础/公共模板" 部分
        Map<String, Object> publicTemplate = new HashMap<>();
        publicTemplate.put("label", "基础/公共模板");

// 查询所有公共模板类型
        List<ConsultantResultTemplateType> publicTypes = templateTypeMapper.selectList();

        List<Map<String, Object>> publicChildren = new ArrayList<>();
        for (ConsultantResultTemplateType type : publicTypes) {
            Map<String, Object> typeNode = new HashMap<>();
            typeNode.put("label", type.getTemplateType()); // 模板类型名称，如 "基础模板"

            // 查询该类型下的所有模板
            List<ConsultantResultTemplateVo> templates = templateMapper.selectVoList(
                new LambdaQueryWrapper<ConsultantResultTemplate>()
                    .eq(ConsultantResultTemplate::getTemplateTypeId, type.getId())
            );

            List<Map<String, Object>> templateChildren = new ArrayList<>();
            for (ConsultantResultTemplateVo template : templates) {
                Map<String, Object> templateNode = new HashMap<>();
                templateNode.put("id", template.getId()); // 模板名称
                templateNode.put("label", template.getTemplateName()); // 模板名称
                templateNode.put("template", template.getContent());
                templateChildren.add(templateNode);
            }

            typeNode.put("children", templateChildren);
            publicChildren.add(typeNode);
        }

        publicTemplate.put("children", publicChildren);
        result.add(publicTemplate);

// 2. 处理 "个人模板" 部分
        Map<String, Object> personalTemplate = new HashMap<>();
        personalTemplate.put("label", "个人模板");
        result.add(personalTemplate);
        resultMap.put("data", result);
        return resultMap;
    }
}
