<?php
    namespace Admin\Controller;
    use Think\Controller;
    use Think\Model;
    class RbacController extends CommonController {
        //岗位列表
        public function Role(){
            $is_rbac = _rbac_btn_show(18,0);
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            $sousuo=I('rolefl');
            $condition="where gongsiid = 10000";
            if ($sousuo == '全部') {//搜索
                $condition.="";
            }elseif($sousuo){
                $condition.=" and rolefl = $sousuo";
            }
            $Model = new \Think\Model();
            $count=$Model->query("select count(*) from __ROLE__ {$condition}");
            $Page=new \Think\Page($count['0']['count(*)'],30);
            $show=$Page->show();
            $list="select * from __ROLE__ {$condition} order by rolefl asc,xsshunxu asc limit ".$Page->firstRow.','.$Page->listRows;
            $Role=M('role')->query($list);
            $this->assign('firstRow',$Page->firstRow);
            $this->assign('role',$Role);
            $this->assign('count',$count);
            $this->assign('page',$show);
            $this->rolefl=M('Peizhi')->where(array('pzming'=>'rolefl','zhuangtai'=>1))->order('xsshunxu asc')->select();
            $this->display();
        }
    	//用户列表  node_id=17
        public function index(){
            $map = "gongsiid=".session('gongsiid');
            $status=I('status');
            $sousuo=I('sousuo');
            $x = _rbac_lists_where(17,0);
            if ($x && $x != "all" && $x != "me") {
                $map .= " and bumen in ({$x})";
            }elseif ($x == "me") {
                $map .= " and id=".session('uid');
            }elseif ($x == false) {
                $map .= " and id=0";
            }
            $tree = new \Org\Util\Tree();
            $bumen = I("get.bumen",0,'intval');
            $result = M('bumen')->order(array("sort" => "ASC"))->select();
            if ($status==1) {
                $map .= " and status=1";
            }else {
                $map .= " and status=0";
            }
            if ($sousuo) {
                $map.=" and (dianhua like '%$sousuo%' or pinyinjs like '%$sousuo%' or ygmingcheng like '%$sousuo%' or ygbianhao like '%$sousuo%')";
            }
            if ($bumen) {
                $arr_string = _rbac_bumen_array($result,$bumen);
                $arr_string[] = $bumen;
                $string = implode(',',$arr_string);
                $map .= " and bumen in ($string)";
            }
            $count=D('UserRelation')->where($map)->count();
            $Page=new \Think\Page($count,30);
            $show=$Page->show();
            $Yonghu=D('UserRelation')->where($map)->limit($Page->firstRow.','.$Page->listRows)->field('mima',true)->relation('role')->order('id asc')->select();
            $this->assign('firstRow',$Page->firstRow);
            $this->assign('user',$Yonghu);
            $this->assign('count',$count);
            $this->assign('page',$show);
            $select_categorys = bumen_option( $bumen, 17);
            $this->assign("select_categorys", $select_categorys);
            $this->display();
        }
        public function stopUser(){
            $is_rbac = _rbac_btn_show(190,0,I('id',0,'intval'));
            if (!$is_rbac) {
                $this->error('异常错误！');
            }
            $id=I('id');
            $yh=M('yonghu')->where(array('id'=>$id))->find();
            $xiugai.="停用员工[".$yh['ygmingcheng']."]";
            if(M('yonghu')->where(array('id'=>$id))->setField('lock1',1)){
                $data_rizhi['zy_type']=8;
                $data_rizhi['uid']=session("uid");
                $data_rizhi['addtime']=time();
                $data_rizhi['cz_type']=21;
                $data_rizhi['zy_id']=I('id');
                $data_rizhi['neirong']=$xiugai;
                M('rizhi')->add($data_rizhi);
                $this->success('已停用');
            }else{
                $this->error('停用失败');
            }
        }
        public function startUser(){
            $is_rbac = _rbac_btn_show(192,0,I('id',0,'intval'));
            if (!$is_rbac) {
                $this->error('异常错误！');
            }
            $id=I('id');
            $yh=M('yonghu')->where(array('id'=>$id))->find();
            $xiugai.="启用员工[".$yh['ygmingcheng']."]";
            if(M('yonghu')->where(array('id'=>$id))->setField('lock1',0)){
                $data_rizhi['zy_type']=8;
                $data_rizhi['uid']=session("uid");
                $data_rizhi['addtime']=time();
                $data_rizhi['cz_type']=22;
                $data_rizhi['zy_id']=I('id');
                $data_rizhi['neirong']=$xiugai;
                M('rizhi')->add($data_rizhi);
                $this->success('已启用');
            }else{
                $this->error('启用失败');
            }
        }
        //节点列表
        public function Node(){
            $is_rbac = _rbac_btn_show(98,0);
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            $field=array('id','name','title','pid','level');
            $this->count=M('node')->count();
            $result=M('node')->field($field)->order('sort')->select();
            $tree = new \Org\Util\Tree();
            $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $newmenus=array();
            foreach ($result as $m){
                $newmenus[$m['id']]=$m;
            }
            foreach ($result as $n=> $r) {
                $result[$n]['parentid'] = $r['pid'];
            }
            foreach ($result as $n=> $r) {
                $result[$n]['parentid_node'] = ($r['parentid']) ? ' class="child-of-node-' . $r['parentid'] . '"' : '';
                $result[$n]['style'] = empty($r['parentid']) ? '' : 'display:none;';
                if ($r['level']!=3) {
                    $level = $r['level']+1;
                    $result[$n]['str_manage'] = '<if condition="_rbac_btn_show(109,0)"><a class="layui-btn layui-btn-normal layui-btn-mini" title="添加方法" href="javascript:;" onclick="layer_show(\'添加方法\',\''.U('Rbac/addNode',array('pid'=>$r['id'],'level'=>$level)).'\',\'600\',\'400\')" style="text-decoration:none"><i class="Hui-iconfont">&#xe604;</i> 添加</a></if>';
                }
                $result[$n]['str_manage'] .='<if condition="_rbac_btn_show(110,0)"><a class="ml-5 layui-btn layui-btn-warm layui-btn-mini" title="编辑" href="javascript:;" onclick="layer_show(\'控制器编辑\',\''.U('Rbac/editNode',array('id'=>$r['id'])).'\',\'600\',\'400\')" style="text-decoration:none"><i class="Hui-iconfont">&#xe6df;</i> 编辑</a></if><if condition="_rbac_btn_show(112,0)"><a class="ml-5 layui-btn layui-btn-mini" title="删除" href="javascript:;" onclick="admin_node_del(this,\''.$r['id'].'\')" style="text-decoration:none;background: red;"><i class="Hui-iconfont">&#xe6e2;</i> 删除</a></if>';
            }
            $tree->init($result);
            $str = "<tr id='node-\$id' \$parentid_node style='\$style'>
                        <td style='padding-left:20px;'>\$id</td>
                        <td>\$name</td>
                        <td>\$spacer\$title</td>
                        <td>\$str_manage</td>
                    </tr>";
            $categorys = $tree->get_tree(0, $str);
            $this->assign("categorys", $categorys);
            //$this->node=node_merge($node);
            $this->display();
        }
        //添加岗位
        public function addRole(){
            $is_rbac = _rbac_btn_show(99,0);
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            if (IS_POST) {
                //防止重复提交
                $yonghu=M('yonghu');
                if (!$yonghu->autoCheckToken($_POST)) {
                    $this->error('请不要重复添加');
                }
                if (session('gongsiid')=="") {
                    $this->error('请重新登录');
                }
                if (I('status')) {
                    $status=1;
                } else {
                    $status=0;
                }
                $data['status']=$status;
                $data['remark']=I('remark');
                $data['rolefl']=I('rolefl');
                $data['miaoshu']=I('miaoshu');
                $data['xsshunxu']=I('xsshunxu');
                $data['gongsiid']=session('gongsiid');
                $isok=M('Role')->add($data);
                if ($isok) {
                    $this->success('添加成功');
                }else{
                    $this->error('添加失败');
                }
            }else{
                $this->rolefl=M('Peizhi')->where(array('pzming'=>'rolefl','zhuangtai'=>1))->order('xsshunxu asc')->select();
                $this->display();
            }
        }
        //更新岗位
        public function editRole(){
            $is_rbac = _rbac_btn_show(101,0);
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            if (IS_POST) {
                if (I('status')) {
                    $status=1;
                } else {
                    $status=0;
                }
                $data['status']=$status;
                $data['remark']=I('remark');
                $data['rolefl']=I('rolefl');
                $data['miaoshu']=I('miaoshu');
                $data['xsshunxu']=I('xsshunxu');
                $data['gongsiid']=session('gongsiid');
                $isok=M('Role')->where(array('id'=>I('id')))->save($data);
                if ($isok) {
                    $this->success('更新成功');
                }else{
                    $this->error('更新失败');
                }
            }else{
                $this->role=M('Role')->where(array('id'=>I('id')))->find();
                $this->rolefl=M('Peizhi')->where(array('pzming'=>'rolefl','zhuangtai'=>1))->order('xsshunxu asc')->select();
                $this->display();
            }
        }
        //删除岗位
        public function delRole(){
            $is_rbac = _rbac_btn_show(103,0);
            if (!$is_rbac) {
                $this->error('异常错误！');
            }
            $isok=M('Role')->where(array('id'=>I('id')))->delete();
            if ($isok) {
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }
        //添加用户
        public function addUser(){
            $is_rbac = _rbac_btn_show(104,0);
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            if (IS_POST) {
                if(!preg_match("/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[8-9])\d{8}$/",I('dianhua'))){  
                    $this->error('电话号码格式不正确!'); 
                }
                if (I('dianhua')) {
                    $user1=M('yonghu')->where(array('dianhua' =>I('dianhua'),'gongsiid'=>session('gongsiid')))->find();
                    if ($user1) {
                        $this->error('手机号已被使用');
                    }
                }else{
                    $this->error('手机号不能为空');
                }
                if (I('ygbianhao')) {
                    $user2=M('yonghu')->where(array('ygbianhao' =>I('ygbianhao'),'gongsiid'=>session('gongsiid')))->find();
                    if ($user2) {
                        $this->error('员工编号已被使用');
                    }
                }
                if (I('xingbie') == 1) {
                    $xingbie = 1;
                } elseif (I('xingbie') == 2) {
                    $xingbie = 2;
                } else {
                    $xingbie = 0;
                }
                $bumen=M('bumen')->where(array('id'=>I('bumen')))->field('level,leixing')->find();
                if (I('leixing') == 1) {
                    $leixing = 1;
                    if ($bumen['leixing'] != 0) {
                        $this->error('请选择非业务部门！');
                    }
                    if ($bumen['level'] != 2) {
                        $this->error('请选择二级部门！');
                    }
                } elseif (I('leixing') == 2) {
                    $leixing = 2;
                    if ($bumen['leixing'] != 0) {
                        $this->error('请选择非业务部门！');
                    }
                    if ($bumen['level'] != 3) {
                        $this->error('请选择三级部门！');
                    }
                } elseif (I('leixing') == 3) {
                    $leixing = 3;
                    if ($bumen['leixing'] != 2) {
                        $this->error('请选择扩展专用部门！');
                    }
                    if ($bumen['level'] != 3) {
                        $this->error('请选择三级部门！');
                    }
                } else {
                    $leixing = 0;
                }
                $user = array(
                    'gongsiid'=>session('gongsiid'),
                    'ygmingcheng'=>I('ygmingcheng'),
                    'pinyinjs'=>I('pinyinjs'),
                    'dianhua'=>I('dianhua'),
                    'ygbianhao'=>I('ygbianhao'),
                    'xingbie'=>$xingbie,
                    'leixing'=>$leixing,
                    'bumen'=>I('bumen'),
                    'mima'=>I('mima','','md5'),
                    'logintime'=>time(),
                    'loginip'=>get_client_ip(),
                );
                for ($i=1; $i < 7; $i++) { 
                    $user['company'.$i]=0;
                }
                $bumen_find = M('bumen')->where(array('id'=>I('bumen')))->find();
                $u = $bumen_find['level'];
                $user['company'.$bumen_find['level']]=$bumen_find['id'];
                for ($i=0; $i < $u; $i++) { 
                    $bumen_find = M('bumen')->where(array('id'=>$bumen_find['parentid']))->find();
                    if ($bumen_find['bmming']) {
                        $user['company'.$bumen_find['level']]=$bumen_find['id'];
                    }
                }
                $role=array();
                if ($uid=M('yonghu')->add($user)) {
                    $role =  array(
                        'role_id'=>I('role_id'),
                        'user_id'=>$uid
                    );
                    M('role_user')->add($role);
                    $this->success('添加成功');
                }else{
                    $this->error('添加失败');
                }
            }else{
                if (session('username') == C('RBAC_SUPERADMIN')) {
                    $this->role=M('role')->where(array('gongsiid'=>session('gongsiid')))->order('rolefl asc,xsshunxu asc')->select();
                } else {
                    $role=M('role_user')->where(array('user_id'=>session('uid')))->getField('role_id');
                    $kxrole=M('role')->where(array('id'=>$role))->getField('kxrole');
                    if (!$kxrole) {
                        $kxrole=0;
                    }
                    $this->role=M('role')->where(array('gongsiid'=>session('gongsiid'),'id'=>array('in',$kxrole)))->order('rolefl asc,xsshunxu asc')->select();
                }
                $parentid = I("get.parentid",0,'intval');
                $select_categorys = bumen_option( $parentid, 106);
                $this->assign("select_categorys", $select_categorys);
                $this->display();
            }
        }
        //更新用户 node_id = 106
        public function editUser(){
            $is_rbac = _rbac_btn_show(106,0,I('id',0,'intval'));
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            $et = I('edittype');
            switch ($et) {
                case '1':
                    if (!IS_POST) {$this->redirect('Rbac/edituser');}
                    $id=I('id');
                    $yh=M('yonghu')->where(array('id'=>$id))->find();
                    if (I('bumen')!=$yh['bumen'] && ($yh['bumen']==true || I('bumen')==true)) {
                        $fzxqs=M('xiaoqu')->where(array('adduid'=>$id))->count();
                        $xqfzr=M('xiaoqu')->where(array('adduid'=>$id))->field('xiaoqum')->select();
                        $xqm = "";
                        foreach ($xqfzr as $key => $value) {
                            if ($key+1 == $fzxqs) {
                                $xqm .= $value['xiaoqum'];
                            } else{
                                $xqm .= $value['xiaoqum']."、";
                            }
                        }
                        if ($xqfzr) {
                            $this->error($yh['ygmingcheng'].'负责小区'.$xqm.'中！请先变更'.$xqm.'的负责人！');
                        }
                    }
                    $this->bumen = M('bumen')->where(array('gongsiid' =>session('gongsiid')))->select();
                    $this->role= M('role')->where(array('gongsiid' =>session('gongsiid')))->select();
                    $role_id=M('role_user')->where(array('user_id'=>$id))->getField('role_id');
                    $User=M("Yonghu");
                    if (I('xingbie') == 1) {
                        $xingbie = 1;
                    } elseif (I('xingbie') == 2) {
                        $xingbie = 2;
                    } else {
                        $xingbie = 0;
                    }
                    $bumen=M('bumen')->where(array('id'=>I('bumen')))->field('level,leixing')->find();
                    if (I('leixing') == 1) {
                        $leixing = 1;
                        if ($bumen['leixing'] != 0) {
                            $this->error('请选择非业务部门！');
                        }
                        if ($bumen['level'] != 2) {
                            $this->error('请选择二级部门！');
                        }
                    } elseif (I('leixing') == 2) {
                        $leixing = 2;
                        if ($bumen['leixing'] != 0) {
                            $this->error('请选择非业务部门！');
                        }
                        if ($bumen['level'] != 3) {
                            $this->error('请选择三级部门！');
                        }
                    } elseif (I('leixing') == 3) {
                        $leixing = 3;
                        if ($bumen['leixing'] != 2) {
                            $this->error('请选择扩展专用部门！');
                        }
                        if ($bumen['level'] != 3) {
                            $this->error('请选择三级部门！');
                        }
                    } else {
                        $leixing = 0;
                    }
                    $data['ygmingcheng']=I('ygmingcheng');
                    $data['pinyinjs']=I('pinyinjs');
                    $data['bumen']=I('bumen');
                    $data['ygbianhao']=I('ygbianhao');
                    $data['xingbie']=$xingbie;
                    $data['leixing']=$leixing;
                    if (I('ygbianhao')) {
                        $user2=M('yonghu')->where(array('ygbianhao' =>I('ygbianhao'),'gongsiid'=>session('gongsiid'),'id<>'.$id))->find();
                        if ($user2) {
                            $this->error('员工编号已被使用');
                        }
                    }
                    $data1 = array(
                        'user_id'=>$id,
                        'role_id'=>I('role')
                    );
                    if ($yh['ygmingcheng']==I('ygmingcheng') && $yh['bumen']==I('bumen') && $yh['ygbianhao']==I('ygbianhao') && $role_id==I('role') && $yh['xingbie']==$xingbie && $yh['leixing']==$leixing && $yh['pinyinjs']==I('pinyinjs')) {
                        $this->error('没有数据被更新');
                    }
                    $xiugai.="修改[".$yh['ygmingcheng']."]的信息为：";
                    if ($yh['ygmingcheng']!=I('ygmingcheng') && ($yh['ygmingcheng']==true || I('ygmingcheng')==true)) {
                        $xiugai.="员工名称：[".$yh['ygmingcheng']."]=>[".I('ygmingcheng')."];";
                    }
                    if ($yh['pinyinjs']!=I('pinyinjs') && ($yh['pinyinjs']==true || I('pinyinjs')==true)) {
                        $xiugai.="拼音检索：[".$yh['pinyinjs']."]=>[".I('pinyinjs')."];";
                    }
                    if ($yh['ygbianhao']!=I('ygbianhao') && ($yh['ygbianhao']==true || I('ygbianhao')==true)) {
                        $xiugai.="员工编号：[".$yh['ygbianhao']."]=>[".I('ygbianhao')."];";
                    }
                    if ($yh['xingbie']!=$xingbie && ($yh['xingbie']==true || $xingbie==true)) {
                        if ($yh['xingbie'] == 1) {
                            $xb = "男";
                        } elseif ($yh['xingbie'] == 2) {
                            $xb = "女";
                        } else {
                            $xb = "未知";
                        }
                        if ($xingbie == 1) {
                            $xb1 = "男";
                        } elseif ($xingbie == 2) {
                            $xb1 = "女";
                        } else {
                            $xb1 = "未知";
                        }
                        $xiugai.="性别:[".$xb."]=>[".$xb1."];";
                    }
                    if ($yh['leixing']!=$leixing && ($yh['leixing']==true || $leixing==true)) {
                        if ($yh['leixing'] == 1) {
                            $xb = "销售经理";
                        } elseif ($yh['leixing'] == 2) {
                            $xb = "销售";
                        } elseif ($yh['leixing'] == 3) {
                            $xb = "销售扩展";
                        }
                        if ($leixing == 1) {
                            $xb1 = "销售经理";
                        } elseif ($leixing == 2) {
                            $xb1 = "销售";
                        } elseif ($leixing == 3) {
                            $xb1 = "销售扩展";
                        }
                        $xiugai.="用户类型:[".$xb."]=>[".$xb1."];";
                    }
                    if (I('bumen')!=$yh['bumen'] && ($yh['bumen']==true || I('bumen')==true)) {
                        $xiugai.=get_xgbm($yh['bumen'],I('bumen'),'bumen');
                    }
                    if (I('role')!=$role_id && ($role_id==true || I('role')==true)) {
                        $xiugai.=get_xgjs($role_id,I('role'),'role');
                    }
                    $data_rizhi=array(
                        'zy_type'=>8,
                        'uid'=>session('uid'),
                        'addtime'=>time(),
                        'cz_type'=>2,
                        'zy_id'=>$id,
                        'neirong'=>$xiugai,
                    );
                    for ($i=1; $i < 7; $i++) { 
                        $data['company'.$i]=0;
                    }
                    $bumen_find = M('bumen')->where(array('id'=>I('bumen')))->find();
                    $u = $bumen_find['level'];
                    $data['company'.$bumen_find['level']]=$bumen_find['id'];
                    for ($i=0; $i < $u; $i++) { 
                        $bumen_find = M('bumen')->where(array('id'=>$bumen_find['parentid']))->find();
                        if ($bumen_find['bmming']) {
                            $data['company'.$bumen_find['level']]=$bumen_find['id'];
                        }
                    }
                    $ues=$User->where(array('id'=>$id))->save($data);
                    M('role_user')->where(array('user_id'=>$id))->delete();
                    $isok=M('role_user')->add($data1);
                    if ($ues or $isok){
                        if (($yh['leixing'] == 1) && ($leixing == 1)) {
                            M("xqbdxs")->where(array('xqtjr'=>$id))->setField('fzr',I('ygmingcheng'));
                        }
                        if (($yh['leixing'] == 2) && ($leixing == 2)) {
                            M("xqbdxs")->where(array('xsid'=>$id))->setField('xsm',I('ygmingcheng'));
                        }
                        M('rizhi')->add($data_rizhi);
                        $this->success('更新成功');
                    }else{
                        $this->error('更新失败');
                    }
                    break;
                case '2':
                    if (!IS_POST) {$this->redirect('Rbac/edituser');}
                    $uid = I('id');
                    $mima = trim(I('mima'));
                    $isok = $mima==''? false : M('yonghu')->where(array('id'=>$uid))->setField(array('mima' =>md5($mima)));
                    if ($isok) {
                        $this->success('密码已重置为：'.$mima);
                    }else{
                        $this->error('密码未更改');
                    }
                    break;
                default:
                    $user=M('Yonghu')->where(array('id'=>I('id')))->find();
                    $this->user=$user;
                    $this->role_id=M('role_user')->where(array('user_id'=>I('id')))->getField('role_id');
                    if (session('username') == C('RBAC_SUPERADMIN')) {
                        $this->role=M('role')->where(array('gongsiid'=>session('gongsiid')))->order('rolefl asc,xsshunxu asc')->select();
                    } else {
                        $role=M('role_user')->where(array('user_id'=>session('uid')))->getField('role_id');
                        $kxrole=M('role')->where(array('id'=>$role))->getField('kxrole');
                        if (!$kxrole) {
                            $kxrole=0;
                        }
                        $this->role=M('role')->where(array('gongsiid'=>session('gongsiid'),'id'=>array('in',$kxrole)))->order('rolefl asc,xsshunxu asc')->select();
                    }
                    $bumen = $user['bumen'];
                    $select_categorys = bumen_option( $bumen, 106);
                    $this->assign("select_categorys", $select_categorys);
                    $this->display();
                break;
            }
        }
        //删除用户  node_id = 108
        public function delUser(){
            $is_rbac = _rbac_btn_show(108,0,I('id',0,'intval'));
            if (!$is_rbac) {
                $this->error('异常错误！');
            }
            $id=I('id');
            $yh=M('yonghu')->where(array('id'=>$id))->find();
            $xiugai.="删除员工[".$yh['ygmingcheng']."]";
            $dp=M('Yonghu');
            $kyshu=M('keyuan')->where('weihurenid='.$id)->count();
            $xqfzr=M('xiaoqu')->where(array('adduid'=>$id))->count();
            $sjshu=$kyshu+$xqfzr;
            if ($sjshu) {
                $this->error('请先转移数据!');
            }
            $isok=$dp->where(array('id'=>$id))->setField('status',0);
            if ($isok){
                $data_rizhi['zy_type']=8;
                $data_rizhi['uid']=session("uid");
                $data_rizhi['addtime']=time();
                $data_rizhi['cz_type']=8;
                $data_rizhi['zy_id']=I('id');
                $data_rizhi['neirong']=$xiugai;
                M('rizhi')->add($data_rizhi);
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }
        //恢复用户
        public function huifuUser(){
            $id=I('id');
            $is_rbac = _rbac_btn_show(518,0,$id);
            if (!$is_rbac) {
                $this->error('异常错误！');
            }
            $yh=M('yonghu')->where(array('id'=>$id))->find();
            $xiugai.="恢复员工[".$yh['ygmingcheng']."]";
            $dp=M('Yonghu');
            $isok=$dp->where(array('id'=>$id))->setField('status',1);
            if ($isok){
                $data_rizhi['zy_type']=8;
                $data_rizhi['uid']=session("uid");
                $data_rizhi['addtime']=time();
                $data_rizhi['cz_type']=24;
                $data_rizhi['zy_id']=I('id');
                $data_rizhi['neirong']=$xiugai;
                M('rizhi')->add($data_rizhi);
                $this->success('恢复成功');
            }else{
                $this->error('恢复失败');
            }
        }
        //添加节点
        public function addNode(){
            $is_rbac = _rbac_btn_show(109,0);
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            if (IS_POST) {
                if (I('status')) {
                    $status=1;
                } else {
                    $status=0;
                }
                $data['status']=$status;
                $data['name']=I('name');
                $data['title']=I('title');
                $data['sort']=I('sort');
                $data['pid']=I('pid');
                $data['level']=I('level');
                $isok=M('Node')->add($data);
                if ($isok) {
                    $this->success('添加成功');
                }else{
                    $this->error('添加失败');
                }
            } else {
                $this->pid=I('pid',0,'intval');
                $this->level=I('level',1,'intval');
                switch ($this->level) {
                    case 1:
                        $this->type='应用';
                        break;
                    case 2:
                        $this->type='控制器';
                        break;
                    case 3:
                        $this->type='动作方法';
                        break;
                }
                $this->display();
            }
        }
        //更新节点
        public function editNode(){
            $is_rbac = _rbac_btn_show(110,0);
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            if (IS_POST) {
                if (I('status')) {
                    $status=1;
                } else {
                    $status=0;
                }
                $data['status']=$status;
                $data['name']=I('name');
                $data['title']=I('title');
                $data['sort']=I('sort');
                $isok=M("Node")->where(array('id'=>I('id')))->save($data);
                if ($isok){
                    $this->success('更新成功');
                }else{
                    $this->error('更新失败');
                }
            } else {
                $node=M('Node')->where(array('id'=>I('id')))->find();
                $this->node=$node;
                switch ($node['level']) {
                    case 1:
                        $this->type='应用';
                        break;
                    case 2:
                        $this->type='控制器';
                        break;
                    case 3:
                        $this->type='动作方法';
                        break;
                }
                $this->display();
            }
        }
        //删除节点
        public function delNode(){
            $is_rbac = _rbac_btn_show(112,0);
            if (!$is_rbac) {
                $this->error('异常错误！');
            }
            $id=I('id');
            $isok=M('Node')->where(array('id'=>$id))->delete();
            if ($isok) {
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }
        //配置权限
        public function access(){
            $is_rbac = _rbac_btn_show(113,0);
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            if (IS_POST) {
                $access1 = htmlspecialchars_decode(I('access'));
                $access2 = json_decode($access1,true);
                $access = array_unique(array_filter($access2));
                $rid = $access['rid'];
                $db = M('access');
                //清空原权限
                $db->where(array('role_id'=>$rid))->delete();
                //组合新权限
                unset($access['rid']);
                unset($access['__hash__']);
                $data = array();
                foreach ($access as $v) {
                    if ($v != "") {
                        $tmp = explode('_', $v);
                        if ($tmp[0] != 0) {
                            $data[]=array(
                            'role_id'=>$rid,
                            'node_id'=>$tmp[0],
                            'level'=>3,
                            'fanwei'=>$tmp[1],
                            'zhuangtai'=>$tmp[2],
                           );
                        }
                    }
                }
                $node = M('node')->where(array('level'=>array('in','1,2')))->select();
                foreach ($node as $v) {
                    $data[]=array(
                        'role_id'=>$rid,
                        'node_id'=>$v['id'],
                        'level'=>$v['level'],
                        'fanwei'=>0,
                        'zhuangtai'=>0,
                    );
                }
                //插入新权限
                if ($db->addALL($data)) {
                    $this->success('修改成功');
                }else{
                    $this->error('修改失败');
                }
            } else {
                $rid = I('rid',0,'intval');
                $arr = M('node_set')->where('status = 1')->order(array("sort" => "ASC"))->select();
                $tree = new \Org\Util\Tree();
                $tree->init($arr);
                $this->categorys = $tree->get_tree_array(0,$arr);
                $this->fyzhuangtai=M('peizhi')->where(array('pzming'=>'zhuangtai','zhuangtai'=>1))->order(array("lxid" => "ASC"))->select();
                $this->kyzhuangtai=M('peizhi')->where(array('pzming'=>'khzhuangtai','zhuangtai'=>1))->order(array("lxid" => "ASC"))->select();
                $bumen_options=M('options')->where(array('option_name'=>'bumen_options'))->find();
                $bumen_arr = json_decode($bumen_options['option_value'],true);
                $this->bumen_arr_level = $bumen_arr['bumen_array'];
                $this->rid=$rid;
                $this->display('access2');
            }
        }
        public function Bumen(){
            $is_rbac = _rbac_node_show(115);
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            $map['gongsiid']=session('gongsiid');
            $Data=M('bumen');
            $result = $Data->where($map)->order(array("sort" => "ASC"))->select();
            $xiao = $result;
            $tree = new \Org\Util\Tree();
            $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $newmenus=array();
            foreach ($result as $m){
                $newmenus[$m['id']]=$m;
            }
            $bumen_option_value = M('options')->where(array('option_name'=>'bumen_options'))->getField('option_value');
            $bumen_option_value_arr = json_decode($bumen_option_value,true);
            $bmlx2 = M('bumen')->where(array('level'=>3,'leixing'=>2))->getField('id');
            $bmlx3 = M('bumen')->where(array('level'=>3,'leixing'=>3))->getField('id');
            foreach ($result as $n=> $r) {
                $result[$n]['level_s'] = $bumen_option_value_arr['bumen_array'][$this->_get_level($r['id'], $newmenus)];
                if ($r['leixing'] == 1) {
                    if (!$bmlx2 && !$bmlx3) {
                        $tjkd="600";
                    } else {
                        $tjkd="480";
                    }
                } else {
                    $tjkd="480";
                }
                $result[$n]['str_manage'] = '<if condition="_rbac_node_show(116)"><a href="javascript:;" class="layui-btn layui-btn-normal layui-btn-mini" onclick="layer_show(\'添加部门\',\''.U('addBumen',array('parentid'=>$r['id'])).'\',\''.$tjkd.'\',\'480\')" style="text-decoration:none"><i class="Hui-iconfont">&#xe604;</i> 添加</a></if>';
                $result[$n]['str_manage'] .='&nbsp;&nbsp;&nbsp;<if condition="_rbac_node_show(118)"><a href="javascript:;" class="layui-btn layui-btn-warm layui-btn-mini" onclick="layer_show(\'更新部门\',\''.U('editbumen',array('id'=>$r['id'])).'\',\'480\',\'480\')" style="text-decoration:none"><i class="Hui-iconfont">&#xe6df;</i> 编辑</a></if>';
                $result[$n]['str_manage'] .='&nbsp;&nbsp;&nbsp;<if condition="_rbac_node_show(120)"><a href="javascript:;" class="layui-btn layui-btn-warm layui-btn-mini" onclick="admin_bumen_del(this,\''.$r['id'].'\')" style="text-decoration:none;background: red;"><i class="Hui-iconfont">&#xe6df;</i> 删除</a></if>';
            }
            $tree->init($result);
            $str = "<tr id='node-\$id' \$parentid_node style='\$style'>
                        <td style='padding-left:20px;'>\$id</td>
                        <td>\$level-\$level_s</td>
                        <td>\$spacer\$bmming</td>
                        <td>\$bmdianhua</td>
                        <td>\$str_manage</td>
                    </tr>";
            $categorys = $tree->get_tree(0, $str);
            $this->assign("categorys", $categorys);
            $this->display();
        }
        /**
         * 获取递归数组深度
         * @param $id
         * @param $array
         * @param $i
         */
        protected function _get_level($id, $array = array(), $i = 0) {
            if ($array[$id]['parentid']==0 || empty($array[$array[$id]['parentid']]) || $array[$id]['parentid']==$id){
                return  $i;
            }else{
                $i++;
                return $this->_get_level($array[$id]['parentid'],$array,$i);
            }
        }
        public function addBumen(){
            $is_rbac = _rbac_node_show(116);
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            if (IS_POST) {
                if (I('sort')) {
                    if(!preg_match("/^\d+$/",I('sort'))){
                        $this->error('排序请输入非负整数');
                    }
                }
                $data['parentid']=I('parentid',0,'intval');
                $level = M('bumen')->where(array('id'=>$data['parentid']))->getField('level');
                $fjlx = M('bumen')->where(array('id'=>$data['parentid']))->getField('leixing');
                if ($level == 1) {
                    if (I('leixing') == 1){
                        $bmlx1 = M('bumen')->where(array('level'=>2,'leixing'=>1))->getField('id');
                        if ($bmlx1) {
                            $this->error('业务部门已存在！');
                        }
                        $data['leixing']=1;
                    }
                }
                if ($level == 2) {
                    if (($fjlx == 1) && !I('leixing')) {
                        $this->error('业务部门只能添加专用部门！');
                    }
                    if (I('leixing') == 2){
                        $bmlx2 = M('bumen')->where(array('level'=>3,'leixing'=>2))->getField('id');
                        if ($bmlx2) {
                            $this->error('销售扩展部门已存在！');
                        }
                        if ($fjlx != 1) {
                            $this->error('父级部门不属于业务部门！');
                        }
                        $data['leixing']=2;
                    }
                }
                $data['level']=$level+1;//重要的等级
                $data['cjshijian']=time();
                $data['bmming']=I('bmming');
                $data['bmdianhua']=I('bmdianhua');
                $data['bmdizhi']=I('bmdizhi');
                $data['sort']=I('sort');
                $data['gongsiid']=session('gongsiid');
                if(M('bumen')->add($data)){
                    $this->success('添加成功');
                }else{
                    $this->error('添加失败');
                }
            } else {
                $parentid = I("get.parentid",0,'intval');
                $this->parentid = $parentid;
                $this->level = M('bumen')->where(array('id'=>$parentid))->getField('level');
                if ($this->level == 2) {
                    $this->bmlx = M('bumen')->where(array('id'=>$parentid))->getField('leixing');
                }
                $this->bmlx1 = M('bumen')->where(array('level'=>2,'leixing'=>1))->getField('id');
                $this->bmlx2 = M('bumen')->where(array('level'=>3,'leixing'=>2))->getField('id');
                $this->display();
            }
        }
        public function editBumen(){
            $is_rbac = _rbac_node_show(118);
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            if (IS_POST) {
                if (I('sort')) {
                    if(!preg_match("/^\d+$/",I('sort'))){
                        $this->error('排序请输入非负整数');
                    }
                }
                $id=I('id');
                $data['bmming']=I('bmming');
                $data['bmdianhua']=I('bmdianhua');
                $data['bmdizhi']=I('bmdizhi');
                $data['sort']=I('sort');
                if (M('bumen')->where(array('id'=>$id,'gongsiid'=>session('gongsiid')))->save($data)) {
                    $this->success('修改成功'); 
                }else{
                    $this->error('修改失败');
                }
            } else {
                $tree = new \Org\Util\Tree();
                $id = I("get.id",0,'intval');
                $this->bumen = M('bumen')->where(array('id'=>$id))->find();
                $parentid = $this->bumen['parentid'];
                $select_categorys = bumen_option( $parentid, 0);
                $this->assign("select_categorys", $select_categorys);
                $this->bm=M('bumen')->where(array('id'=>$id))->find();
                $this->yonghu=M('yonghu')->where(array('bumen'=>$id,'gongsiid'=>session('gongsiid')))->select();
                $this->display();
            }
        }
        public function delBumen(){
            $is_rbac = _rbac_node_show(120);
            if (!$is_rbac) {
                $this->error('异常错误！');
            }
            $bm=M('bumen')->where(array('id'=>I('id')))->getField('leixing');
            if ($bm) {
                $this->error('专用部门不可删除！');
            }
            $isok=M('bumen')->where(array('id'=>I('id')))->delete();
            if ($isok) {
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }
        public function xxzhuanyi(){
            $is_rbac = _rbac_btn_show(414,0,I('id'));
            if (!$is_rbac) {
                $this->redirect('Index/error');
            }
            if (IS_POST) {
                $yid = I('yid');
                $yh = M('yonghu')->where(array('id'=>$yid))->getField('ygmingcheng');
                $uid = I('uid1');
                if(!$uid){
                    $this->error("请选择客源维护人！");
                }
                if($yid == $uid){
                    $this->error("不能转移给自己！");
                }
                $bumen = I('bumen');
                $fkyid = I('fkyid');
                if($fkyid == ''){
                    $this->error("未选择客源");
                }
                $name = M('yonghu')->where(array('id'=>$uid))->getField('ygmingcheng');
                if(is_array($fkyid)){
                    $where = 'id in('.implode(',',$fkyid).')';
                }else{
                    $where = 'id='.$fkyid;
                }
                $zys=M('keyuan')->where(array($where))->count();
                $zy=M('keyuan')->where(array($where))->select();
                foreach ($zy as $key => $value) {
                    if($yid != $value['weihurenid']){
                        $this->error("数据异常！".$value['xqbianhao']."不是".$yh."的客源！");
                    }
                }
                foreach ($zy as $key => $value) {
                    if ($key+1 == $zys) {
                        $zybh.=$value['xqbianhao'];
                    } else{
                        $zybh.=$value['xqbianhao'].'、';
                    }
                }
                $xiugai.="将用户[".$yh."]的客户[".$zybh."]转移给[".$name."]";
                $data['weihurenid'] = $uid;
                $data['weihuren'] = $name;
                $isok=M('keyuan')->where(array($where))->save($data);
                if ($isok) {
                    $data_rizhi['zy_type']=8;
                    $data_rizhi['uid']=session("uid");
                    $data_rizhi['addtime']=time();
                    $data_rizhi['cz_type']=23;
                    $data_rizhi['zy_id']=$yid;
                    $data_rizhi['neirong']=$xiugai;
                    M('rizhi')->add($data_rizhi);
                    $this->success("成功转移客户".$zys."条");
                } else{
                    $this->error('转移失败');
                }
            }else{
                $uid=I('id');
                if (!$uid) {
                    $this->error('未找到用户');
                }
                $condition=" weihurenid=".$uid;
                $shijian1=I('shijian1');
                $shijian2=I('shijian2');
                if ($shijian1) {
                    $this->shijian1=$shijian1;
                    $shijian3=strtotime($shijian1);
                }
                if ($shijian2) {
                    $this->shijian2=$shijian2;
                    $shijian4=strtotime($shijian2)+86400;
                }
                if ($shijian3 and $shijian4){
                    if ($shijian3 > $shijian4){
                        $condition.=" and lurusj > ".$shijian4." and lurusj < ".$shijian3;
                        $this->shijian1=$shijian2;
                        $this->shijian2=$shijian1;
                    } else {
                        $condition.=" and lurusj > ".$shijian3." and lurusj < ".$shijian4;
                    }
                } elseif ($shijian3) {
                    $condition.=" and lurusj > ".$shijian3;
                } elseif ($shijian4) {
                    $condition.=" and lurusj < ".$shijian4;
                }
                $count=M('keyuan')->where($condition)->count();
                $page= new\Think\Page($count,30);
                $show=$page->show();
                $fkyzy=M('keyuan')->where($condition)->field('id,xqbianhao,khxingming,weihurenid,dianhua,kehulx,lurusj')->order('lurusj desc')->limit($page->firstRow.','.$page->listRows)->select();
                $bumen = I("get.bumen",0,'intval');
                $select_categorys = bumen_option( $bumen, 414);
                $this->assign("select_categorys", $select_categorys);
                $this->assign('firstRow',$Page->firstRow);
                $this->assign('fkyzy',$fkyzy);
                $this->assign('count',$count);
                $this->assign('page',$show);
                $this->display();
            }
        }
        // 员工日志
        public function rizhi(){
            $map = "gongsiid=".session('gongsiid');
            $x = _rbac_lists_where(442,0);
            if ($x && $x != "all" && $x != "me") {
                $map .= " and bumen in ({$x})";
            }elseif ($x == "me") {
                $map .= " and id=".session('uid');
            }elseif ($x == false) {
                $map .= " and id=0";
            }
            if (I('is_ajax')) {
                $startUnix = strtotime(I('datetime1'));
                $endUnix = strtotime(I('datetime2'))+86399; 
                $p = I('pageSize');
                $sn = I('sortName');
                $so = I('sortOrder');
                $sousuo=" where zy_type=8";
                if (I('datetime1') and I('datetime2')) {
                    $sousuo.=" and addtime >= '".$startUnix."' and addtime<'".$endUnix."'";
                }elseif (I('datetime1')) {
                    $sousuo.=" and addtime >= '".$startUnix."'";
                }elseif (I('datetime2')) {
                    $sousuo.=" and addtime<'".$endUnix."'";
                }
                if (I('searchText')) {
                    $map.= " and ((pinyinjs like '%" .I('searchText'). "%') or (ygmingcheng like '%" .I('searchText'). "%') or (dianhua like '%" .I('searchText'). "%'))";
                }
                $count=M('rizhi')->query("select count(*) from __RIZHI__ a join (select id as b_id,ygmingcheng,bumen from __YONGHU__ where ".$map." ) b on a.uid=b.b_id ".$sousuo);
                $Page = new \Think\Page($count['0']['count(*)'],$p);
                $show = $Page->show();
                $sql="select a.*,b.ygmingcheng,b.bumen from __RIZHI__ a join (select id as b_id,ygmingcheng,bumen from __YONGHU__ where ".$map." ) as b on a.uid=b.b_id ".$sousuo." order by a.id DESC limit  ".$Page->firstRow.','.$Page->listRows;
                $Model = new \Think\Model();
                $arr=$Model->query($sql);
                foreach ($arr as $key => $value) {
                    $arr[$key]['addtime1']=date('Y-m-d H:i:s',$value['addtime']);
                    $arr[$key]['bmming']=bumen($value['bumen']);
                }
                $data=array('data'=>$arr,'total'=>$count['0']['count(*)'],);
                header("Content-type: application/json");
                exit(json_encode($data));
            }else{
                $this->display();
            }
        }
        //可选岗位
        public function kxrole(){
            $is_rbac = _rbac_btn_show(586,0);
            if (!$is_rbac) {
                $this->error('异常错误！');
            }
            if (IS_POST) {
                $id=I('id');
                $roleids=I('duoxuan');
                foreach ($roleids as $key => $value) {
                    $arr[]=$value;
                }
                $ids=implode(",",$arr);
                $isok=M('role')->where(array('id'=>$id))->setField('kxrole',$ids);
                if ($isok) {
                    $this->success('配置成功');
                }else{
                    $this->error('配置失败');
                }
            }else{
                $role=M('role_user')->where(array('user_id'=>session('uid')))->getField('role_id');
                $kxrole=M('role')->where(array('id'=>$role))->getField('kxrole');
                if (session('username') == C('RBAC_SUPERADMIN')) {
                    $this->role=M('role')->where(array('gongsiid'=>session('gongsiid')))->order('rolefl asc,xsshunxu asc')->select();
                } else {
                    if (!$kxrole) {
                        $kxrole="0";
                    }
                    $this->role=M('role')->where(array('gongsiid'=>session('gongsiid'),'id'=>array('in',$kxrole)))->order('rolefl asc,xsshunxu asc')->select();
                }
                $kxroleid=M('role')->where(array('id'=>I('id')))->getField('kxrole');
                $roleids=explode(",",$kxroleid);
                foreach ($roleids as $key => $value) {
                    $arr[$value]=$value;
                }
                $this->roleid=$arr;
                $this->rolefl=M('Peizhi')->where(array('pzming'=>'rolefl','zhuangtai'=>1))->order('xsshunxu asc')->select();
                $this->display();
            }
        }
    }
?>