<?php

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

class Department
{
    public $list = [];

    public function getCurrentUserDepartment(){
        //获取当前用户部门ID
    }

    public function getDepartments(){
        $depts = Db::table('department')->field('id,pid,name,sort')->order('pid asc')->select();
        return json([
            'status'=>1,
            'message'=>'ok',
            'data' => $depts
        ]);
    }

    public function getDepartmentsWithLevel(){
        $depts = Db::table('department')->field('id,pid,name,sort')->select();

        $data = $this->getTree($depts);

        return json($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;
    }

}