<?php

namespace catchAdmin\permissions\model;

use catchAdmin\permissions\model\search\DepartmentSearch;
use catcher\base\CatchModel;
use think\db\exception\DbException;
use catcher\Utils;

use catchAdmin\permissions\model\DataRangScopeTrait;
use catchAdmin\system\model\SysDictData;
use catchAdmin\system\model\SysDictType;
use PhpParser\Node\Stmt\Return_;
use think\facade\Db;

class Department extends CatchModel
{
    use DepartmentSearch;
    use DataRangScopeTrait;

    protected $name = 'departments';

    protected $field = [
        'id', // 
        'department_name', // 部门名称
        'parent_id', // 父级ID
        'principal', // 负责人
        'mobile', // 联系电话
        'email', // 联系又想
        'creator_id', // 创建人ID
        'status', // 1 正常 2 停用
        'level',//级别
        'sort', // 排序字段
        'created_at', // 创建时间
        'updated_at', // 更新时间
        'deleted_at', // 删除状态,null 未删除 timestamp 已删除
    ];

    /**
     * 列表数据
     *
     * @time 2020年01月09日
     * @return array
     * @throws DbException
     */
    public function getList(): array
    {

        $where = array();
        if (!Utils::isSuperAdmin()) {
            $user = request()->user();
            // $departmentIds = Department::where('parent_id', $user->department_id)->column('id');
            // $departmentIds[] = $user->department_id;
            // 如果不是超级管理员,获取子部门及上级直至顶级部门
            $parentiIds = $this->getParentDepartmentIds($user->department_id);
            $childIds = $this->getChildrenDepartmentIds($user->department_id);
            $departmentIds = array_merge($parentiIds, $childIds);
            $where[] = ['id', 'in', $departmentIds];
        }
        return $this->where($where)
            ->catchSearch()
            ->catchOrder()
            ->select()->toTree();
    }

    
       /**
     * 有学校的列表数据
     *
     * @time 2020年01月09日
     * @return array
     * @throws DbException
     */
    public function getListHasSchool(): array
    {
        $where = array();
        $user = request()->user();
        //获取学校类型
        $type_id = SysDictType::where('code','DepartmentType')->value('id');
        $school_type = SysDictData::where(['remark'=>'school','type_id'=>$type_id])->column('code');
        $grade_type = SysDictData::where(['remark'=>'grade','type_id'=>$type_id])->column('code');
        $class_type = SysDictData::where(['remark'=>'class','type_id'=>$type_id])->column('code');
        if ($user->department_id) {
            $parentiIds = $this->getParentDepartmentIds($user->department_id);
            $childIds = $this->getChildrenDepartmentIds($user->department_id);
            $departmentIds = array_merge($parentiIds, $childIds);
            $where[] = ['id', 'in', $departmentIds];
        } else {
            $parentiIds = $this->whereIn('department_type', $school_type)->column('parent_id');
            $parentiIds = array_unique($parentiIds);
            $schDepartIds = $this->whereIn('department_type', $school_type)->column('id');
            $gradeIds = $this->whereIn('parent_id', $schDepartIds)->whereIn('department_type',$grade_type)->column('id');
            $classIds = $this->whereIn('parent_id', $gradeIds)->whereIn('department_type',$class_type)->column('id');
            $departmentIds = array_merge($parentiIds, $schDepartIds,$gradeIds,$classIds);
            $where[] = ['id', 'in', $departmentIds];
        }
       

        $departs =  $this->where($where)
            ->catchSearch()
            ->append(['department_type_text'])
            ->catchOrder()
            ->select()->toTree();
        return $departs;
    }

    /**
     * 只获取学校数据
     *
     * @time 2020年01月09日
     * @return array
     * @throws DbException
     */
    public function getOnlySchoolData()
    {
        //获取学校类型
        $type_id = SysDictType::where('code','DepartmentType')->value('id');
        $school_type = SysDictData::where(['remark'=>'school','type_id'=>$type_id])->column('code');
        $res = $this->dataRange()
                    ->catchSearch()
                    ->where('status', 1)
                    ->whereIn('department_type', $school_type)
                    ->append(['department_type_text'])
                    ->catchOrder()
                    ->select();

        if ($res->isEmpty()) {
            // 如果学校角色不通过 creator_id 过滤,通过 department_id 过滤,否则无法获取到上级添加的学校
            $school_role_ids = Roles::getSchoolRoleids();
            $count = Db::table('user_has_roles')->where('uid', request()->user()->id)
                        ->whereIn('role_id', $school_role_ids)
                        ->count();
            if ($count) {
                $res2 = $this->where('id', request()->user()->department_id)->where('status', 1)->select();
                $res = $res->merge($res2);
            }
        }
        return $res;
    }

    /**
     * 只获取学校下拉
     *
     * @time 2020年01月09日
     * @return array
     * @throws DbException
     */
    public function getOnlySchoolOption()
    {
        //获取学校类型
        $type_id = SysDictType::where('code','DepartmentType')->value('id');
        $school_type = SysDictData::where(['remark'=>'school','type_id'=>$type_id])->column('code');
        
        $res = $this->dataRange()
                    ->catchSearch()
                    ->whereIn('department_type', $school_type)
                    ->field('id as value,department_name as text')
                    ->catchOrder()
                    ->select();
        if ($res->isEmpty()) {
            // 如果学校角色不通过 creator_id 过滤,通过 department_id 过滤,否则无法获取到上级添加的学校
            $school_role_ids = Roles::getSchoolRoleids();
            $count = Db::table('user_has_roles')->where('uid', request()->user()->id)
                        ->whereIn('role_id', $school_role_ids)
                        ->count();
            if ($count) {
                $res2 = $this->where('id', request()->user()->department_id)->where('status', 1)->field('id as value,department_name as text')->select();
                $res = $res->merge($res2);
            }
        }
        return $res;
    }
    
