<?php
/**
 * Created by PhpStorm.
 * User: hujun
 * Date: 2018/1/16
 * Time: 13:51
 */

namespace app\index\controller;

use app\index\extend\Basic;
use app\model\AuthGroup;
use app\model\AuthRule;
use think\Db;
class Auth extends Basic
{
   protected $authGroupModel;
    protected $authRuleModel;
   


    /**
     * 权限列表页
     * 
     * @return type
     */
    public function index(){
        return view('index');
    }
    

    /**
     * 权限分配
     * 
     * @param type $group_id
     */
    public function access($group_id = 0) {
        return view('access');
    }

    /**
     * 用户组授权用户列表
     * 
     * @param type $group_id
     */
    public function accessUser($group_id = 0) {
        return view('accessUser');
    }

    public function getAuth() {
        $data['status'] = 200;
        $data['msg'] = '';

        $params = $this->request->param();
        $pageNo = empty($params['pageNo']) ? 1 : $params['pageNo'];
        $pageSize = empty($params['pageSize']) ? 15 : $params['pageSize'];
        $auth_group = New AuthGroup();
        $where = 'status <> 0';
        $data['list'] = $auth_group->getList($pageNo, $pageSize, '','*', $where);
        $data['total'] = $auth_group->getTotal($where);
        return $this->response(200, '', $data);
    }

    /**
     * 角色编辑
     */
    public function roleEdit() {
        //$this->assign('type','1');
        // return $this->display();
        return view('role_edit');
    }

    /**
     * 验证数据
     * @param  string $validate 验证器名或者验证规则数组
     * @param  array  $data          [description]
     * @return [type]                [description]
     */
    protected function validateData($data,$validate)
    {
        if (!$validate || empty($data)) return false;
        $result = $this->validate($data,$validate);
        if(true !== $result){
            // 验证失败 输出错误信息
            return $result;
        }
        return 1;

    }

    /*
    * 新增or修改or查看
    * $group_id !=0为查看
    * post存在id为新增
    *
    * */
    public function  addAuth($group_id=0){
        $title = $group_id ? '编辑':'新增';
        $table= New AuthGroup();
        

        if (empty($group_id)) {
            $data = input('post.');
            $err=$this->validateData($data,
                [
                    ['title','require|chsAlpha','用户组名称不能为空|用户组名称只能是汉字和字母'],
                    ['description','chsAlphaNum','描述只能是汉字字母数字']
                ]
            );

           if($err!=1){
               return $this->response(100, $err);
           }
            $id   = isset($data['id']) && $data['id']>0 ? $data['id']:false;

            if ($table->editData($data,$id)) {
                return $this->response(200, '成功');
            } else {
                return $this->response(101, '失败');

            }

        } else {
            $info= $table->where("id={$group_id}")->find();
            return $this->response(200, $title, $info);


        }
    }

//权限表list
    public function classList($type=1){
        $table=new authRule;
        $menus=db('auth_rule')->select();

        // exit;
        $menus =$table->toFormatTree($menus,'title');
        // prt($menus);
        if($type==1) {
            return $this->response(200, '成功', $menus);
        }else{
            return $menus;
        }
    }
    

    /**
     * 角色权限分配or查看
     * @param  integer $group_id 组ID
     * @return [type] [description]
     * @date   2018-01-22
     * @author zfc
     */
    public function accessLook($group_id=0){
         $table= New AuthGroup;
         $table2=new authRule;
        $data['title']='权限分配';
//        echo $group_id;
//        exit;
        if (IS_POST && $group_id==0) {
            //添加or修改
            $data['id']    = $group_id;
            $menu_auth     = input('post.menu_auth/a','');//获取所有授权菜单id
            $data['rules'] = implode(',',$menu_auth);//拼接
            $id   = isset($data['id']) && $data['id']>0 ? $data['id']:false;

            //提交数据
            if ( $table->editData($data,$id)) {
                return $this->response(200, '成功');
            }else{
                return $this->response(100, '失败');
            }
                
            //}

        } else{
            //查看
            $role_auth_rule = $table->where(['id'=>intval($group_id)])->value('rules');
            $data['rules']=explode(',',$role_auth_rule);//获取指定获取到的权限
            $data['class']=$this->classList(2);
            //设置选中
            foreach($data['class'] as $k=>$v){
                if(in_array($v['id'],$data['rules'])){
                    $data['class'][$k]['is']='1';

                }else{
                    $data['class'][$k]['is']='0';

                }

            }
        }
        return $this->response(200,'可以查看',$data);
    }
    //编辑角色权限
    public  function updateAccess(){
        $table= New AuthGroup;

        $data = input('post.');
       // prt($data);
        $data['rules']=trim($data['rules'],',');
        //提交数据
        if ( $table->editData($data,$data['id'])) {
            return $this->response(200, '成功');
        }else{
            return $this->response(100, '失败');
        }



    }
    
