<?php
namespace app\admin\controller;

class Iplimit extends Base
{
    //访问ip管理
    public function index()
    {
        if (request()->isAjax()) {
            $param  = input('param.');
            $limit  = $param['pageSize'];
            $offset = (($param['pageNumber'] - 1) * $limit);
            $where['object'] = $param['type'];
            if (strlen($param['searchText'])) {
                $ip = bindec(decbin(ip2long($param['searchText'])));
                $where['ip'] = ['like', '%' . $param['searchText'] . '%'];
                $res = db('iplimit')->where('start_ip','<',$ip)->where('end_ip','>',$ip)->where('object',$param['type'])->limit($offset, $limit)->select();
            }

            $result = db('iplimit')->where($where)->limit($offset, $limit)->select();
            if(!empty($res)){
                for($i=0;$i<count($res);$i++){
                    $result[] = $res[$i];
                }
            }
//            array_unique($result, SORT_REGULAR);

            $admins = db('admins')->select();
            foreach ($result as $key => $vo) {

                for($i=0;$i<count($admins);$i++){
                    if($vo['admin_id'] == $admins[$i]['id']){
                        $result[$key]['admin'] = $admins[$i]['user_name'];
                    }
                }

                if($vo['ip'] == ''){
                    $result[$key]['ip'] = $result[$key]['start_ip'].' - '.$result[$key]['end_ip'];
                }

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

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

            return json($return);

        }

        return $this->fetch();
    }

    //访问ip添加
    public function add(){
        if(request()->isPost()){

            $param     = input('post.');
            $findWhere = [
                'ip' => $param['ip'],
                'object'  => $param['object'],
            ];

            $has = db('iplimit')->where($findWhere)->find();
            if (empty($has) === false) {
                return json(['code' => -1, 'data' => '', 'msg' => '该ip已经存在']);
            }

            if(strpos($param['ip'], '-') !== false){
                $ip = explode('-',$param['ip']);
                //将ip地址转换成int型
                $param['start_ip'] = bindec(decbin(ip2long($ip[0])));
                $param['end_ip'] = bindec(decbin(ip2long($ip[1])));
            }
            $param['ctime'] = date('Y-m-d H:i:s',time());
            $param['utime']  = date('Y-m-d H:i:s',time());
            $param['admin_id']  = session('user_id');


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

            return json(['code' => 1, 'data' => '', 'msg' => '添加访问ip成功']);
        }

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

        return $this->fetch();
    }

    //访问ip编辑
    public function edit(){
        if(request()->isAjax()){

            $param = input('post.');

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

            if(strpos($param['ip'], '-') !== false){
                $ip = explode('-',$param['ip']);
                //将ip地址转换成int型
                $param['start_ip'] = bindec(decbin(ip2long($ip[0])));
                $param['end_ip'] = bindec(decbin(ip2long($ip[1])));
            }
            $param['ctime'] = date('Y-m-d H:i:s',time());
            $param['utime']  = date('Y-m-d H:i:s',time());
            $param['admin_id']  = session('user_id');

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

            return json(['code' => 1, 'data' => '', 'msg' => '编辑访问ip成功']);
        }

        $id = input('param.id/d');
        $info = db('iplimit')->where('id', $id)->find();

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

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

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

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

    //开启/关闭ip限制
    public function disjunctor(){
        if(request()->isAjax()){
            $disjunctor = input('param.disjunctor');
            $type = input('param.type');
            try{
                if($disjunctor == 'on' && $type == 'kf'){
                    $msg = '开启客服白名单';
                    db('settings')->where('id', 1)->update(['kf_white_list'=>$disjunctor]);
                }
                if($disjunctor == 'off' && $type == 'kf'){
                    $msg = '关闭客服白名单';
                    db('settings')->where('id', 1)->update(['kf_white_list'=>$disjunctor]);
                }
                if($disjunctor == 'on' && $type == 'account'){
                    $msg = '开启用户黑名单';
                    db('settings')->where('id', 1)->update(['account_black_list'=>$disjunctor]);
                }
                if($disjunctor == 'off' && $type == 'account'){
                    $msg = '关闭用户黑名单';
                    db('settings')->where('id', 1)->update(['account_black_list'=>$disjunctor]);
                }
            }catch(\Exception $e){
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => $msg.'成功']);
        }
    }

    // 生成按钮
    private function makeBtn($id)
    {
        $operate = '<a href="' . url('iplimit/edit', ['id' => $id]) . '">';
        $operate .= '<button type="button" class="btn btn-primary btn-sm"> 编辑</button></a> ';

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

        return $operate;
    }

}
