package com.zsc.edu.gateway.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.common.util.TreeUtil;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.modules.system.dto.DeptDto;
import com.zsc.edu.gateway.modules.system.entity.Dept;
import com.zsc.edu.gateway.modules.system.mapper.DeptMapper;
import com.zsc.edu.gateway.modules.system.repo.DeptRepository;
import com.zsc.edu.gateway.modules.system.service.DeptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 部门 服务实现类
 * </p>
 *
 * @author Yao
 * @since 2023-04-06
 */
@RequiredArgsConstructor
@Service
public class DeptServiceImpl extends ServiceImpl<DeptRepository, Dept> implements DeptService {

    private final DeptMapper mapper;

    @Override
    public Dept create(DeptDto dto) {
        boolean existsByName = count(new LambdaQueryWrapper<Dept>().eq(Dept::getName, dto.getName())) > 0;
        if (existsByName) {
            throw new ConstraintException("name", dto.name, "部门已存在");
        }
        Dept dept = mapper.toEntity(dto);
        save(dept);
        return dept;
    }

    @Override
    public Boolean edit(DeptDto dto, Long id) {
        boolean isExists = count(new LambdaQueryWrapper<Dept>().ne(Dept::getId, id).eq(Dept::getName, dto.getName())) > 0;
        if (isExists) {
            throw new ConstraintException("name", dto.name, "同名部门已存在");
        }
        return update(dto.updateWrapper(id));
    }

    @Override
    public Boolean toggle(Long id) {
        Dept dept = getById(id);
        dept.setEnabled(!dept.getEnabled());
        return updateById(dept);
    }

    @Override
    public List<Dept> listTree(Long deptId) {
        List<Dept> deptTrees = baseMapper.selectDeptTree();
        List<Dept> deptTree = TreeUtil.makeTree(
                deptTrees,
                department -> department.getPid() == null || department.getPid() == -1L,
                (parent, child) -> parent.getId().equals(child.getPid()),
                Dept::setChildren
        );

        if (Objects.nonNull(deptId)) {
            if (deptId == 0) {
                // 返回全部部门树
                return deptTree;
            } else {
                // 返回指定部门及其子部门树
                List<Dept> deptChildrenTree = new ArrayList<>();
                TreeUtil.forLevelOrder(deptTree, node -> {
                    if (node.getId().equals(deptId)) {
                        deptChildrenTree.add(node);
                    }
                }, Dept::getChildren);
                return deptChildrenTree;
            }
        }
        return deptTree;
    }

}