      /**
     * 设置角色的状态
     */
    public function setStatus($model ='auth_rule',$script = false){
        $ids = input('request.ids/a');
        if ($model =='AuthGroup') {
            if (is_array($ids)) {
                if(in_array(1, $ids)) {
                    $this->error('超级管理员不允许操作');
                }
            } else{
                if($ids === 1) {
                    $this->error('超级管理员不允许操作');
                }
            }
        } else{
            //cache('admin_sidebar_menus_'.$this->currentUser['uid'],null);//清空后台菜单缓存
        }
        
        parent::setStatus($model);
    }
    //权限表界面
    public function  authRuleIndex(){

      return view('auth_rule_index');
    }
    //权限列表
    public function authRuleList(){
        $table= new authRule;
        $data['status'] = 200;
        $data['msg'] = '';
        $params = $this->request->param();
        $pageNo = empty($params['pageNo']) ? 1 : $params['pageNo'];
        $pageSize = empty($params['pageSize']) ? 15 : $params['pageSize'];
       //条件
        $field="a.id,a.name,a.title,a.depend_flag,a.type,a.pid,a.icon,a.sort,if(a.is_menu,'是','否')is_menu,a.status,ifnull(b.title,'顶级') as title2";
        $where='a.status=1';
        $order='a.pid asc,a.sort asc';
        $join=[['auth_rule b', ' a.pid=b.id','left']];
       $data['list']  = $table->authRuleList($pageNo, $pageSize,$order,$field,$join, $where);
       $data['total'] = $table->getTotal('status=1');
       // prt($list);//转化arr
       //prt(collection($list)->toArray());//转化arr
        return $this->response(200,'成功',$data);

    }
    //编辑权限窗口
    public function AuthRuleBox($id=0){
        return view('auth_rule_box');
    }
   //分类列表
    public function AuthClass($fu='0'){
        $table=new AuthRule;
        $data['status'] = 200;
        $data['msg'] = '';
        $field="a.id,a.title,a.pid,a.sort";
        $where='a.status=1';
        $order='a.pid asc,a.sort asc';
        $data['list']  = $table->authRuleList2($order,$field,'', $where);
        //echo $table->getLastSql();
        //prt(collection($data['list'])->toArray());//转化arr
        if($fu=='1'){
            return $data['list'];
        }else{
            return $this->response(200,'成功',$data);

        }
    }
    //新增编辑权限
    public function updateAuthRule($group_id=0){
        $data['status'] = 200;
        $data['msg'] = '';
        $title = $group_id ? '编辑':'新增';

        $table= New AuthRule;
        

        if (IS_POST && $group_id==0) {

            $data = input('post.');
           
            $id   = isset($data['id']) && $data['id']>0 ? $data['id']:false;
            //判断name是否重复

            if($table->repetition('name',$data['name'])&& empty($id)){
                return $this->response(100, '存在重复值');
            }


            //新增或者编辑数据
            //prt($data);
            if ($table->editData($data,$id)) {
                return $this->response(200, '成功');

            } else {
                return $this->response(100, '无修改');

            }

        } else {
            $where="a.id={$group_id}";
            $field="a.*,ifnull(b.title,'顶级菜单') as title2";
            $order='';
            $join=[['auth_rule b', ' a.pid=b.id','left']];
            $info= $table->authRuleList2($order,$field,$join, $where);
           //echo $table->getLastSql();
            return $this->response(200, $title, $info[0]);


        }  
    }


   
}