package im.zhaojun.system.service;
import im.zhaojun.system.mapper.DeptTreeMapper;
import im.zhaojun.system.model.Dept;
import im.zhaojun.system.model.DeptTree;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class DeptTreeService {

    @Resource
    private DeptTreeMapper deptTreeMapper;

    public DeptTree insert(DeptTree dept) {
        int maxOrderNum = deptTreeMapper.selectMaxOrderNum();
        dept.setOrderNum(maxOrderNum + 1);
        deptTreeMapper.insert(dept);
        return dept;
    }
    public int selectMaxOrderNum() {
        return deptTreeMapper.selectMaxOrderNum();
    }

    public int deleteByPrimaryKey(String deptId) {
        return deptTreeMapper.deleteByPrimaryKey(deptId);
    }

    public DeptTree updateByPrimaryKey(DeptTree dept) {
        deptTreeMapper.updateByPrimaryKey(dept);
        return dept;
    }

    public DeptTree selectByPrimaryKey(String deptId) {
        return deptTreeMapper.selectByPrimaryKey(deptId);
    }


    /**
     * 删除当前部门及子部门.
     */
    public void deleteCascadeByID(String deptId) {

        List<String> childIDList = deptTreeMapper.selectChildrenIDByPrimaryKey(deptId);
        for (String childId : childIDList) {
            deleteCascadeByID(childId);
        }

        deleteByPrimaryKey(deptId);
    }

    /**
     * 根据父 ID 查询部门
     */
    public List<DeptTree> selectByParentId(String parentId) {
        return deptTreeMapper.selectByParentId(parentId);
    }

    /**
     * 查找所有的部门的树形结构
     */
    public List<DeptTree> selectAllDeptTree(String parentId) {
        return deptTreeMapper.selectAllTree(parentId);
    }

    /**
     * 获取所有菜单并添加一个根节点 (树形结构)
     */
    public List<DeptTree> selectAllDeptTreeAndRoot() {
        return  selectAllDeptTree(null);
    }



    public void swapSort(Integer currentId, Integer swapId) {
        deptTreeMapper.swapSort(currentId, swapId);
    }
}
