<?php
namespace app\admin\controller;

use think\Loader;
use think\Controller;
use think\Db;
/**
 * 智能问答类
 */
class Robot extends Base
{

    /**
     * 智能问答列表
     *
     * @access public
     * @return array JsonString
     */
    public function index()
    {
        if (request()->isAjax()) {
            $param  = input('param.');
            $limit  = $param['pageSize'];
            $offset = (($param['pageNumber'] - 1) * $limit);
            $where  = [];
            if (strlen($param['searchText'])) {
                // $where['robot_name'] = $param['searchText'];
                $where['robot_name'] = ['like', '%' . $param['searchText'] . '%'];
            }

            $field  = ['robot_id', 'robot_name', 'robot_content', 'robot_host', 'robot_status', 'user_name', 'robot_updateTime'];
            $join   = [
                'admins b'      => 'a.admin_id = b.id',
            ];
            $result = model('Robot')->selectJoin($field, $join, $where, $offset, $limit);
            foreach ($result as $key => $vo) {
                // 优化显示状态.
                if(1 == $vo['robot_status']) {
                    $result[$key]['robot_status'] = '<span style="color: #2fbe1b">启用</span>';
                } else {
                    $result[$key]['robot_status'] = '<span style="color: red">禁用</span>';
                }

                // 优化显示热点问题.
                if (1 == $vo['robot_host']) {
                    $result[$key]['robot_host'] = '<span style="color: #2fbe1b">是</span>';
                } else {
                    $result[$key]['robot_host'] = '<span style="color: red">否</span>';
                }

                // 生成操作按钮.
                $result[$key]['operate'] = $this->makeBtn($vo['robot_id']);
            }
// var_dump($where);die;
            // 总数据.
            $return['total'] = model('Robot')->count($where);
            $return['rows'] = $result;

            return json($return);

        }

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


    // 添加智能问答
    public function addWord()
    {
        if(request()->isPost()){

            $param = input('post.');
            $param['robot_content'] = trim($param['robot_content']);
            $robotWhere = [
                'robot_name' => $param['robot_name'],
            ];

            $has = db('robot')->field('robot_id')->where($robotWhere)->find();
            if(!empty($has)){
                return json(['code' => -1, 'data' => '', 'msg' => '该智能问答已经存在']);
            }

            $param['robot_addTime']    = date('Y-m-d H:i:s');
            $param['robot_updateTime'] = date('Y-m-d H:i:s');
            $param['groups_id']        = 1;
            $param['robotgroups_id']   = 1;
            $param['admin_id']         = session('user_id');
            try{
                db('robot')->insert($param);
            }catch(\Exception $e){
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '添加智能问答成功']);
        }
        $groups = db('groups')->where('status', 1)->select();
        $robotgroups = db('robotgroups')->where('robotgroups_status', 1)->select();
        $this->assign([
            'status' => config('kf_status'),
            'host' => config('host'),
            'groups' => $groups,
            'robotgroups' => $robotgroups,
        ]);

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

    // 编辑智能问答
    public function editWord()
    {
        if(request()->isAjax()){

            $param = input('post.');
            $param['robot_content'] = trim($param['robot_content']);
            $param['robot_updateTime'] = date('Y-m-d H:i:s');
            $robotWhere = [
                'robot_name' => $param['robot_name'],
            ];

            // 检测用户修改的智能问答是否重复
            $has = db('robot')->where($robotWhere)->count();
            if($has>1){
                return json(['code' => -1, 'data' => '', 'msg' => '该智能问答已经存在']);
            }
            $param['groups_id'] = 1;
            $param['robotgroups_id'] = 1;
            $param['admin_id']   = session('user_id');

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

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

        $id = input('param.robot_id/d');
        $info = db('robot')->where('robot_id', $id)->find();
        $groups = db('groups')->where('status', 1)->select();
        $robotgroups = db('robotgroups')->where('robotgroups_status', 1)->select();

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

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

            try{
                db('robot')->where('robot_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()){
            try{
                Db::execute("truncate table ws_robot");
            }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('robot/editword', ['robot_id' => $id]) . '">';
        $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 .= ' 删除</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');
        if(empty($file)){
            $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]['robot_name'] = $v[0];
                $info[$k]['robot_content'] = $v[1];
                $info[$k]['robot_status'] = $v[2];
                $info[$k]['robot_host'] = $v[3];
                $info[$k]['groups_id'] = 1;
                $info[$k]['robotgroups_id'] = 1;
                $info[$k]['robot_addTime'] = date('Y-m-d H:m:s',time());
                $info[$k]['robot_updateTime'] = date('Y-m-d H:m:s',time());
                $info[$k]['admin_id'] = session('user_id');
            }
            //检查表中数据是否为空和重复
            for($a=0;$a<count($info);$a++){
                if(empty($info[$a]['robot_name'])){
                    $this->error('excel表第'.($a+2).'行智能问答问题为空');
                    return json(['code' => -3, 'data' => url('robot/index'), 'msg' => 'excel表第'.($a+2).'行智能问答问题为空']);
                }
                if(empty($info[$a]['robot_content'])){
                    $this->error('excel表第'.($a+2).'行智能问答答案为空');
                    return json(['code' => -4, 'data' => url('robot/index'), 'msg' => 'excel表第'.($a+2).'行智能问答答案为空']);
                }
                for($b=$a+1;$b<count($info);$b++){
                    if($info[$a]['robot_name'] == $info[$b]['robot_name']){
                        $this->error('excel表第'.($a+2).'行与第'.($b+2).'行智能问答问题重复');
                        return json(['code' => -2, 'data' => url('robot/index'), 'msg' => 'excel表第'.($a+2).'行与第'.($b+2).'行智能问答问题重复']);
                    }
                }
            }
            //检查表格中数据是否已存在与数据库
            $robot = db('robot')->select();
            for($i=0;$i<count($info);$i++){
                for($j=0;$j<count($robot);$j++){
                    if($info[$i]['robot_name'] == $robot[$j]['robot_name']){
                        $this->error('excel表第'.($i+2).'行智能问答问题已存在');
                        return json(['code' => -1, 'data' => url('robot/index'), 'msg' => 'excel表第'.($i+2).'行智能问答问题已存在']);
                    }
                }
            }
            db('robot')->insertAll($info); //批量插入数据
            $this->success('插入智能问答数据成功');
            return json(['code' => 1, 'data' => $this->redirect('robot/index'), 'msg' => '插入智能问答数据成功']);
        } else {
            $this->error('插入智能问答数据失败');
            return json(['code' => -2, 'data' => url('robot/index'), 'msg' => '插入智能问答数据失败']);
        }
    }
}
