<?php
/**
 * 权限相关
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Permission extends MY_Controller{

    public $retData = array('referer' => '', 'refresh' => true, 'state' => 'success', 'message' => '提交成功');

    protected $page = 10;//分页

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper('cookie');
        $this->load->library('pagination');
    }


    /**
     * 用户列表
     */
    public function list(){
        if(!$this->isAdmin()) {//如果不是管理员没有权限查看用户列表
            redirect('permission/forbidpage');
            exit;
        }
        $data = array('list' => []);
        $data['list'] = $this->db->get('cmsadmin')->result_array();
        $role = $this->db->get('cmsrole')->result_array();
        $roleName = [0=>'普通用户'];
        foreach ($role as $row){
            $roleName[$row['id']] = $row['rolename'];
        }
        $data['roleName'] = $roleName;
        $this->load->view('permission/list', $data);
    }

    /**
     * 获取菜单相关
     */
    public function menu(){
        $data = array('menu' => []);
        $this->config->load('menu', true);
        $menu = $this->config->item('menu', 'menu');
        $data['role'] = $this->db->get('cmsrole')->result_array();
        $data['menu'] = $menu;
        $data['androidPackageList'] = $this->androidPackageList + $this->oldAnPackageList;
        $data['iosPackageList'] = $this->iosPackageList + $this->oldIosPackageList;
        $this->load->view('permission/menu', $data);
    }

    /**
     * 更新用户和权限
     */
    public function actionadd(){
        if(!$this->isAdmin()) {//如果不是管理员没有权限查看用户列表
            redirect('permission/forbidpage');
            exit;
        }
        $username = $this->input->post('username');
        $userpwd  = $this->input->post('userpwd');
        $mobile   = intval($this->input->post('mobile'));
        if(empty($username) || empty($userpwd)) {
            $retData = $this->retData;
            $retData['state'] = 'error';
            $retData['message'] = '用户名和密码和手机号不能为空';
            die(json_encode($retData));
        }

        $userRole = $this->input->post('userRole');
        if($userRole == 'admin') {
            $urllist = [];
            $package = [];
        }else {
            $urllist= $this->input->post('urllist');
            $package = $this->input->post('package');//页面那边并没有传过来
            if($package || empty($package)){
                $package = [];
            }
//            if(empty($package)) {
//                $retData = $this->retData;
//                $retData['state'] = 'error';
//                $retData['message'] = '包选择不能为空';
//                die(json_encode($retData));
//            }
        }
        $sidList = json_encode($package);
        //插入用户信息表
        if($userRole != 'admin'){
            $is_admin = 0;
            $role = $userRole;
        }else{
            $is_admin = 1;
            $role = 0;
        }
        $data = array(
            'username' => $username,
            'pwd' => md5($userpwd),
            'chinesename' => $username,
            'is_admin' => $is_admin,
            'role' => $role,
            'mobile' => $mobile,
        );
        $this->db->insert('cmsadmin', $data);

        //插入用户权限表
        $permissionData = array(
            'adminid' => $this->db->insert_id(),
            'list' => serialize($urllist),
            'sidList' => $sidList
        );
        $this->db->insert('permission', $permissionData);
        $this->retData['referer'] = 'permission/list';
        die(json_encode($this->retData));
    }


    /**
     * 编辑玩家权限
     */
    public function edit($id = 0){
        if(!$this->isAdmin()) {//如果不是管理员没有权限查看用户列表
            redirect('permission/forbidpage');
            exit;
        }
        $data = array('menu' => [], 'list' => [], 'name' => '');
        $this->config->load('menu', true);
        $menu = $this->config->item('menu', 'menu');
//        $data['menu'] = $menu;

        //链表查询
        $this->db->select('cmsadmin.*, permission.list, permission.sidList');
        $this->db->from('cmsadmin');
        $this->db->join('permission', 'cmsadmin.id = permission.adminid', 'left');
        $this->db->where('cmsadmin.id', $id);
        $query = $this->db->get();
        $row = $query->row_array();

        $data['username'] = $row['username'];
        $data['chinesename'] = $row['chinesename'];
        $data['id'] = $row['id'];
        $data['admin'] = $row['is_admin'];
        $data['userRole'] = $row['role'];
        $data['mobile'] = $row['mobile'];
        $data['role'] = $this->db->get('cmsrole')->result_array();
        $data['list'] = $row['list'] ? unserialize($row['list']) : [];
        $data['androidPackageList'] = $this->androidPackageList + $this->oldAnPackageList;
        $data['iosPackageList'] = $this->iosPackageList + $this->oldIosPackageList;
        $data['packageList'] = json_decode($row['sidList'], 1);
        $this->load->view('permission/edit', $data);
    }

    /**
     * 编辑玩家的权限
     */
    public function actionedit(){
        $adminid = $this->input->post('adminid');
        $userRole = intval($this->input->post('userRole'));
        $chinesename = $this->input->post('chinesename');
        $mobile = $this->input->post('mobile');
        if($userRole == 'admin'){
            $this->db->update('cmsadmin', ['is_admin'=>1,'role'=>0,'chinesename'=>$chinesename,'mobile'=>$mobile], ['id'=>$adminid]);
            $this->db->replace('permission', [
                'list' => serialize([]),
                'adminid' => $adminid,
                'sidList' => json_encode([])
            ]);
            die(json_encode($this->retData));
        }else{
            $urllist= $this->input->post('urllist');
            $package = $this->input->post('package');
//            $list = serialize($urllist??[]);//前端提交过来的
            //需求 不再让单个用户编辑自己的权限
            $tb = otable::cmsrole();
            $sql = "SELECT * FROM {$tb} WHERE id = {$userRole} LIMIT 1";
            $ret = oo::commonOprDb("default")->getOne($sql,1);
            $list = $ret['rule'];

            if($userRole == 0){
//                if(empty($package) || empty($list) ) {
//                    $retData = $this->retData;
//                    $retData['state'] = 'error';
//                    $retData['message'] = '普通用戶包或权限不能为空';
//                    die(json_encode($retData));
//                }
            }
            $sidList = json_encode($package??[]);
            $data = array(
                'list' => $list,
                'adminid' => $adminid,
                'sidList' => $sidList
            );
            $this->db->update('cmsadmin', ['is_admin'=>0,'role'=>$userRole,'chinesename'=>$chinesename,'mobile'=>$mobile], ['id'=>$adminid]);
            $this->db->replace('permission', $data);
            die(json_encode($this->retData));
        }
    }

    public function actionDelUser(){
        $id = $this->input->post('id');
        $this->db->delete('cmsadmin', array('id' => $id));
    }

    /**
     * 没有权限页面
     */
    public function forbidpage(){
        $this->load->view('permission/forbidpage');
    }

    /**
     * 角色管理
     * Created by: Owen
     * Created on: 2019/8/8 18:46
     * Description:
     */
    public function role(){
        $data = array('list' => []);
        $query = $this->db->get('cmsrole');
        $data['list'] = $query->result_array();
        $this->load->view('permission/role', $data);
    }

    public function roleList(){
        $data = array('list' => []);
        $query = $this->db->get('cmsrole');
        $list = $query->result_array();
        $list[] = ['id'=>0,'rolename'=>'管理员'];
        $tb = otable::cmsadmin();
        foreach($list as $key => $row){
            $id = $row['id'];
            if($row['rolename'] == "管理员"){
                $list[$key]['userList'] = oo::commonOprDb("default")->getAll("SELECT * FROM {$tb} WHERE role = {$id} AND is_admin = 1",1);
            }else{
                $list[$key]['userList'] = oo::commonOprDb("default")->getAll("SELECT * FROM {$tb} WHERE role = {$id}",1);
            }
        }
        $data['list'] = $list;
        $this->load->view('permission/roleList', $data);
    }

    /**
     * 角色新增
     * Created by: Owen
     * Created on: 2019/8/8 18:46
     * Description:
     */
    public function roleAdd(){
        $data = array('menu' => []);
        $this->config->load('menu', true);
        $menu = $this->config->item('menu', 'menu');
        $data['menu'] = $menu;
        $data['androidPackageList'] = $this->androidPackageList + $this->oldAnPackageList;
        $data['iosPackageList'] = $this->iosPackageList + $this->oldIosPackageList;
        $this->load->view('permission/roleadd', $data);
    }


    /**
     * 更新用户和权限
     */
    public function actionroleadd(){
        $username = $this->input->post('rolename');
        $internal = $this->input->post('is_internal');

        if(empty($username)) {
            $retData = $this->retData;
            $retData['state'] = 'error';
            $retData['message'] = '角色名不能为空';
            die(json_encode($retData));
        }


        $urllist= $this->input->post('urllist');
        if(empty($urllist)) {
            $retData = $this->retData;
            $retData['state'] = 'error';
            $retData['message'] = '权限不能为空';
            die(json_encode($retData));
        }

//        $package = $this->input->post('package');
//        if(empty($package)) {
//            $retData = $this->retData;
//            $retData['state'] = 'error';
//            $retData['message'] = '包选择不能为空';
//            die(json_encode($retData));
//        }

        $sidList = json_encode([1,2]);
        //插入用户信息表
        $data = array(
            'is_internal' => (int)$internal,
            'rolename' => $username,
            'rule' => serialize($urllist),
            'package' => $sidList,
        );
        $this->db->insert('cmsrole', $data);
        $this->retData['referer'] = 'permission/role';
        die(json_encode($this->retData));
    }

    public function actionDelRole(){
        $id = $this->input->post('id');
        $this->db->delete('cmsrole', array('id' => $id));
    }


    /**
     * 编辑玩家权限
     */
    public function roleEdit($id = 0){
        $data = array('menu' => [], 'list' => [], 'name' => '');
        $this->config->load('menu', true);
        $menu = $this->config->item('menu', 'menu');
        $data['menu'] = $menu;

        //链表查询
        $this->db->select('*');
        $this->db->from('cmsrole');
        $this->db->where('id', $id);
        $query = $this->db->get();
        $row = $query->row_array();

        $data['rolename'] = $row['rolename'];
        $data['id'] = $row['id'];
        $data['is_internal'] = $row['is_internal'];
        $data['rule'] = $row['rule'] ? unserialize($row['rule']) : [];
        $data['androidPackageList'] = $this->androidPackageList + $this->oldAnPackageList;
        $data['iosPackageList'] = $this->iosPackageList + $this->oldIosPackageList;
        $data['package'] = json_decode($row['package'], 1);
        $this->load->view('permission/roleedit', $data);
    }

    /**
     * 编辑玩家的权限
     */
    public function actioneditRole(){
        $adminid= $this->input->post('adminid');
        $urllist= $this->input->post('urllist');
        $internal= $this->input->post('is_internal');
//        $package = $this->input->post('package');

        $list = serialize($urllist);
        if(empty($list)) {
            $retData = $this->retData;
            $retData['state'] = 'error';
            $retData['message'] = '权限不能为空';
            die(json_encode($retData));
        }
//        if(empty($package)) {
//            $retData = $this->retData;
//            $retData['state'] = 'error';
//            $retData['message'] = '包选择不能为空';
//            die(json_encode($retData));
//        }
//        $sidList = json_encode($package);
        $internal = !in_array($internal, [0, 1]) ? 1 : (int)$internal;
        $this->db->update('cmsrole', ['rule'=>$list, 'is_internal' => $internal], ['id'=>$adminid]);
        $this->retData['referer'] = 'permission/role';
        die(json_encode($this->retData));
    }

    //操作日记
    public function log($page = 0){
        //分页
        $where = '';
        $data['stime'] = get_cookie('stime') ?? '';
        $data['etime'] = get_cookie('etime') ?? '';
        $data['key'] = get_cookie('key') ?? '';
        if(!empty($data['stime'])){
            $where .= " AND add_time >= ".strtotime($data['stime'] . " 0:0:0");
        }
        if(!empty($data['etime'])){
            $where .= " AND add_time <= ".strtotime($data['etime'] . " 23:59:59");
        }
        if(!empty($data['key'])){
            $uid = intval($data['key']);
            if($uid){
                $where .= " AND ( uid = {$uid} OR username = '{$data['key']}' OR reason LIKE '%{$data['key']}%' OR url LIKE '%{$data['key']}%' OR uri LIKE '%{$data['key']}%')";
            }else{
                $where .= " AND ( username = '{$data['key']}' OR reason LIKE '%{$data['key']}%' OR url LIKE '%{$data['key']}%' OR uri LIKE '%{$data['key']}%')";
            }
        }
        $tb = otable::cmslog();
        $sql = "SELECT count(*) as total FROM {$tb} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb("default")->getOne($sql,1);
        $total = $ret['total'];
        $sql = "SELECT * FROM {$tb} WHERE 1=1 {$where} ORDER BY id DESC limit {$page},{$this->page}";
        $data['list'] = oo::commonOprDb("default")->getAll($sql,1);
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#permission/log');
        $pageConfig['total_rows'] = $total;
        $pageConfig['per_page'] = $this->page;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['page'] = $page;
        $data['total'] = $total;

        $this->load->view('permission/log', $data);
    }
}
