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

class Settings extends Base
{
    // 访客端入口列表
    public function entranceList()
    {
        if(request()->isAjax()){
            // 查询目录下所有文件
            $files = $this->allFile(ROOT_PATH.'entranceJs/new');
            $filesInfo = [];
            foreach ($files as $v) {
                $addTime = filemtime(ROOT_PATH."entranceJs/new/$v");
                $lastLoad = fileatime(ROOT_PATH."entranceJs/new/$v");
                $filesInfo[] = (object)[
                    'fileName' => $v,
                    'addTime' => date("Y-m-d H:i:s",$addTime),
                    'lastLoad' => date("Y-m-d H:i:s",$lastLoad),
                    'operate' => $this->fileBtn($v),
                ];
            }
            $return = (object)[
                'total' => count($filesInfo),
                'rows' => $filesInfo,
            ];
            return json($return);
        }

        return $this->fetch('entrancelist');
    }
    // 访客端入口新增
    public function index()
    {
        if(request()->isPost()){
            $param = input('post.');
            $name = $param['name'];
            // 查询目录下所有文件
            $files = $this->allFile(ROOT_PATH.'entranceJs/new');
            $have = 0;
            // 判断是否存在该文件.
            foreach ($files as $v) {
                $fileName = substr($v,0,strpos($v, '.'));
                if ($fileName == $name) {
                    $have = 1;
                    break;
                }
            }
            if ($have) {
                return json(['code' => -2, 'data' => '', 'msg' => '文件名已存在']);
            }
            $result = db('guestenter')->order('sort','asc')->select();
            $copy = $this->file2dir(ROOT_PATH.'entranceJs/FloatingButton.js',ROOT_PATH.'entranceJs/new/', $name.'.js');
            $result[] = (object)[
                "margin_top" => $param['marginTop'],
                "stop_time" => $param['overtime'],
                "copywriting" => $param['overtimeInfo'],
            ];
            $data = json_encode($result);
            if ($copy) {
                $dataArr = ["data = $data;"];
                $result = $this->UpdataFile(ROOT_PATH.'entranceJs/new/'.$name.'.js', $dataArr, 24, 24, false);
                if ($result) {
                    return json(['code' => 1, 'data' => 'settings/index', 'msg' => '入口添加成功']);
                } else {
                    return json(['code' => -2, 'data' => '', 'msg' => '操作失败']);
                }
            } else {
                return json(['code' => -2, 'data' => '', 'msg' => '操作失败']);
            }
        }
        if(request()->isAjax()){
            $param  = input('param.');
            $limit  = $param['pageSize'];
            $offset = (($param['pageNumber'] - 1) * $limit);
            $where = [];
            $result = db('guestenter')->where($where)->limit($offset, $limit)->order('sort', 'asc')->select();
            //客服组
            $group = db('groups')->select();
            foreach($result as $key=>$vo){
                // 优化显示头像
                $result[$key]['image'] = '<img src="' . $vo['image'] . '" height="40px">';

                if($vo['group_id'] == 'all'){
                    $result[$key]['user_group'] = '所有客服组';
                }
                for($i=0;$i<count($group);$i++){
                    if($vo['group_id'] == $group[$i]['id']){
                        $result[$key]['user_group'] = $group[$i]['name'];
                    }
                }

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

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

            return json($return);

        }
        $settings = db('settings')->where('id',1)->find();

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

        return $this->fetch();
    }
    // 访客端入口列表
    public function add()
    {
        if(request()->isAjax()){
            $param  = input('param.');
            $limit  = $param['pageSize'];
            $offset = (($param['pageNumber'] - 1) * $limit);
            $where = [];
            $result = db('guestenter')->where($where)->limit($offset, $limit)->order('sort', 'asc')->select();
            //客服组
            $group = db('groups')->select();
            foreach($result as $key=>$vo){
                // 优化显示头像
                $result[$key]['image'] = '<img src="' . $vo['image'] . '" height="40px">';

                if($vo['group_id'] == 'all'){
                    $result[$key]['user_group'] = '所有客服组';
                }
                for($i=0;$i<count($group);$i++){
                    if($vo['group_id'] == $group[$i]['id']){
                        $result[$key]['user_group'] = $group[$i]['name'];
                    }
                }

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

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

            return json($return);

        }
        $settings = db('settings')->where('id',1)->find();

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

        return $this->fetch();
    }

    // 编辑访客端入口
    public function edit()
    {
        if(request()->isAjax()){

            $param = input('post.');
            unset($param['file']); // 删除layui头像上传隐藏字段

            if(strlen($param['name'])>12) {
                return json(['code' => -8, 'data' => '', 'msg' => '名称字数超过限制']);
            }

            if(!is_numeric($param['sort'])) {
                return json(['code' => -6, 'data' => '', 'msg' => '排序未输入整数']);
            }

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

            $name = db('guestenter')->where('name',$param['name'])->where('id','<>',$param['id'])->select();
            if(!empty($name)){
                return json(['code' => -3, 'data' => '', 'msg' => '此名称已存在']);
            }

            $info = array();
            $info['name'] = $param['name'];
            $info['image'] = $param['image'];
            $info['group_id'] = $param['group_id'];
            $info['sort'] = $param['sort'];

            try{
                db('guestenter')->where('id', $param['id'])->update($info);
            }catch(\Exception $e){
                return json(['code' => -6, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => 'settings/index', 'msg' => '编辑功能菜单成功']);
        }
        $id = input('param.id/d');
        $info = db('guestenter')->where('id', $id)->find();

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

    // 删除访客端入口
    public function del()
    {
        if(request()->isAjax()){
            $id = input('param.id/d');

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

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

    // 删除访客端入口文件
    public function delFile()
    {
        if(request()->isAjax()){
            $fileName = input('param.fileName');

            try{
                unlink(ROOT_PATH."entranceJs/new/$fileName");
            }catch(\Exception $e){
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }

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

    /**
     * 效果预览
     */
    function demo()
    {
        return $this->fetch();
    }

    // 上传客服头像
    public function upAvatar()
    {
        if(request()->isAjax()) {

            $file = request()->file('file');
            if (!empty($file)) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if ($info) {
                    $src = '/uploads' . '/' . date('Ymd') . '/' . $info->getFilename();
                    return json(['code' => 0, 'data' => ['src' => $src], 'msg' => 'ok']);
                } else {
                    // 上传失败获取错误信息
                    return json(['code' => -1, 'data' => '', 'msg' => $file->getError()]);
                }
            }
        }
    }

    // 生成按钮
    private function makeBtn($id)
    {
        $operate = '<a href="' . url('settings/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;
    }

    // 生成按钮
    private function fileBtn($fileName)
    {

        $operate = '<a style="margin-left:5px;" href="javascript:DelFile(`' . $fileName . '`)"><button type="button" class="btn btn-danger btn-sm">';
        $operate .= ' 删除</button></a> ';

        return $operate;
    }
    //复制文件
    function file2dir($sourcefile, $dir,$filename){
        if( ! file_exists($sourcefile)){
            return false;
        }
        //$filename = basename($sourcefile);
        return copy($sourcefile, $dir .''. $filename);
    }
    // 获取文件夹下的文件.
    function allFile($dir) {
        $handle=opendir($dir);
        $i=0;
        $list = [];
        while(!!$file = readdir($handle)) {
            if (($file!=".")and($file!="..")) {
                $list[$i]=$file;
                $i=$i+1;
            }
        }
        closedir($handle);
        return $list;
    }

    /**
     * 修改文件
     * @author GRACE
     * @param $file       文件路径
     * @param $arr        修改值数组
     * @param $len        开始索引位置
     * @param $end        结束索引位置 或 匹配 索引值
     * @param bool $loke  文件为空时，是否添加 <?php 头
     */
    function UpdataFile ($file, $arr, $len, $end, $loke = true)
    {
        if (is_dir($file)) {
            exit($file. '请传入正确的文件路径');
        }
        if (is_file($file)) {
            // 判断是否是常规文件
            if (is_readable($file)) {
                // 文件是否可读
                if (is_writable($file)) {
                    // 文件是否可写
                    $fp = file($file);
                    // 以数据的方式读取文件
                    if (!empty($fp)) {
                        $lokes = true;
                        $arr1 = [];
                        // 接收前半部分
                        $arr2 = [];
                        // 接收后半部分
                        foreach ($fp as $k => $v) {
                            if ($k >= $len && $lokes) {
                                if (is_int($end)) {
                                    if ($k == $end) {
                                        $lokes = false;
                                    }
                                } else {
                                    if (trim($v) == $end) {
                                        $arr2[] = $v; $lokes = false;
                                    }
                                }
                            } else {
                                if ($lokes) {
                                    $arr1[] = $v;
                                } else {
                                    $arr2[] = $v;
                                }
                            }
                        }
                        $arr3 = join('', $arr1).join(PHP_EOL, $arr).PHP_EOL.join('', $arr2);
                        if (file_put_contents($file, $arr3)) {
                            return '修改成功';
                        } else {
                            return '修改失败';
                        }
                    } else {
                        if ($loke) {
                            $a = '<?php'.PHP_EOL; $a.= join(PHP_EOL, $arr).PHP_EOL; file_put_contents($file, $a, FILE_APPEND);
                        } else {
                            $a = join(PHP_EOL, $arr).PHP_EOL; file_put_contents($file, $a, FILE_APPEND);
                        }
                    }
                } else {
                    exit($file. 'The file is not writable');
                }
            } else {
                exit($file. ' is not a regular file');
            }
        } else {
            exit($file. ' is not a regular file');
        }
    }

}
