<?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 common\models\User as UserModel;
use common\api\Department as DepartmentApi;

/**
 * 用户接口文件
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class User extends Api
{

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

    /**
     * 获取用户列表
     * 
     * @return type
     */
    public static function getList()
    {
        $cache = Yii::$app->cache;
        $list = false;//$cache->get('api_user_list');

        if (false === $list) {
            $list = self::getQuery()->all();
            $list = self::getExtraInfo($list);
            $cache->set('api_user_list', $list);
        }

        return $list;
    }

    /**
     * 取得分页用户
     *
     * @return array 返回一个数组，data里包含分页用户，pagination包含分页对象
     */
    public static function getListByPage($map = null, $pageSize = 15)
    {
        $query = self::getQuery($map);
        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => $pageSize,
            ],
        ]);
        $data = $provider->getModels();
        $data = self::getExtraInfo($data);
        $list['data'] = $data;
        $list['pagination'] = $provider->pagination;
        return $list;
    }

    /**
     * 按照部门取得用户
     *
     * @author HuLimin http://blog.u-bo.com
     *
     * @param int $deptId 部门id
     * @param bool $tree 部门是否获取数结构
     * @return array 
     */
    public static function getListByDepartment($map = [], $deptId = 0, $tree = false)
    {
        $query = new Query();

        $depts = ($tree) ? DepartmentApi::getListByTree() : DepartmentApi::getList($map);

        if ($deptId) {
            $temp = (array_key_exists($deptId, $depts)) ? [$deptId => $depts[$deptId]] : [];
            $depts = $temp;
        }
        foreach ($depts as &$dept) {
            $user_ids = $query->select('user_id')->from('{{%user_department}}')->where(['in', 'dept_id', explode(',', $dept['child_ids'])])->column();
            $newMap = array_merge($map, [['in', 'u.user_id', $user_ids]]);
            $dept['user'] = self::getQuery($newMap)->all();
        }
        return $depts;
    }

    /**
     * 获取用户通用的查询对象
     *
     * @return type
     */
    private static function getQuery($map = null)
    {
        $query = (new \yii\db\Query())
            ->select('u.user_id,u.user_no,u.username,u.realname,u.gender,u.email,u.avatar,u.status,i.phone,i.qq,i.remark')
            ->from('{{%user}} u')
            ->leftJoin('{{%user_info}} i', 'i.user_id = u.user_id')
            //->leftJoin('{{%department}} d', 'd.dept_id = u.dept_id')
            ->where('u.status=:status', [':status' => \common\models\User::STATUS_ENABLE])
            ->orderBy(['u.user_id' => SORT_ASC])
            ->indexBy('user_id');

        if ($map !== null && is_array($map)) {
            foreach ($map as $m) {
                $query->andWhere($m);
            }
        }
        return $query;
    }

    /**
     * 获取额外的信息
     * 
     * @return type
     */
    private static function getExtraInfo($list)
    {
        $list = self::addDept($list);
        $list = self::addRole($list);
        return $list;
    }

    /**
     * 获取用户的部门列表
     * 
     * @param type $list
     * @return type
     */
    private static function addDept($list)
    {
        $query = new \yii\db\Query();
        $deptList = DepartmentApi::getList();
        foreach ($list as &$user) {
            $depts = [];
            $deptArr = $query->select('dept_id')->from('{{%user_department}}')->where(['user_id' => $user['user_id']])->column();
            foreach ($deptArr as $deptId) {
                array_key_exists($deptId, $deptList) && $depts[$deptId] = $deptList[$deptId]['name'];
            }
            $user['depts'] = $depts;
        }
        return $list;
    }

    /**
     * 获取用户的角色
     *
     * @param type $list
     * @return type
     */
    private static function addRole($list)
    {
        foreach ($list as &$user) {
            $user['roles'] = array_keys(\qcbase\models\Auth::getRolesByUser($user['user_id']));
        }
        return $list;
    }
}
