<?php

namespace app\admin\model;

use app\BaseModel;

class Department extends BaseModel
{

    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    //获取指定部门的下级树形结构
    public static function getChildrenTree($department_id) {
        //查询所有下级部门
        $list = self::order('parent_id', 'asc')
            ->order('weight', 'desc')
            ->select();   
        $tree = linear_to_tree($list, 'children', 'id', 'parent_id', $department_id);
        return $tree;
    }

    //获取所有下级的ID
    public static function getChildrenIds($children) {
        $ids = [];
        foreach ($children as $value) {
            $ids[] = $value['id'];
            if (!empty($value['children'])) {
                $ids = array_merge($ids, self::getChildrenIds($value['children']));
            }
        }
        return $ids;
    }

    //获取部门下级的所有客服ID
    public static function getDepartmentCsUids($admin_id) { 
        $department_id = Admin::where('id', $admin_id)->value('department_id');
        $parent_department_id = self::where('id', $department_id)->value('parent_id');
        $tree = self::getChildrenTree($parent_department_id);
        $department_ids = self::getChildrenIds($tree);

        $cs_uids = Admin::alias('admin')
                    ->join(env('database.DATABASE').'.bot_users user', 'admin.id = user.uid', 'left')
                    // ->join('user', 'admin.id=user.uid','left')
                    ->whereIn('admin.department_id', $department_ids)
                    ->where('user.role', '>', 0)
                    ->column('user.user_id');
        return $cs_uids;
    }

}