<?php
/**
 * User: nickbai
 * Date: 2017/10/23 13:33
 * Email: 1902822973@qq.com
 */
namespace app\admin\controller;

class Admins extends Base
{
    // 管理员列表
    public function index()
    {
//        $token = 'NzgyNTUwIyRAJSFeKi8xNTYxNTQwMzQzLzE=';
//        $res = model('Admins')->checktoken($token);
//        if($res == -1){
//            return $res;
//        }
//        $admin_id = explode('/',base64_decode($token))['2'];
//        $adminInfo = db('admins')->where('id', $admin_id)->find();

        if (request()->isAjax()) {

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            if (strlen($param['searchText'])) {
                $where['user_name'] = ['like', '%' . $param['searchText'] . '%'];
            }

            $result = db('admins')->where($where)->limit($offset, $limit)->select();
            $powergroup = db('admingroup')->select();
            foreach ($result as $key => $vo) {
                for($i=0;$i<count($powergroup);$i++){
                    if($result[$key]['group_id'] == $powergroup[$i]['group_id']){
                        $result[$key]['group_name'] = $powergroup[$i]['group_name'];
                    }
                }
                // 优化显示状态
                if(1 == $vo['status']){
                    $result[$key]['status'] = '<span style="color: #2fbe1b">启用</span>';
                }else{
                    $result[$key]['status'] = '<span style="color: red">禁用</span>';
                }

//                // 优化显示状态
//                if (1 == $vo['status']) {
//                    $result[$key]['status'] = '<span class="label label-primary">启用</span>';
//                } else {
//                    $result[$key]['status'] = '<span class="label label-danger">禁用</span>';
//                }

                // 上次登录时间
                $result[$key]['last_login_time'] = empty($vo['last_login_time']) ? '' : date('Y-m-d H:i:s', $vo['last_login_time']);

                // 生成操作按钮
                if (1 != $vo['id']) {
                    $result[$key]['operate'] = $this->makeBtn($vo['id']);
                }
            }

            $return['total'] = db('admins')->where($where)->count();  //总数据
            $return['rows'] = $result;

            return json($return);

        }
//
        return $this->fetch();
    }

    // 添加管理员
    public function addAdmin()
    {
        if (request()->isPost()) {

            $param = input('post.');

            $has = db('admins')->field('id')->where('user_name', $param['user_name'])->find();
            if (!empty($has)) {
                return json(['code' => -1, 'data' => '', 'msg' => '该管理员已经存在']);
            }

            if(empty($param['group_id'])){
                return json(['code' => -4, 'data' => '', 'msg' => '请选择权限']);
            }

            $param['password'] = md5($param['password'] . config('salt'));
            try {
                db('admins')->insert($param);
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '添加管理员成功']);
        }
        $admingroup = db('admingroup')->where('status',1)->select();
        $this->assign([
            'admingroup' => $admingroup,
            'status' => config('kf_status')
        ]);

