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

use think\Loader;
use think\Controller;

class Words extends Base
{
    // 常用语列表
    public function index()
    {
        if(request()->isAjax()){

            $param = input('param.');

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

            $where['user_id'] = $param['type'] == 1? 0 : ['neq',0];
            if (strlen($param['searchText'])) {
                $where['content'] = ['like', '%' . $param['searchText'] . '%'];
            }

            $result = db('words')
                ->field(['a.id', 'title', 'content', 'update_time', 'user_name', 'a.status'])
                ->alias('a')
                ->join('admins b', 'a.admin_id = b.id','left')
                ->where($where)
                ->limit($offset, $limit)
                ->select();
            foreach($result as $key=>$vo){
                // 优化显示状态
//                if(1 == $vo['status']){
//                    $result[$key]['status'] = '<span class="label label-primary">启用</span>';
//                }else{
//                    $result[$key]['status'] = '<span class="label label-danger">禁用</span>';
//                }

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

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

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

            return json($return);

        }

        return $this->fetch();
    }

    // 添加常用语
    public function addWord()
    {
        if(request()->isPost()){

            $param = input('post.');
            $param['content'] = trim($param['content']);

            $has = db('words')->field('id')->where(['title' => $param['title'], 'user_id' => 0])->find();
            if(!empty($has)){
                return json(['code' => -1, 'data' => '', 'msg' => '该常用语已经存在']);
            }

            $param['update_time'] = date('Y-m-d H:i:s');
            $param['admin_id'] = session('user_id');
            try{
                db('words')->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('addword');
    }

    // 编辑常用语
    public function editWord()
    {
        if(request()->isAjax()){

            $param = input('post.');
            $param['content'] = trim($param['content']);

            $param['update_time'] = date('Y-m-d H:i:s');
            $param['admin_id'] = session('user_id');
            // 检测用户修改的常用语是否重复
            $has = db('words')->where(['title' => $param['title'], 'user_id' => 0])->where('id', '<>', $param['id'])->find();
            if(!empty($has)){
                return json(['code' => -1, 'data' => '', 'msg' => '该常用语已经存在']);
            }

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

            return json(['code' => 1, 'data' => '', 'msg' => '编辑常用语成功']);
        }

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

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

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

            try{
                db('words')->where('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('words')->where('user_id',0)->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('words/editword', ['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]['title'] = $v[0];
                $info[$k]['content'] = $v[1];
                $info[$k]['status'] = $v[2];
                $info[$k]['update_time'] = date('Y-m-d H:m:s',time());
                $info[$k]['user_id'] = 0;
                $info[$k]['admin_id'] = session('user_id');
            }
            //检查表中数据是否为空和重复
            for($a=0;$a<count($info);$a++){
                if(empty($info[$a]['title'])){
                    $this->error('excel表第'.($a+2).'行快捷词为空');
                    return json(['code' => -3, 'data' => url('words/index'), 'msg' => 'excel表第'.($a+2).'行快捷词为空']);
                }
                if(empty($info[$a]['content'])){
                    $this->error('excel表第'.($a+2).'行内容为空');
                    return json(['code' => -4, 'data' => url('words/index'), 'msg' => 'excel表第'.($a+2).'行内容为空']);
                }
                for($b=$a+1;$b<count($info);$b++){
                    if($info[$a]['title'] == $info[$b]['title']){
                        $this->error('excel表第'.($a+2).'行与第'.($b+2).'行快捷词重复');
                        return json(['code' => -1, 'data' => url('words/index'), 'msg' => 'excel表第'.($a+2).'行与第'.($b+2).'行快捷词重复']);
                    }
                }
            }
            //检查表格中数据是否已存在与数据库
            $words = db('words')->where('user_id',0)->select();
            for($i=0;$i<count($info);$i++){
                for($j=0;$j<count($words);$j++){
                    if($info[$i]['title'] == $words[$j]['title']){
                        $this->error('excel表第'.($i+2).'行快捷回复已存在');
                        return json(['code' => -1, 'data' => url('words/index'), 'msg' => 'excel表第'.($i+2).'行快捷回复已存在']);
                    }
                }
            }
            db('words')->insertAll($info); //批量插入数据
            $this->success('导入快捷回复成功');
            return json(['code' => 1, 'data' => $this->redirect('words/index'), 'msg' => '导入快捷回复成功']);
        } else {
            $this->error('导入快捷回复失败');
            return json(['code' => -2, 'data' => url('words/index'), 'msg' => '导入快捷回复失败']);
        }
    }

}
