package com.cmeeting.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmeeting.constant.CategoryConstant;
import com.cmeeting.mapper.primary.SysUserSyncCategoryMapper;
import com.cmeeting.pojo.SysUserSyncCategory;
import com.cmeeting.service.ISysUserSyncCategoryService;
import com.cmeeting.util.CategoryTreeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysUserSyncCategoryServiceImpl extends ServiceImpl<SysUserSyncCategoryMapper, SysUserSyncCategory> implements ISysUserSyncCategoryService {


    @Override
    public String getPath(String id, Map<String, String> map) {
        if (map.get(id) == null) {
            return "";
        }
        if (map.get(id).equals(CategoryConstant.ROOT_ID)) {
            return CategoryConstant.ROOT_PATH + id;
        }
        return getPath(map.get(id), map) + CategoryConstant.ROOT_PATH + id;
    }

    @Override
    public List<Tree<String>> tree() {
        List<SysUserSyncCategory> sysUserSyncCategories = baseMapper.selectList(new LambdaQueryWrapper<>());
        if(CollUtil.isNotEmpty(sysUserSyncCategories)){
            Set<String> set = sysUserSyncCategories.stream().map(SysUserSyncCategory::getDeptId).collect(Collectors.toSet());
            for (SysUserSyncCategory sysUserSyncCategory : sysUserSyncCategories) {
                if(!set.contains(sysUserSyncCategory.getParentId())){
                    sysUserSyncCategory.setParentId(CategoryTreeUtil.ALL);
                }
            }
        }
        SysUserSyncCategory top = SysUserSyncCategory.builder()
                .id(CategoryTreeUtil.ALL)
                .deptId(CategoryTreeUtil.ALL)
                .name(CategoryTreeUtil.NAME)
                .parentId(CategoryConstant.ROOT_ID).build();
        sysUserSyncCategories.add(top);
        CategoryTreeUtil<SysUserSyncCategory> util = new CategoryTreeUtil<>();
        return util.build(sysUserSyncCategories);
    }

    @Override
    public List<SysUserSyncCategory> selectParentIdNoInId(String search) {
        return baseMapper.selectParentIdNoInId(search);
    }

    @Override
    public String getPathName(String deptId, Map<String, String> parentIdMap, Map<String, String> nameMap) {
        if (parentIdMap.get(deptId) == null) {
            return "";
        }
        if (parentIdMap.get(deptId).equals(CategoryConstant.ROOT_ID)) {
            return CategoryConstant.ROOT_PATH + nameMap.get(deptId);
        }
        return getPathName(parentIdMap.get(deptId), parentIdMap, nameMap) + CategoryConstant.ROOT_PATH + nameMap.get(deptId);
    }
}

