<?php
namespace app\admin\controller;

use app\admin\model\DepartmentModel;
use app\admin\model\RoleModel;
use app\admin\model\StaffIdentity;
use app\admin\model\StaffModel;
use app\admin\model\StaffPropertyModel;
use app\admin\model\StaffRoleModel;
use app\admin\validate\StaffValidate;
use app\admin\model\ElectricMeter;
use app\admin\model\PermissionDataModel;
use think\facade\Session;
use think\Request;
use think\db;

/**
 * 员工控制器
 * 负责员工的增删改查
 * 员工密码的初始化
 * Class Staff
 * @package app\admin\controller
 */
class Staff extends Base
{
    public function index(Request $request)
    {
                $map=[];
                $search_text = $request->get('search_text');
                $search_type = $request->get('search_type'); 
                if($search_text){
                switch ($search_type) {
                    case '1':
                  $this->assign('search_text',$search_text);
                    $map[]=['staff.name','like',"%$search_text%"];
                  $this->assign('search_type',$search_type);
                        break;
                    case '2':
                  $this->assign('search_text',$search_text);
                    $map[]=['email','like',"%$search_text%"];
                  $this->assign('search_type',$search_type);
                        break;
        
                   case '3':
                  $this->assign('search_text',$search_text);
                   $map[]=['tel','like',"%$search_text%"];
                  $this->assign('search_type',$search_type);
                        break;
                    }
               }else{
                  $this->assign('search_type','');
                  $this->assign('search_text','');
               }
                $page = $request->get('page')?$request->get('page'):1;

                $limit = $request->get('limit')?$request->get('limit'):10;
                if(empty($request->get('page'))){
                   $page_s=0;
                }else{
                    $page_s=(($page-1)*$limit);
                }
              
                $statff= new StaffModel;
                $statfflist= $statff->selectStaffList($map,$page,$limit);
                $statffcount= $statff->selectStaffCount($map);
                if($request->get('page')){
                return ['code'=>0,'msg'=>'','count'=>$statffcount,'data'=>$statfflist];
                }
        return $this->fetch('index');
    }

    public function create()
    {
        $data = (new DepartmentModel)->getDepartmentTree();
        $idens = StaffIdentity::field('id,title,level')->select();
        $this->assign('idens',$idens);
        $this->assign('data',$data);
        return $this->fetch('add');
    }

    public function edit($id){
        $staff = StaffModel::find($id);
        $model =  new DepartmentModel;
        $data = $model->getDepartmentTree();
        $idens = StaffIdentity::field('id,title,level')->select();
        $this->assign('idens',$idens);
        $this->assign('data',$data);
        $this->assign('staff',$staff);
        return $this->fetch('edit');
    }

    public function store(Request $request){

        $validate = new StaffValidate;

        if(!$validate->check($request->post())){
            return jsonErr($validate->getError());
        }

        $staff = new StaffModel;
        $staff->name = $request->post('name');
        $staff->email = $request->post('email');
        $staff->d_id = $request->post('d_id');
        $staff->tel = $request->post('tel') + 0;
        $staff->iden_id = $request->post('iden_id');
        $staff->status = $request->post('status');

        if($staff->save()){
            return jsonSuc('添加员工成功');
        } else {
            return jsonErr('添加员工失败');
        }
    }

    public function update(Request $request){
        $id = $request->post('id') + 0;

        $staff = StaffModel::find($id);

        if($staff){
            $staff->name = $request->post('name') ?: $staff->name;
            $staff->email = $request->post('email') ?: $staff->email;
            $staff->d_id = $request->post('d_id') ?: $staff->d_id;
            $staff->tel = $request->post('tel') ?: $staff->tel;
            $staff->iden_id = $request->post('iden_id') ?: $staff->iden_id;
            $staff->status = $request->post('status') ?: $staff->status;

            //查询 邮箱是否唯一

            $staffCheck = StaffModel::
                where([
                    ['email','=',$request->post('email')],
                    ['id','neq',$id]
                ])->find();
            if(!$staffCheck){
                if($staff->save()){
                    return jsonSuc('修改员工信息成功');
                } else {
                    return jsonErr('修改员工信息失败');
                }
            }
            return jsonErr('email已存在');

        }
        return jsonErr('参数错误');

    }

