<?php

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

namespace qcbase\models;

use Yii;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\helpers\Url;
use common\components\Tree;
use common\components\Tool;
use common\models\User;
use qcbase\models\Auth;

/**
 * 用户部门关联信息表 ({{%user_department}})
 *
 * @property integer $user_id  (用户id)
 * @property integer $dept_id  (部门id)
 * @property string $name  (部门名称)
 *
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class UserDepartment extends ActiveRecord
{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user_department}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'user_id' => '用户id',
            'dept_id' => '部门id',
        ];
    }

    /**
     * 根据部门领导获取其所管部门已经其下属部门用户ID
     * @param type $user_id 部门领导
     * @param type $dept_user 返回部门 or 用户 默认访问部门
     *
     * @author HuLimin <http://blog.u-bo.com>
     * @since 0.1
     */
    function getAllUserByLeader($user_id = 0, $dept_user = FALSE)
    {
        $infoArr = [];
        $deptChildArr = Department::find()
                ->select('child_ids')
                ->where(['status' => 1, 'lead_user_id' => $user_id])
                ->asArray()
                ->column();
        if(empty($deptChildArr)){
            return;
        }
        $deptChilds = implode(',', $deptChildArr);
        //去除重复
        $infoArr = array_unique(explode(',', $deptChilds));
        if($dept_user){
            $infoArr = static::find()
                    ->select('user_id')
                    ->where(['in', 'dept_id', $infoArr])
                    ->asArray()
                    ->column();
        }
        return $infoArr;
    }

    /**
     * 获取当前部门以及父部门下所有的用户
     * 
     * @param  integer $dept_id 部门ID
     * @param  integer $parent_id 父部门ID
     * 
     * @return string 生成的用户下拉框代码
     *
     * @author Strief
     */
    public static function getUserByDeptAndParent($dept_id, $parent_id,$lead_user_id=0)
    {
        $infoArr = [];
        $deptParentArr = Department::find()
                ->select('parent_ids')
                ->where(['status' => 1, 'dept_id' => $parent_id])
                ->asArray()
                ->one();
        if(empty($deptParentArr)){
            $deptParentArr = [];
        }

        $deptParents = implode(',', $deptParentArr);
        $deptParents = explode(',', $deptParents);
        $deptParents = array_merge($deptParents, ["$dept_id", "$parent_id"]);
        $deptParents = array_unique($deptParents);

        $infoArr = static::find()
                ->select('user_id')
                ->where(['in', 'dept_id', $deptParents])
                ->asArray()
                ->all();

        if($infoArr != []){
            $str = '';
            $info = [];
            foreach ($infoArr as $key => $value) {
                $info[] = $value['user_id'];
            }
            $info = array_unique($info);
            foreach ($info as $key => $value) {
                $user = User::findById($value);
                $selected=FALSE;
                if(!empty($user)){
                    if($value==$lead_user_id){
                        $selected='selected';
                    }
                    echo $lead_user_id;
                    $str .= "<option value='" . $value . "'{$selected}>" . $user['realname'] . "[" . $user['username'] . "]" . "</option>";
                }
            }
            return $str;
        } else {
            return '';
        }
    }

    /**
     * 获取某一部门下所有的用户
     * @param  integer $dept_id 部门ID
     * @return string 生成的用户下拉框代码
     *
     * @author Strief
     */
    public static function getUserByDept($dept_id)
    {
        $list = static::find()
                ->select('user_id')
                ->where(['dept_id' => $dept_id])
                ->asArray()
                ->all();
        if($list != []){
            $str = '';
            foreach ($list as $key => $value) {
                //$isSelect = $v['scope_id'] == $cur ? "selected='selected'" : '';
                $user = User::findById($value['user_id']);
                if(isset($user)){
                    $str .= "<option value='" . $value['user_id'] . "'>" . $user['realname'] . "</option>";
                }
            }
            return $str;
        } else {
            return '';
        }
    }

    /**
     * 获取部门部门下所有用户
     *
     * @param type $where      获取部门的限制条件
     * @param type $userId   用户ID
     *
     * @author HuLimin <http://blog.u-bo.com>
     * @since 0.1
     */
    public static function getDepartmentByUser($where = [], $scopeUser = [0])
    {
        $deptIds = static::find()
                ->where($where)
                ->select('dept_id')
                ->column();
        $deptIds = explode(',', implode(',', $deptIds));
        if(empty($deptIds)){
            return FALSE;
        }
        $deptListUser = [];
        //获取部门以及其下属用户
        $deptList = User::getDepartmentAndUser([['in', 'dept_id', $deptIds]]);

        foreach ($deptList as &$dept) {

//            $dept['user_ids'] = implode(',', \yii\helpers\ArrayHelper::getColumn($dept['user'], 'user_id'));
            // if ($dept['dept_id'] == $dept['child_ids']) {
            foreach ($dept['user'] as $user) {
                if(in_array($user['user_id'], $scopeUser) || empty($scopeUser)){
                    if($dept['lead_user_id'] == $user['user_id']){
                        $realname = $user['realname'] . "★";
                    } else {
                        $realname = $user['realname'];
                    }
                    $deptListUser[] = [
                        'dept_id' => 'user_' . $user['user_id'],
                        'parent_id' => $dept['dept_id'],
                        'name' => $realname,
                        'child_ids' => 0,
                        'user_ids' => $user['user_id']
                    ];
                }
            }
            // }
            unset($dept['user']);
        }
        $deptList = \yii\helpers\ArrayHelper::merge($deptListUser, $deptList);
//        $cache->set($cache_key . '_user_department_' . $user_id, $deptList);
        return $deptList;
    }

    /**
     * 获取部门以及用户
     *
     * @param type $permission 权限节点
     * @author HuLimin <http://blog.u-bo.com>
     * @since 0.1
     */
    public static function obtainDepartmentTree($permission = '')
    {
        $session = Yii::$app->session;
        if(empty($permission)){
            return;
        }
        $listDeptsTree = $session->get($permission);
        if(empty($listDeptsTree)){
            $scopeUser = \common\models\PermissionScope::getScopeUser($permission);
            //没有权限
            if($scopeUser === FALSE){
                return;
            }
            if(empty($scopeUser)){//超级管理员
                $map = [];
            } else {
                $map = ['in', 'user_id', $scopeUser];
            }
            $listDeptsTree = static::getDepartmentByUser($map, $scopeUser);
            foreach ($listDeptsTree as &$dept) {
                if($dept['child_ids'] != $dept['dept_id']){
                    $dept['isParent'] = true;
                    $dept['open'] = FALSE;
                }
            }
            $session->set($permission, $listDeptsTree);
        }
        return $listDeptsTree;
    }

    /**
     * 根据用户获取上级领导，用于报销审核获取审核人
     * 
     * @param  integer $user_id 用户ID
     * @return integer $leader_id 部门领导ID
     */
    public static function getDeptLeaderByUser($user_id, $checkAccess = '', $pk = 'lead_user_id')
    {
        //初始领导人为admin
        $leader_id = 1;
        $dept_id = 0;

        $depts = Department::find()->indexBy('dept_id')->asArray()->all();
        /* $dept = static::findOne(['user_id' => $user_id]);

          //若当前用户不属于任何部门，则审核人为admin
          if (!empty($dept) && isset($depts[$dept->dept_id])) {
          //若当前用户属于多个部门，则暂时先将审核人设为admin
          $count = static::find()->where(['user_id' => $user_id])->count();
          if ($count == 1) {
          //当前用户只属于一个部门，则获取该部门的领导人
          $leader_id = $depts[$dept->dept_id]['lead_user_id'];
          }
          } */

        $count = static::find()->where(['user_id' => $user_id])->count();

        //若当前用户不属于任何部门，则审核人为admin
        if($count == 0){
            return 1;
        }

        //若当前用户属于一个人部门，则获取该部门的领导人
        if($count == 1){
            $dept = static::findOne(['user_id' => $user_id]);
            $leader_id = $depts[$dept->dept_id][$pk];
            $dept_id = $dept->dept_id;
        }

        //若当前用户属于多个部门，则获取最顶级的部门
        if($count > 1){
            $deptArr = static::find('dept_id')->where(['user_id' => $user_id])->asArray()->all();

            //获取当前用户属于的全部部门
            foreach ($deptArr as $key => $value) {
                $deptArr[$key] = $value['dept_id'];
            }

            //逐个判断每一个部门，当找到符合最顶级部门时停止循环
            foreach ($deptArr as $key => $value) {
                //当前部门的父部门集合
                $pId = explode(',', $depts[$value]['parent_ids']);

                //是否为顶级部门，默认为是
                $isParent = true;

                foreach ($deptArr as $key1 => $value1) {
                    //若其他部门有一个是在该部门的父部门里，则该部门不符，停止循环
                    if(in_array($value1, $pId)){
                        $isParent = false;
                        break;
                    }
                }

                if($isParent){
                    //判断当前部门是否符合，若符合则停止循环
                    $leader_id = $depts[$value][$pk];
                    $dept_id = $value;
                    break;
                }
            }
        }

        //判断部门领导人是否不存在或就是当前用户
        if($leader_id == 0 || $leader_id == $user_id || !Auth::checkAccessById($checkAccess, $leader_id)){
            //将当前用户所在部门的所有父部门转换成数组
            $arrParentIds = explode(',', $depts[$dept_id]['parent_ids']);

            //去除部门ID为0的数组元素
            unset($arrParentIds[0]);

            //反转数组
            $arrParentIds = array_reverse($arrParentIds);

            //循环遍历查询父部门的领导人，若领导人存在且不是当前用户，则获取值并中断循环
            foreach ($arrParentIds as $key => $value) {
                if($depts[$value][$pk] != 0 && $depts[$value][$pk] != $user_id && Auth::checkAccessById($checkAccess, $leader_id)){
                    $leader_id = $depts[$value][$pk];
                    break;
                }
            }

            //循环遍历后检查领导人
            if($leader_id == 0 || $leader_id == $user_id || !Auth::checkAccessById($checkAccess, $leader_id)){
                $leader_id = 1;
            }
        }

        return $leader_id;
    }

}
