<?php
namespace app\admin\model;

use think\facade\Session;

class DepartmentModel extends BaseModel
{
    protected $table = 'department';

    public function getDepartmentTree(){
        $data = $this->order('sort desc,id asc')->select()->toArray();
        $data = getTree($data);
        foreach ($data as &$value){
            $value['title'] = str_repeat('--', $value['level']).$value['name'];
        }
        return $data;
    }

    //通过递归循环取出所有pid下属的部门id
    //return ids = [];
    public function getNodeIds($pid){

        $data = self::field('id,pid')->select()->toArray();
        $ids = getNodeIds($data,$pid);
        $ids = array_unique($ids);

        $ids = implode(',',$ids);
        return $ids;
    }
    public function getNodesTree($fields = 'id,pid,name',$isNav = false){
        if($fields != ''){
            $this->fields = $fields;
        }
        $data = $this->field($this->fields)->order('sort desc,id asc')->select()->toArray();
        if(empty($data) || false == $data){
            throw new Exception('没有权限数据!');
        }
        $data = getNodesTree($data);
//        return json_encode((object)$data);
        return $data;
    }

    public function getDeparmentIds(){
        $user = Session::get('user');
        $staff = StaffModel::get(['id'=>$user['user_id']]);
        return $this->getNodeIds($staff->d_id);
    }

}