        return $this->fetch('addadmin');
    }

    // 编辑管理员
    public function editAdmin()
    {
        if (request()->isAjax()) {

            $param = input('post.');

            // 检测用户修改的管理员是否重复
            $has = db('admins')->where('user_name', $param['user_name'])->where('id', '<>', $param['id'])->find();
            if (!empty($has)) {
                return json(['code' => -1, 'data' => '', 'msg' => '该管理员已经存在']);
            }

            if ($param['group_id'] == 0) {
                return json(['code' => -2, 'data' => '', 'msg' => '请选择分组']);
            }

            // 修改用户密码
            if (empty($param['password'])) {
                unset($param['password']);
            } else {
                $param['password'] = md5($param['password'] . config('salt'));
            }

            try {
                db('admins')->where('id', $param['id'])->update($param);
            } catch (\Exception $e) {
                return json(['code' => -3, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '编辑管理员成功']);
        }

        $id = input('param.id/d');
        $info = db('admins')->where('id', $id)->find();
        $admingroup = db('admingroup')->where('status',1)->select();

        $this->assign([
            'info' => $info,
            'admingroup' => $admingroup,
            'status' => config('kf_status')
        ]);
        return $this->fetch('editadmin');
    }

    // 删除管理员
    public function delAdmin()
    {
        if (request()->isAjax()) {
            $id = input('param.id/d');
            //return $id;

            try {
                db('admins')->where('id', $id)->delete();
            } catch (\Exception $e) {
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '删除管理员成功']);
        }
    }

    // 权限组
    public function power()
    {
        if (request()->isAjax()) {

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $result = db('admingroup')->limit($offset, $limit)->select();
            foreach ($result as $key => $vo) {
                // 优化显示状态

                if(1 == $vo['status']){
                    $result[$key]['status'] = '<span style="color: #2fbe1b">启用</span>';
                }else{
                    $result[$key]['status'] = '<span style="color: red">禁用</span>';
                }

//                if (1 == $vo['status']) {
//                    $result[$key]['status'] = '<span class="label label-primary">启用</span>';
//                } else {
//                    $result[$key]['status'] = '<span class="label label-danger">禁用</span>';
//                }

                // 上次登录时间
                $result[$key]['addtime'] = date('Y-m-d H:i:s', $vo['addtime']);

                // 生成操作按钮
                if (1 != $vo['group_id']) {
                    $result[$key]['operate'] = $this->makeBtnPower($vo['group_id']);
                }
            }

            $return['total'] = db('admingroup')->count();  //总数据
            $return['rows'] = $result;

            return json($return);

        }
        return $this->fetch();
    }

    // 添加权限组
    public function addpower()
    {
        if (request()->isPost()) {
            $menu = db('menu')->select();
            $param = input('post.');

            $has = db('admingroup')->where('group_name', $param['group_name'])->find();
            if (!empty($has)) {
                return json(['code' => -1, 'data' => '', 'msg' => '该权限组已经存在']);
            }
            $info=array();
            $info['group_name'] = $param['group_name'];
            $info['status'] = $param['status'];
            $info['addtime'] = time();
            try {
                $group_id = db('admingroup')->insertGetId($info);
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }

            $data=array();
            for($i=0;$i<count($menu);$i++){
                if($param[$menu[$i]['name_cn']] != 0){
                    $data[]  = [
                        'group_id' => $group_id,
                        'menu_id' => $param[$menu[$i]['name_cn']],
                    ] ;
                }
            }
            if(!empty($data)){
                try {
                    db('admingrouppower')->where('group_id',$param['group_id'])->delete();
                    db('admingrouppower')->insertAll($data);
                } catch (\Exception $e) {
                    return json(['code' => -3, 'data' => '', 'msg' => $e->getMessage()]);
                }
            }

            return json(['code' => 1, 'data' => '', 'msg' => '添加权限组成功']);
        }
        $menu = db('menu')->where('p_id',0)->select();
        $menulist = db('menu')->where('p_id','<>',0)->select();
        for($i=0;$i<count($menu);$i++){
            for($j=0;$j<count($menulist);$j++){
                $menulist[$j]['class'] = $menu[$i]['ico'];
                if($menu[$i]['id'] == $menulist[$j]['p_id']){
                    $menu[$i]['menulist'][$j] = $menulist[$j];
                }
            }
        }

        $this->assign([
            'info' => $menu,
            'status' => config('kf_status')
        ]);

        return $this->fetch();
    }

    // 编辑权限组
    public function editpower()
    {
        // 权限组id
        $id = input('param.id/d');
        if (request()->isAjax()) {

            $menu = db('menu')->select();
            $param = input('post.');

            $has = db('admingroup')->where('group_name',$param['group_name'])->where('group_id','<>',$param['group_id'])->find();
            if (!empty($has)) {
                return json(['code' => -1, 'data' => '', 'msg' => '该权限组已经存在']);
            }
            $info=array();
            $info['group_name'] = $param['group_name'];
            $info['status'] = $param['status'];
            $info['addtime'] = time();

            $data=array();
            for($i=0;$i<count($menu);$i++){
                if($param[$menu[$i]['name_cn']] != 0){
                    $data[]  = [
                        'group_id' => $param['group_id'],
                        'menu_id' => $param[$menu[$i]['name_cn']],
                    ] ;
                }
            }
            $admingrouppower = db('admingrouppower')->where('group_id',$param['group_id'])->select();
            try {
                db('admingroup')->where('group_id',$param['group_id'])->update($info);
                if(!empty($admingrouppower)){
                    db('admingrouppower')->where('group_id',$param['group_id'])->delete();
                }
                if(!empty($data)){
                    db('admingrouppower')->insertAll($data);
                }
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => '', 'msg' => '编辑权限组成功']);
        }
        $menu = db('menu')->where('p_id',0)->select();
        $menulist = db('menu')->where('p_id','<>',0)->select();
        $adminmenu = db('admingrouppower')->where('group_id', $id)->select();
        for($i=0;$i<count($menu);$i++){
            $n = 0;
            for($a=0;$a<count($adminmenu);$a++){
                if($menu[$i]['id'] == $adminmenu[$a]['menu_id']){
                    $n = 1;
                }
            }
            if($n == 1){
                $menu[$i]['power'] = 1;
            }else{
                $menu[$i]['power'] = 0;
            }
            for($j=0;$j<count($menulist);$j++){
                $num = 0;
                $menulist[$j]['class'] = $menu[$i]['ico'];
                for($b=0;$b<count($adminmenu);$b++){
                    if($menulist[$j]['id'] == $adminmenu[$b]['menu_id']){
                        $num = 1;
                    }
                }
                if($num == 1){
                    $menulist[$j]['power'] = 1;
                }else{
                    $menulist[$j]['power'] = 0;
                }
                if($menu[$i]['id'] == $menulist[$j]['p_id']){
                    $menu[$i]['menulist'][$j] = $menulist[$j];
                }
            }
        }
        $admingroup = db('admingroup')->where('group_id',$id)->find();

        $this->assign([
            'info' => $menu,
            'id' => $id,
            'admingroup' => $admingroup,
            'status' => config('kf_status')
        ]);
        return $this->fetch();
    }

    // 删除权限组
    public function delPower()
    {
        if (request()->isAjax()) {
            $id = input('param.id/d');
            //return $id;

            try {
                db('admingroup')->where('group_id', $id)->delete();
                db('admingrouppower')->where('group_id', $id)->delete();
            } catch (\Exception $e) {
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '删除权限组成功']);
        }
    }

    // 生成管理员操作按钮
    private function makeBtn($id)
    {
        $operate = '<a href="' . url('admins/editadmin', ['id' => $id]) . '">';
//        $operate .= '<button type="button" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 编辑</button></a> ';
        $operate .= '<button type="button" class="btn btn-primary btn-sm"> 编辑</button></a> ';

        $operate .= '<a href="javascript:adminDel(' . $id . ')"><button type="button" class="btn btn-danger btn-sm">';
//        $operate .= '<i class="fa fa-trash-o"></i> 删除</button></a> ';
        $operate .= ' 删除</button></a> ';

        return $operate;
    }

    // 生成权限组操作按钮
    private function makeBtnPower($id)
    {
        $operate = '<a href="' . url('admins/editpower', ['id' => $id]) . '">';
//        $operate .= '<button type="button" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 编辑</button></a> ';
        $operate .= '<button type="button" class="btn btn-primary btn-sm"> 编辑</button></a> ';

        $operate .= '<a href="javascript:powerDel(' . $id . ')"><button type="button" class="btn btn-danger btn-sm">';
//        $operate .= '<i class="fa fa-trash-o"></i> 删除</button></a> ';
        $operate .= ' 删除</button></a> ';

        return $operate;
    }
}