    /**
     * 学校列表数据
     *
     * @time 2020年01月09日
     * @return array
     * @throws DbException
     */
    public function getSchoolList(): array
    {

        $where = array();
        $user = request()->user();
        //获取学校类型
        $type_id = SysDictType::where('code','DepartmentType')->value('id');
        $school_type = SysDictData::where(['remark'=>'school','type_id'=>$type_id])->column('code');
        if ($user->department_id) {
            $parentiIds = $this->getParentDepartmentIds($user->department_id);
        } else {
            $parentiIds = $this->whereIn('department_type', $school_type)->column('parent_id');
            $parentiIds = array_unique($parentiIds);
        }
        $childIds = $this->whereIn('department_type', $school_type)->column('id');
        $departmentIds = array_merge($parentiIds, $childIds);
        $where[] = ['id', 'in', $departmentIds];

        $departs =  $this->where($where)
            ->catchSearch()
            ->append(['department_type_text'])
            ->catchOrder()
            ->select()->toTree();
        return $departs;
    }

    /**
     * 运营商列表数据
     *
     * @time 2020年01月09日
     * @return array
     * @throws DbException
     */
    public function getYysDepartList(): array
    {

        $where = array();
        $user = request()->user();
        //获取学校类型
        $type_id = SysDictType::where('code','DepartmentType')->value('id');
        $yys_type = SysDictData::where(['remark'=>'yys','type_id'=>$type_id])->column('code');
        if ($user->department_id) {
            $parentiIds = $this->getParentDepartmentIds($user->department_id);
            $childIds= $this->getChildrenDepartmentIdsByType([$user->department_id],$yys_type);
            $childIds[]=$user->department_id;//加入自身
            $departmentIds = array_merge($parentiIds, $childIds);
        } else {
            $parentiIds = $this->whereIn('department_type', $yys_type)->column('parent_id');
            $parentiIds = array_unique($parentiIds);
            $childIds = $this->whereIn('department_type', $yys_type)->column('id');
            $departmentIds = array_merge($parentiIds, $childIds);
        }
        
        $where[] = ['id', 'in', $departmentIds];

        $departs =  $this->where($where)
            ->catchSearch()
            ->append(['department_type_text'])
            ->catchOrder()
            ->select()->toTree();
        return $departs;
    }
    
    /**
     * 班级列表数据
     *
     * @time 2020年01月09日
     * @return array
     * @throws DbException
     */
    public function getClassList($pid): array
    {
        //获取年级班级类型
        $type_id = SysDictType::where('code','DepartmentType')->value('id');
        $grade_type = SysDictData::where(['remark'=>'grade','type_id'=>$type_id])->column('code');
        $class_type = SysDictData::where(['remark'=>'class','type_id'=>$type_id])->column('code');
        //该学校下所有年级
        $gid = $this->where(['parent_id' => $pid])->whereIn('department_type', $grade_type)->column('id');
        $cid = $this->where('parent_id', 'in', $gid)->whereIn('department_type', $class_type)->column('id');
        $departmentIds = array_merge($gid, $cid);
        $where[] = ['id', 'in', $departmentIds];
        $departs =  $this->where($where)
            ->select()->toTree($pid);
        // var_dump($this->getLastSql(),$departs);
        return $departs;
    }
    /**
     * 获取子部门IDS
     *
     * @time 2020年11月04日
     * @param $id
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @return mixed
     */
    public static function getChildrenDepartmentIds($id)
    {
        $departmentIds = Department::field(['id', 'parent_id'])->select()->getAllChildrenIds([$id]);

        $departmentIds[] = $id;

        return $departmentIds;
    }
     /**
     * 获取运营商子部门IDS
     *
     * @time 2020年11月04日
     * @param $id
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @return mixed
     */
    public function getChildrenDepartmentIdsByType($ids,$type)
    {

        $childDepartmentIds = Department::whereIn('parent_id',$ids)->whereIn('department_type',$type)->column('id');
        
        if (!empty($childDepartmentIds)) {
            $childIds= $this->getChildrenDepartmentIdsByType($childDepartmentIds,$type);
            $childDepartmentIds = array_merge($childDepartmentIds, $childIds);
        }
        return $childDepartmentIds;
    }

    /**
     * 获取部门名称
     */
    public static function getDepartmentName($id)
    {
        $department_name = Department::where('id', $id)->value('department_name');

        return $department_name;
    }

    /**
     * 获取上级至顶级部门ids
     */
    public function getParentDepartmentIds($id)
    {
        $ids = [];
        $pid = Department::where('id', $id)->value('parent_id');

        if ($pid > 0) {
            $ids[] = $pid;
            $parentId = $this->getParentDepartmentIds($pid);
            $ids = array_merge($ids, $parentId);
        }
        return $ids;
    }
    /**
     * 获取上级至顶级部门ids
     */
    public function getSchoolParentDepartmentIds($id)
    {
        $ids = [];
        $pid = Department::where('id', $id)->value('parent_id');
        if ($pid > 0) {
            $ids[] = $pid;

            $parentId = $this->getSchoolParentDepartmentIds($pid);
            if (Department::where('id', $pid)->value('parent_id')) {
            }
            $ids = array_merge($ids, $parentId);
        }
        return $ids;
    }
}