<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace common\api;

use Yii;
use yii\db\Query;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use qcbase\models\Department as DepartmentModel;
use common\components\Tree;

/**
 * 部门接口文件
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class Department extends Api
{

    /**
     * 根据id获取某一个部门的信息
     * 
     * @param type $user
     */
    public static function getOne($id)
    {
        $list = self::getList();
        return ArrayHelper::getValue($list, $id);
    }

    /**
     * 获取部门列表
     *
     * @author HuLimin http://blog.u-bo.com
     *
     * @param type $map 查询条件，默认空
     * @param type $field 所需字段
     * @return type
     */
    public static function getList($map = [], $field = '*')
    {
        $cache = Yii::$app->cache;
        $list = $cache->get('api_dept_list_hlm');
        if (false === $list) {
            $query = self::getQuery($map, $field);

            $list = $query->all();
            $cache->set('api_dept_list', $list);
        }
        return $list;
    }

    /**
     * 获取部门列表（树形）
     *
     * @return type
     */
    public static function getListByTree()
    {
        $cache = Yii::$app->cache;
        $list = $cache->get('api_dept_list_tree');

        if (false === $list) {
            $list = self::getQuery()->indexBy('dept_id')->all();
            $list = Tree::getList($list, 'dept_id', 'parent_id');
            $list = ArrayHelper::index($list, 'dept_id');
            $cache->set('api_dept_list_tree', $list);
        }

        return $list;
    }

    /**
     * 获取部门通用的查询对象
     * 
     * @return type
     */
    private static function getQuery($map = [], $field = '*')
    {
        $query = DepartmentModel::find()
            ->select($field)
            ->where('status=:status', [':status' => \common\models\User::STATUS_ENABLE])
            ->orderBy(['sort' => SORT_DESC])
            ->asArray();
        if (!empty($map) && is_array($map)) {
            foreach ($map as $m) {
                $query->andWhere($m);
            }
        }
        return $query;
    }
}