package com.hotwj.platform.config.systemTemplate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotwj.platform.config.systemTemplate.domain.HotSystemTemplate;
import com.hotwj.platform.config.systemTemplate.domain.bo.HotSystemTemplateBo;
import com.hotwj.platform.config.systemTemplate.domain.vo.HotSystemTemplateVo;
import com.hotwj.platform.config.systemTemplate.mapper.HotSystemTemplateMapper;
import com.hotwj.platform.config.systemTemplate.service.IHotSystemTemplateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * 体系模板Service业务层处理
 *
 * @author shihongwei
 * @date 2026-02-14
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotSystemTemplateServiceImpl implements IHotSystemTemplateService {

    private final HotSystemTemplateMapper baseMapper;

    /**
     * 查询体系模板
     *
     * @param id 主键
     * @return 体系模板
     */
    @Override
    public HotSystemTemplateVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询体系模板列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 体系模板分页列表
     */
    @Override
    public TableDataInfo<HotSystemTemplateVo> queryPageList(HotSystemTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotSystemTemplate> lqw = buildQueryWrapper(bo);
        Page<HotSystemTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的体系模板列表
     *
     * @param bo 查询条件
     * @return 体系模板列表
     */
    @Override
    public List<HotSystemTemplateVo> queryList(HotSystemTemplateBo bo) {
        LambdaQueryWrapper<HotSystemTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotSystemTemplate> buildQueryWrapper(HotSystemTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotSystemTemplate> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotSystemTemplate::getId);
        lqw.eq(bo.getCompanyId() != null, HotSystemTemplate::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getParentId() != null, HotSystemTemplate::getParentId, bo.getParentId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), HotSystemTemplate::getName, bo.getName());
        lqw.eq(bo.getType() != null, HotSystemTemplate::getType, bo.getType());
        lqw.like(StringUtils.isNotBlank(bo.getCreateByName()), HotSystemTemplate::getCreateByName, bo.getCreateByName());
        lqw.like(StringUtils.isNotBlank(bo.getUpdateByName()), HotSystemTemplate::getUpdateByName, bo.getUpdateByName());
        lqw.eq(bo.getIsDeleted() != null, HotSystemTemplate::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增体系模板
     *
     * @param bo 体系模板
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotSystemTemplateBo bo) {
        HotSystemTemplate add = MapstructUtils.convert(bo, HotSystemTemplate.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改体系模板
     *
     * @param bo 体系模板
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotSystemTemplateBo bo) {
        HotSystemTemplate update = MapstructUtils.convert(bo, HotSystemTemplate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotSystemTemplate entity) {
        if (entity.getParentId() == null) {
            LambdaQueryWrapper<HotSystemTemplate> lqw = Wrappers.lambdaQuery();
            lqw.eq(HotSystemTemplate::getCompanyId, entity.getCompanyId());
            lqw.eq(HotSystemTemplate::getType, entity.getType());
            lqw.eq(HotSystemTemplate::getIsDeleted, 0L);
            lqw.ne(entity.getId() != null, HotSystemTemplate::getId, entity.getId());
            Long count = baseMapper.selectCount(lqw);
            if (count != null && count > 0) {
                throw new ServiceException("同公司同体系类型的根节点只能存在一个");
            }
        }
    }

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

    @Override
    public Boolean syncFromHeadquarters(Long companyId, Long type) {
        Long hqCompanyId = 1L;
        LambdaQueryWrapper<HotSystemTemplate> hqWrapper = Wrappers.lambdaQuery();
        hqWrapper.eq(HotSystemTemplate::getCompanyId, hqCompanyId);
        hqWrapper.eq(HotSystemTemplate::getType, type);
        hqWrapper.eq(HotSystemTemplate::getIsDeleted, 0L);
        List<HotSystemTemplate> hqList = baseMapper.selectList(hqWrapper);
        if (hqList.isEmpty()) {
            return true;
        }
        LambdaQueryWrapper<HotSystemTemplate> tgtWrapper = Wrappers.lambdaQuery();
        tgtWrapper.eq(HotSystemTemplate::getCompanyId, companyId);
        tgtWrapper.eq(HotSystemTemplate::getType, type);
        tgtWrapper.eq(HotSystemTemplate::getIsDeleted, 0L);
        List<HotSystemTemplate> tgtList = baseMapper.selectList(tgtWrapper);
        for (HotSystemTemplate t : tgtList) {
            t.setIsDeleted(1L);
            baseMapper.updateById(t);
        }
        Map<Long, List<HotSystemTemplate>> children = hqList.stream().collect(Collectors.groupingBy(HotSystemTemplate::getParentId));
        Map<Long, Long> idMap = new HashMap<>();
        List<HotSystemTemplate> roots = hqList.stream()
            .filter(e -> e.getParentId() == null || Long.valueOf(0L).equals(e.getParentId()))
            .collect(Collectors.toList());
        for (HotSystemTemplate r : roots) {
            copyNode(r, companyId, type, idMap, children);
        }
        return true;
    }

    private void copyNode(HotSystemTemplate src, Long companyId, Long type,
                          Map<Long, Long> idMap, Map<Long, List<HotSystemTemplate>> children) {
        Long parentTargetId = src.getParentId() == null ? null : idMap.get(src.getParentId());
        HotSystemTemplate add = new HotSystemTemplate();
        add.setCompanyId(companyId);
        add.setParentId(parentTargetId);
        add.setName(src.getName());
        add.setType(type);
        add.setIsDeleted(0L);
        baseMapper.insert(add);
        idMap.put(src.getId(), add.getId());
        List<HotSystemTemplate> childList = children.get(src.getId());
        if (childList != null) {
            for (HotSystemTemplate c : childList) {
                copyNode(c, companyId, type, idMap, children);
            }
        }
    }
 
}
