<?php
namespace app\admin\controller;

use think\Loader;
use think\Controller;

class Sensitivec extends Base
{
	//敏感词管理
    public function index()
    {
    	if (request()->isAjax()) {
            $param  = input('param.');
            $limit  = $param['pageSize'];
            $offset = (($param['pageNumber'] - 1) * $limit);
            $where['sensitivewords_for'] = $param['type'];
            if (strlen($param['searchText'])) {
                $where['sensitivewords_word'] = ['like', '%' . $param['searchText'] . '%'];
            }

            $result = db('sensitivewords')
                ->field(['sensitivewords_id', 'sensitivewords_word', 'sensitivewords_time', 'sensitivewords_status', 'user_name'])
                ->alias('a')
                ->join('admins b', 'a.sensitivewords_uid = b.id','left')
                ->where($where)
                ->limit($offset, $limit)
                ->select();

            foreach ($result as $key => $vo) {
                // 优化显示状态.
                if(1 == $vo['sensitivewords_status']) {
                    $result[$key]['sensitivewords_status'] = '<span style="color: #2fbe1b">启用</span>';
                } else {
                    $result[$key]['sensitivewords_status'] = '<span style="color: red">禁用</span>';
                }

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

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

            return json($return);

        }

    	return $this->fetch();
    }

    //敏感词添加
    public function addsensitive(){
    	if(request()->isPost()){

            $param     = input('post.');
            $findWhere = [
                'sensitivewords_word' => $param['sensitivewords_word'],
                'sensitivewords_for'  => $param['sensitivewords_for'],
            ];

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

            $param['sensitivewords_time'] = date('Y-m-d H:i:s');
            $param['sensitivewords_uid']  = session('user_id');

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

            return json(['code' => 1, 'data' => '', 'msg' => '添加敏感词成功']);
        }

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

        return $this->fetch();
    }

    //敏感词编辑
    public function editsensitive(){
    	if(request()->isAjax()){

            $param = input('post.');

            // 检测用户修改的管理员是否重复
            $has = db('sensitivewords')->where('sensitivewords_word', $param['sensitivewords_word'])->find();
            $thisWord = db('sensitivewords')->where('sensitivewords_id', $param['sensitivewords_id'])->find();
            if(!empty($has) && $has['sensitivewords_id'] != $param['sensitivewords_id'] && $thisWord['sensitivewords_for'] == $has['sensitivewords_for']){
                return json(['code' => -1, 'data' => '', 'msg' => '该敏感词已经存在']);
            }

            $param['sensitivewords_time'] = date('Y-m-d H:i:s');
            $param['sensitivewords_uid'] = session('user_id');//uid

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

            return json(['code' => 1, 'data' => '', 'msg' => '编辑敏感词成功']);
        }

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

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

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

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

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

    //删除所有关键字
    public function delAll(){
        if(request()->isAjax()){
            $type = input('param.type/d');
            if($type == 1){
                $name = '用户';
            }
            if($type == 2){
                $name = '客服';
            }
            try{
                db('sensitivewords')->where('sensitivewords_for', $type)->delete();
            }catch(\Exception $e){
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => '', 'msg' => '删除全部'.$name.'敏感词成功']);
        }
    }

    // 生成按钮
    private function makeBtn($id)
    {
        $operate = '<a href="' . url('sensitivec/editsensitive', ['sensitivewords_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:userDel(' . $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;
    }

    //导入敏感词
    function inserExcel()
    {
        Loader::import('PHPExcel.PHPExcel');
        Loader::import('PHPExcel.PHPExcel.PHPExcel_IOFactory');
        Loader::import('PHPExcel.PHPExcel.PHPExcel_Cell');
        //获取表单上传文件
        $file = request()->file('excel');
        //$file = $_FILES['excel'];
//        return $file;
//        print_r($file) ;

//        if(request()->isAjax()){
//            $file = input('param.file');
//             //return $file;
//        }

        if(empty($file)){
//return  '<script src="/static/admin/js/jquery.min.js?v=2.1.4"></script><script src="/static/admin/js/plugins/layer/layer.min.js"></script><script>layer.msg("请先上传文件123", {icon: 1});console.log(12345);</script>';
            $this->error('请先上传文件');
            return json(['code' => -4, 'data' => '', 'msg' => '请先上传文件']);
        }

        $info = $file->validate(['ext' => 'xlsx'])->move(ROOT_PATH . 'public' . DS . 'uploads');
        //上传验证后缀名,以及上传之后移动的地址
        if ($info) {
//            echo $info->getFilename();
            $exclePath = $info->getSaveName();  //获取文件名
            $file_name = ROOT_PATH . 'public' . DS . 'uploads' . DS . $exclePath;   //上传文件的地址
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            $obj_PHPExcel = $objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8
            $excel_array = $obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
            array_shift($excel_array);  //删除第一个数组(标题);
            $info = [];
            foreach ($excel_array as $k => $v) {
                $info[$k]['sensitivewords_word'] = $v[0];
                $info[$k]['sensitivewords_status'] = $v[1];
                $info[$k]['sensitivewords_for'] = $v[2];
                $info[$k]['sensitivewords_time'] = date('Y-m-d H:m:s',time());
                $info[$k]['sensitivewords_uid'] = session('user_id');
            }
            //检查表中数据是否为空和重复
            for($a=0;$a<count($info);$a++){
                if(empty($info[$a]['sensitivewords_word'])){
                    $this->error('excel表第'.($a+2).'行敏感词为空');
                    return json(['code' => -3, 'data' => url('sensitivec/index'), 'msg' => 'excel表第'.($a+2).'行敏感词为空']);
                }
                for($b=$a+1;$b<count($info);$b++){
                    if($info[$a]['sensitivewords_word'] == $info[$b]['sensitivewords_word'] && $info[$a]['sensitivewords_for'] == $info[$b]['sensitivewords_for']){
                        $this->error('excel表第'.($a+2).'行与第'.($b+2).'行敏感词重复');
                        return json(['code' => -1, 'data' => url('sensitivec/index'), 'msg' => 'excel表第'.($a+2).'行与第'.($b+2).'行敏感词重复']);
                    }
                }
            }
            //检查表格中数据是否已存在与数据库
            $sensitivewords = db('sensitivewords')->select();
            for($i=0;$i<count($info);$i++){
                for($j=0;$j<count($sensitivewords);$j++){
                    if($info[$i]['sensitivewords_word'] == $sensitivewords[$j]['sensitivewords_word'] && $info[$i]['sensitivewords_for'] == $sensitivewords[$j]['sensitivewords_for']){
                        $this->error('excel表第'.($i+2).'行敏感词已存在');
                        return json(['code' => -1, 'data' => url('sensitivec/index'), 'msg' => 'excel表第'.($i+2).'行敏感词已存在']);
                    }
                }
            }
            db('sensitivewords')->insertAll($info); //批量插入数据
            $this->success('插入敏感词成功');
            return json(['code' => 1, 'data' => $this->redirect('sensitivec/index'), 'msg' => '插入敏感词成功']);
        } else {
            $this->error('插入敏感词失败');
            return json(['code' => -2, 'data' => url('sensitivec/index'), 'msg' => '插入敏感词失败']);
        }
    }
}
