<?php
namespace app\admin\model;

use think\facade\Session;

class StaffModel extends BaseModel
{
    protected $table = 'staff';

    public function department(){
        return $this->belongsTo('DepartmentModel','d_id','id');
    }

    public function identity(){
        return $this->belongsTo('StaffIdentity','iden_id','id');
    }

    public function roles(){
        return $this->belongsToMany('RoleModel','staff_role','role_id','staff_id');
    }

    public function passwd(){
        return $this->hasOne('StaffPropertyModel','staff_id','id');
    }

    public static function getStaffsByDepartment($id){
        $staff = self::find($id);
        $staffs = self::field('id,name')->where(['d_id'=>$staff->d_id])->select();
        return $staffs;
    }

    public static function getCurrentStaffsByDepartment(){
        $user = Session::get('user');
        $staff = self::find($user['user_id']);
        $Dids = (new DepartmentModel())->getNodeIds($staff->d_id);

        $map[] = ['d_id','in',$Dids];
        $staffs = self::field('id,name')->where($map)->select();

        //找到当前用户ID
        //找到用户所在部门
        //找到用户所在部门的下属部门ID
        //通过in查询来获取所有员工


        return $staffs;
    }

    public static function getStaffsDepartmentCurrent(){
        $user = Session::get('user');
        return self::getStaffsByDepartment($user['user_id']);
    }

    public static function getStaffNameById($id){
        if($id == 0 || empty($id)){
            return '未填写';
        }
        $staff = self::field('name as sName')->find($id);
        if($staff){
            return $staff->sName;
        }
        return  '';
    }

    public  function getStaffStatusById($id){
        $staffs = $this->field('status')->where(['id'=>$id])->find()->toArray();
        return $staffs;
    }
     public  function getStaffStatusByName($email){
        $staffs = $this->field('status')->where(['email'=>$email])->find()->toArray();
        return $staffs;
    }
    public  function setStaffStatus($id,$status){
        $staffs = $this->allowField(true)->save(['status'=>$status],['id' => $id]);
        return $staffs;
    }
    public function selectStaffList($map,$Nowpage,$limits){
         $staffs = $this->field('staff.id,staff.name,tel,staff.status,staff.email,
            case when  d.name is null  then "广厦网络" else d.name end as  department_name')->leftjoin(['department'=> 'd'],'d.id=staff.d_id')->where($map)->page($Nowpage, $limits)->select()->toarray();
         return $staffs;
    }
      public function selectStaffCount($map){
         $staffs = $this->where($map)->count();
         return $staffs;
    }
}