package org.dromara.web.service.impl;

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.SysUser;
import org.dromara.system.domain.bo.SysDiseaseLabelBo;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.mapper.SysDiseaseLabelMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.web.domain.NutritionEducationTemplate;
import org.dromara.web.domain.TreatmentUser;
import org.dromara.web.domain.bo.NutritionEducationTemplateBo;
import org.dromara.web.domain.vo.NutritionEducationTemplateVo;
import org.dromara.web.mapper.NutritionEducationTemplateMapper;
import org.dromara.web.service.INutritionEducationTemplateService;
import org.springframework.stereotype.Service;


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

/**
 * 营养宣教模板Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-14
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class NutritionEducationTemplateServiceImpl implements INutritionEducationTemplateService {

    private final NutritionEducationTemplateMapper baseMapper;

    private final SysDeptMapper deptMapper;

    private final SysUserMapper userMapper;

    private final SysDiseaseLabelMapper labelMapper;

    /**
     * 查询营养宣教模板
     *
     * @param id 主键
     * @return 营养宣教模板
     */
    @Override
    public NutritionEducationTemplateVo queryById(Long id) {
        NutritionEducationTemplateVo templateVo = baseMapper.selectVoById(id);
        List<SysDept> deptlList = deptMapper.selectList(Wrappers.lambdaQuery(SysDept.class).select(SysDept::getDeptId, SysDept::getDeptName));
        Map<String, String> deptMap = deptlList.stream().collect(Collectors.toMap(k1 -> String.valueOf(k1.getDeptId()), k2 -> k2.getDeptName(), (k1, k2) -> k1));

        List<SysDiseaseLabel> disLabelList = labelMapper.selectList(Wrappers.lambdaQuery(SysDiseaseLabel.class).select(SysDiseaseLabel::getLabelId, SysDiseaseLabel::getLabelName));
        Map<String, String> labelMap = disLabelList.stream().collect(Collectors.toMap(k1 -> String.valueOf(k1.getLabelId()), k2 -> String.valueOf(k2.getLabelName()), (k1, k2) -> k1));

        if (StringUtils.isNotBlank(templateVo.getDeptId())) {
            List<String> stringIdList = Arrays.stream(templateVo.getDeptId().split(",")).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());
           List<String> deptNameList = new ArrayList<>();
            for (String idStr : stringIdList) {
                deptNameList.add(deptMap.get(idStr));
            }
            templateVo.setDeptName(String.join(",", deptNameList));
        }

        if (StringUtils.isNotBlank(templateVo.getDiseaseLabelId())) {
            List<String> labelIdList = Arrays.stream(templateVo.getDiseaseLabelId().split(",")).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());
            List<String> labelList = new ArrayList<>();
            for (String idStr : labelIdList) {
                labelList.add(labelMap.get(idStr));
            }
            templateVo.setDiseaseLabelId(String.join(",", labelList));
        }
        return templateVo;
    }

    /**
     * 分页查询营养宣教模板列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 营养宣教模板分页列表
     */
    @Override
    public TableDataInfo<NutritionEducationTemplateVo> queryPageList(NutritionEducationTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<NutritionEducationTemplate> lqw = buildQueryWrapper(bo);
        Page<NutritionEducationTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<NutritionEducationTemplateVo> records = result.getRecords();
        String deptId = null;
        String name = null;
        List<String> deptIds = null;
        List<String> deptNameList = null;
        List<SysDept> deptlList = deptMapper.selectList(Wrappers.lambdaQuery(SysDept.class).select(SysDept::getDeptId, SysDept::getDeptName));
        Map<String, String> deptMap = deptlList.stream().collect(Collectors.toMap(k1 -> String.valueOf(k1.getDeptId()), k2 -> k2.getDeptName(), (k1, k2) -> k1));

        List<SysUser> userList = userMapper.selectList(Wrappers.lambdaQuery(SysUser.class).select(SysUser::getUserId, SysUser::getUserName));
        Map<String, String> userMap = userList.stream().collect(Collectors.toMap(k1 -> String.valueOf(k1.getUserId()), k2 -> k2.getUserName(), (k1, k2) -> k1));

        if (null != records) {
            for (NutritionEducationTemplateVo record : records) {
                deptId = record.getDeptId();
                deptIds = Arrays.stream(deptId.split(",")).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());
                deptNameList = new ArrayList<>();
                for (String id : deptIds) {
                    deptNameList.add(deptMap.get(id));
                }
                name = String.join(",", deptNameList); // 自动处理逗号
                record.setDeptName(name);
                if (null != record.getCreateBy()) {
                    record.setCreateByUser(userMap.get(record.getCreateBy().toString()));
                }
                if (null != record.getUpdateBy()) {
                    record.setUpdateByUser(userMap.get(record.getUpdateBy().toString()));
                }
                if (null != record.getCreateDept()) {
                    record.setCreateDeptName(deptMap.get(record.getCreateDept().toString()));
                }
                if (null != record.getUpdateDept()) {
                    record.setUpdateDeptName(deptMap.get(record.getUpdateDept().toString()));
                }

            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的营养宣教模板列表
     *
     * @param bo 查询条件
     * @return 营养宣教模板列表
     */
    @Override
    public List<NutritionEducationTemplateVo> queryList(NutritionEducationTemplateBo bo) {
        LambdaQueryWrapper<NutritionEducationTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NutritionEducationTemplate> buildQueryWrapper(NutritionEducationTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<NutritionEducationTemplate> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(NutritionEducationTemplate::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getDeptId()), NutritionEducationTemplate::getDeptId, bo.getDeptId());
        lqw.like(bo.getCreateDept() != null, NutritionEducationTemplate::getCreateDept, bo.getCreateDept());
        if (StringUtils.isNotBlank(bo.getSearchValue())) {
            lqw.and(wrapper ->
                wrapper.like(NutritionEducationTemplate::getTemplateName, bo.getSearchValue())
                    .or()
                    .like(NutritionEducationTemplate::getDescription, bo.getSearchValue())
                    .or()
                    .like(NutritionEducationTemplate::getCreateBy, bo.getSearchValue())
                    .or()
                    .like(NutritionEducationTemplate::getUpdateBy, bo.getSearchValue()));
        }
        return lqw;
    }

    /**
     * 新增营养宣教模板
     *
     * @param bo 营养宣教模板
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(NutritionEducationTemplateBo bo) {
        String deptId = null;
        String diseaseLabel = null;
        bo.setContent(URLDecoder.decode(new String(Base64.getDecoder().decode(bo.getContentStr()), StandardCharsets.UTF_8)));
        if (null != bo.getDeptIdList() && bo.getDeptIdList().size() > 0) {
            deptId = String.join(",", bo.getDeptIdList());
        }
        bo.setDeptId(deptId);
        if (null != bo.getLabelList() && bo.getLabelList().size() > 0) {
            List<String> labelIds = bo.getLabelList().stream().map(labelBo -> labelBo.getLabelId().toString()).collect(Collectors.toList());
            diseaseLabel = String.join(",", labelIds);
        }
        bo.setDiseaseLabelId(diseaseLabel);
        NutritionEducationTemplate add = MapstructUtils.convert(bo, NutritionEducationTemplate.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            bo.setUpdateDept(bo.getCreateDept());
        }
        return flag;
    }

    /**
     * 修改营养宣教模板
     *
     * @param bo 营养宣教模板
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(NutritionEducationTemplateBo bo) {
        String deptId = null;
        String diseaseLabel = null;
        if (null != bo.getDeptIdList() && bo.getDeptIdList().size() > 0) {
            deptId = String.join(",", bo.getDeptIdList());
        }
        bo.setDeptId(deptId);
        if (null != bo.getLabelList() && bo.getLabelList().size() > 0) {
            List<String> labelIds = bo.getLabelList().stream().map(labelBo -> labelBo.getLabelId().toString()).collect(Collectors.toList());
            diseaseLabel = String.join(",", labelIds);
        }
        bo.setDiseaseLabelId(diseaseLabel);
        bo.setContent(URLDecoder.decode(new String(Base64.getDecoder().decode(bo.getContentStr()), StandardCharsets.UTF_8)));
        NutritionEducationTemplate update = MapstructUtils.convert(bo, NutritionEducationTemplate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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