<?php

/**
 * 部门信息接口
 */
namespace app\api\controller\v1\common;
use app\api\exception\DbLinkException;
use think\Db;

class Department
{
    public $list = [];

    /**
     * 获取部门列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDepartments(){
        $depts = Db::table('department')->field('id,pid,name,sort')->order('pid asc')->select();
        if(!$depts)
            throw new DbLinkException;

        return json([
            'status'=>1,
            'message'=>'ok',
            'data' => $depts
        ]);
    }

    /**
     * 获取部门列表带部门级别
     * @return \think\response\Json
     * @throws DbLinkException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDepartmentsWithLevel(){
        $depts = Db::table('department')->field('id,pid,name,sort')->select();
        if(!$depts)
            throw new DbLinkException;

        $data = $this->getTree($depts);
        return json([
            'status'=>1,
            'message'=>'ok',
            'data' => $data
        ]);
    }

    //返回节点树
    private function getTree($array, $pid =0, $level = 2){
        //声明静态数组,避免递归调用时,多次声明导致数组覆盖
        foreach ($array as $key => $value){
            //第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
            if ($value['pid'] == $pid){
                //父节点为根节点的节点,级别为0,也就是第一级
                $value['level'] = $level;
                //把数组放到list中
                $this->list[] = $value;
                //把这个节点从数组中移除,减少后续递归消耗
                unset($array[$key]);
                //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
                $this->getTree($array, $value['id'], $level+1);
            }
        }
        return $this->list;
    }

}