    public function delete(Request $request){
        $id =  $request->post('id');

        if(is_int($id + 0) && ($id + 0) > 0) {
            $staff =StaffModel::get($id);

            if(!$staff){
                return jsonErr('删除失败，用户不存在');
            }

            //如果删除成功
            if($staff->delete()){
                //删除权限
                return $this->role_del($staff);
            } else {
                return jsonErr('删除失败请重试');
            }
        } else {
            return jsonErr('参数错误');
        }
    }
     //状态修改
     public function status(Request $request){
         $id = $request->post('id');
         $staff= new StaffModel;
         $status=$staff->getStaffStatusById($id);
         if($status['status']==1){
          $status= $staff->setStaffStatus($id,0);
          return jsonSuc('状态禁用成功');
         }else{
          $status= $staff->setStaffStatus($id,1);
          return jsonSuc('状态开启成功');
         }
     }
          //数据导入
     public function basestation_import(Request $request){
        $file = $request->file('file_name');
        $upload = new Upload($file,2);
        $result = $upload->upload();
        $fileurl=$_SERVER['DOCUMENT_ROOT'].$result['src'];
        $excel = new Excel;
        $excelresult=$excel->basestation_importExecl($fileurl);
        if($excelresult['code']==200){
        return jsonSuc('导入成功!  总导入条数为 '.$excelresult['data']['total'].' 条'.'  成功导入条数为  '.$excelresult['data']['suc']. '  条'.'   失败'.$excelresult['data']['er']. '条');
        }else{
        return jsonErr('导入数据错误');
        }
     }
    //配置员工所属角色匹配角色所属权限
    public function role(){
        $data = StaffModel::with('roles')->select();
        $this->assign('data',$data);
        $this->assign('empty','<span class="layui-bg-orange">[没有权限]</span>');
        return $this->fetch('role');
    }

