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

namespace app\index\controller;

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


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

    /**
     * 权限分配
     */
    public function access() {
        return view('access');
    }

    /**
     * 用户组授权用户列表
     */
    public function accessUser() {
        return view('accessUser');
    }

    /**
     * 角色列表接口
     * @return \think\Response
     */
    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 in(0,1)';
        $search=$params['search'];
        if(!empty($search)){
            $where.=" and id='$search' or title like '%$search%' ";
            $data['search']=$search;
        }

        $data['list'] = $auth_group->getList($pageNo, $pageSize, 'id desc','*', $where);
        $data['total'] = $auth_group->getTotal($where);
        return $this->response(200, '', $data);
    }

    /**
     * 角色列表接口无分页
     * @return \think\Response
     */
    public function getAuth2() {
        $data['status'] = 200;
        $data['msg'] = '';

        $auth_group = New AuthGroup();
        $where = 'status = 0';
        $data['list'] = $auth_group->getList2('id desc','id,title', $where);
        return $this->response(200, '', $data);
    }

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

    /**验证数据
     * @param $data
     * @param $validate
     * @return array|bool|int|string|true
     */


    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查看
     * post存在id为新增
     * $group_id !=0为查看
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function  addAuth(){
        $group_id=$this->request->param('id');

        $table= New AuthGroup();
        

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

           if($err!=1){
               return $this->response(100, $err);
           }
            //新增或者编辑数据
            if(empty($data['id'])){
                $data['create_time']=  date( 'Y-m-d H:i:s',time());
                $data['update_time']=  date( 'Y-m-d H:i:s',time());
                $id='';
            }else{
                $data['update_time']=  date( 'Y-m-d H:i:s',time());
                $id=$data['id'];
            }

            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, '取值', $info);


        }
    }


//权限表list

    /**
     * @param int $type
     * @return array|false|\PDOStatement|string|\think\Collection|\think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    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查看
     * @date   2018-01-22
     * @author zfc
     */
    /**
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function accessLook(){
         $table= New AuthGroup;
        $group_id=$this->request->param('id');
        $data['title']='权限分配';
//        echo $group_id;
//        exit;
        if ($this->request->isPost()) {
            //添加or修改
            $data['id']    = $group_id;
            $menu_auth     = input('post.menu_auth/a','');//获取所有授权菜单id
            $data['rules'] = implode(',',$menu_auth);//拼接
            //新增或者编辑数据
            if(empty($data['id'])){
                $data['create_time']=  date( 'Y-m-d H:i:s',time());
                $data['update_time']=  date( 'Y-m-d H:i:s',time());
                $id='';
            }else{
                $data['update_time']=  date( 'Y-m-d H:i:s',time());
                $id=$data['id'];
            }

            //提交数据
            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 updateRoleStatus(){
        $table=New AuthRule;
        $data=$this->request->param();


        $ids=trim($data['ids'],',');
        if($table->saveStatus('status',$data['status'],$ids)){
            return $this->response(200,'成功',$data);
        }else{
            return $this->response(100,'失败',$data);
        }
    }

    
      /**
     * 设置角色的状态
     */
    public function updateGroup(){
        $table=New AuthGroup;
        $data=$this->request->param();


        $ids=trim($data['ids'],',');
        if($table->saveStatus('status',$data['status'],$ids)){
            return $this->response(200,'成功',$data);
        }else{
            return $this->response(100,'失败',$data);
        }
    }
    //权限表界面
    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 in(0,1)';
        $search=$params['search'];
        if(!empty($search)){
            $where.=" and a.id='$search' or a.name like '%$search%' or a.title like '%$search%' ";
            $data['search']=$search;
        }
        $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($where,'a');
       // prt($list);//转化arr
       //prt(collection($list)->toArray());//转化arr
        return $this->response(200,'成功',$data);

    }
    //编辑权限窗口
    public function AuthRuleBox(){
        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=$this->request->param('id');
        $table= New AuthRule;
        

        if ($this->request->isPost()) {

            $data = input('post.');

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

            //新增或者编辑数据
            if(empty($data['id'])){
                $data['create_time']=  date( 'Y-m-d H:i:s',time());
                $data['update_time']=  date( 'Y-m-d H:i:s',time());
                $id='';
            }else{
                $data['update_time']=  date( 'Y-m-d H:i:s',time());
                $id=$data['id'];
            }


            //新增或者编辑数据
            //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, '取值', $info[0]);


        }  
    }


   
}