package com.tuoheng.admin.service.dept.query;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.conver.DeptConverMapper;
import com.tuoheng.admin.entity.Dept;
import com.tuoheng.admin.enums.code.dept.QueryDeptTreeListCodeEnum;
import com.tuoheng.admin.mapper.DeptMapper;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.dept.DeptTreeVo;
import com.tuoheng.common.core.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  获取部门树形列表业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-11-19
 */
@Slf4j
@Service
public class QueryListTreeService {

    @Autowired
    private DeptMapper deptMapper;

    /**
     * 获取部门树形列表
     *
     * @return
     */
    public JsonResult getListTree() {
        List<DeptTreeVo> deptTreeVoList = new ArrayList<>();

        String tenantId = CurrentUserUtil.getTenantId();

        // 查询所有有效的部门数据
        List<Dept> deptList = deptMapper.selectList(new LambdaQueryWrapper<Dept>()
                                .eq(Dept::getTenantId, tenantId)
                                .eq(Dept::getMark, 1));

        if (CollectionUtil.isEmpty(deptList)) {
            log.info("获取部门列表为空");
            return JsonResult.success(deptTreeVoList);
        }

        List<DeptTreeVo> deptTreeVoListTmp = DeptConverMapper.INSTANCE.deptListToDeptVoList(deptList);

        Map<String, DeptTreeVo> deptVoMap = new HashMap<>();
        for (DeptTreeVo deptTreeVo : deptTreeVoListTmp) {
            deptVoMap.put(deptTreeVo.getId(), deptTreeVo);
        }
        for (DeptTreeVo deptTreeVo : deptTreeVoListTmp) {
            DeptTreeVo child = deptTreeVo;
            if (SystemConstant.ROOT_DEPT_PID.equals(child.getPid())) {
                deptTreeVoList.add(deptTreeVo);
            } else {
                DeptTreeVo parent = deptVoMap.get(child.getPid());
                deptTreeVo.setPname(parent.getName());
                parent.getChildren().add(child);
            }
        }
        return JsonResult.success(deptTreeVoList);
    }

}