    public function role_edit($id){
        $data = StaffModel::with('roles')->field('id,name')->find($id)->toArray();
        $roles = RoleModel::field('id,title')->select()->toArray();

        //筛选匹配的键
        foreach ($roles as $key => $role){
            foreach ($data['roles'] as  $drole){
                if($drole['id'] == $role['id']){
                    $roles[$key]['checked'] = true;
                }
            }
            if(!isset($roles[$key]['checked'])){
                $roles[$key]['checked'] = false;
            }
        }
        $this->assign('roles',$roles);
        $this->assign('data',$data);
        return  $this->fetch('role_edit');
    }
       public function staff_role_department($id){
        $role = StaffModel::get($id)->toArray();
        $permissionOwn = PermissionDataModel::where(['s_id'=>$id])->find();
        $nodes = (new DepartmentModel)->getNodesTree();
        $permissions = $permissionOwn['permission_ids'];
            if($permissions){
                $jsonpermissions=json_decode($permissions);
                $permissions = explode(',',$jsonpermissions->department_id);
                $repermissions = explode(',',$jsonpermissions->region_id);
                $buspermissions = explode(',',$jsonpermissions->business_id);
                $this->assign('buspermissions',$buspermissions);
                $this->assign('repermissions',$repermissions);
                $this->assign('permissions',$permissions);
            }else{
                 $this->assign('buspermissions',[]);
                 $this->assign('repermissions',[]);
                 $this->assign('permissions',[]);
            }
        $regionnodes = getNodesTree((new ElectricMeter)->regions());
        $businessnodes= (new ElectricMeter)->business();
        $this->assign('data',$role);
        $this->assign('nodes',$nodes);
        $this->assign('regionnodes',$regionnodes);
        $this->assign('businessnodes',$businessnodes);
      
 
        return  $this->fetch('staff_role_department');
    }
     public function depat_role_update(Request $request){
        $id = $request->post('id');
         //区域
         $repermission=$request->post('repermission');
         //业务线
         $buspermission=$request->post('buspermission');
         //部门
         $result = $this->addDepartPermission($id,$request->post('permission'),$repermission,$buspermission);
      
            if($result){
                return jsonSuc('基站数据权限设置成功');
            } else {
                return jsonErr('基站数据权限设置失败');
            }
        }
       private function addDepartPermission($id, $permission = [],$repermissions = [],$buspermissions = []) {
        $DepartPermission = new PermissionDataModel;
        $model =  $DepartPermission->where(['s_id'=>$id])->find();
        if($permission){

           $permissions = implode(',',$permission); 
           $convert['department_id']=$permissions; 
        }else{
           $convert['department_id']='';
        }
        if($repermissions){
            $repermissions = implode(',',$repermissions);  
            $convert['region_id']=$repermissions;
        }else{
            $convert['region_id']='';
        }
       
        if($buspermissions){
            $buspermissions = implode(',',$buspermissions);  
            $convert['business_id']=$buspermissions;
        }else{
            $convert['business_id']='';
        }
        
        if($model){
            $model->permission_ids = json_encode($convert);
            return $model->save();
        } else {
            $DepartPermission->s_id = $id;
            $DepartPermission->permission_ids = json_encode($convert);
            return $DepartPermission->save();
        }
    }
    /**
     * 添加用户权限
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     *
     */
    public function role_update(Request $request){

        $id = $request->post('id');
        $roles = $request->post('role');

        if(!$id){
            return jsonErr('参数有错误刷新之后添加');
        }

        $staffRole = StaffRoleModel::where(['staff_id'=>$id])->find();

        //如果没有记录，则更新
        if($staffRole) {
            //先清除所有权限
            StaffRoleModel::where(['staff_id' => $id])->delete();
        }

        //生成权限数据
        $staffRoleList = [];
        foreach ($roles as $key => $role){
            $staffRoleList[$key]['staff_id'] = $id;
            $staffRoleList[$key]['role_id'] = $role;
        }

        //批量插入权限
        if((new StaffRoleModel)->saveAll($staffRoleList)){
            return jsonSuc('添加权限成功');
        } else {
            return jsonErr('添加权限失败');
        }
    }


    public function role_del($staff=''){

        if(!empty($staff)){
            $id = $staff->id;
        } else {
            $id =  Request::post('id');
        }

        if(is_int($id + 0) && ($id + 0) > 0){
            if(StaffRoleModel::where(['staff_id' => $id])->delete()){
                return jsonSuc('删除权限成功');
            } else {
                return jsonErr('删除失败，用户没有设置权限');
            }
        } else {
            return jsonErr('参数错误');
        }
    }


    /**
     * 重置密码
     * @param Request $request
     * @return \think\response\Json
     */
    public function resetPass(Request $request){
        $id = $request->post('id') + 0;

        $staff = StaffModel::get(['id'=>$id]);
        $staffProperty = StaffPropertyModel::where(['staff_id'=>$id])->find();

        $pass = createPass();
        if($staffProperty){ //之前有密码
            $staffProperty->passwd = md5($pass.config('admin.passwd_salt'));
        } else { //新用户创建
            $staffProperty =  new StaffPropertyModel;
            $staffProperty->passwd = md5($pass.config('admin.passwd_salt'));
            $staffProperty->staff_id = $id;
        }

        $message =
            [
                'username' => $staff->email,
                'pass' => $pass
            ];
        if($staffProperty->save()){
            return jsonSuc('密码重置成功', $message);
        } else {
            return jsonErr('重置密码失败，请重试');
        }

    }

    public function getIdentity($uid= ''){
        if(empty($uid)){
            $user = $this->getCurrentUser();
            if($this->isAdmin()){
                return 'admin';
            }
            return $user->iden_id;
        }
    }

    public function getCurrentUser(){
        $user = Session::get('user');
        return StaffModel::get($user['user_id']);
    }

    public function isAdmin(){
        $user = Session::get('user');
        return $user['is_admin'];
    }
}