<?php
/**
 * Created by PhpStorm.
 * User: Jonlin
 * Date: 2019/6/27
 * Time: 10:15
 */
namespace app\admin\controller;

class Messages extends Base
{
    // 留言列表
    public function index()
    {
        if(request()->isAjax()){

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

            $where  = [];
            $orwhere  = [];
            //用户名称
            if (strlen($param['searchText'])) {
                $where['a.name'] = array('like','%'.$param['searchText'].'%');
                $orwhere['name'] = array('like','%'.$param['searchText'].'%');
            }
            //处理客服id
            if (empty($param['user_id']) === false) {
                $where['a.user_id'] = $param['user_id'];
                $orwhere['user_id'] = $param['user_id'];
            }
            //留言状态
            if ($param['message_status'] != '' && $param['message_status'] != -1) {
                $where['a.message_status'] = $param['message_status'];
                $orwhere['message_status'] = $param['message_status'];
            }
            //公开状态
            if ($param['if_public'] != '' && $param['if_public'] != -1) {
                $where['a.if_public'] = $param['if_public'];
                $orwhere['if_public'] = $param['if_public'];
            }
            //留言类型id
            if (empty($param['type_id']) === false) {
                $where['a.type_id'] = $param['type_id'];
                $orwhere['type_id'] = $param['type_id'];
            }
            $return['total'] = db('Accountsmessage')->where($orwhere)->count();  //总数据
            if (strlen($param['start']) && strlen($param['end']) && $param['start'] <= $param['end']) {
                $start = strtotime($param['start']);
                $end = strtotime($param['end'] . ' 23:59:59');
                $return['total'] = db('Accountsmessage')->whereBetween('add_time', [$start, $end])->where($orwhere)->count();  //总数据
            }
            $join   = [
                'messagetype b'      => 'a.type_id = b.id',
            ];
            $leftjoin   = [
                'users c'      => 'a.user_id = c.id',
            ];
            $result = model('Accountsmessage')->selectJoin($join,$leftjoin,$where, $start,$end,$offset, $limit);
            foreach($result as $key=>$vo){

                if(!empty($result[$key]['image'])){
                    // 优化显示附件
                    $images = $result[$key]['image'];
                    //转换成数组格式
                    $images = explode(",", $images);
                    if(!empty($images)){
                        $img = '';
                        for($i=0;$i<count($images);$i++){
                            $img = $img.'<img src="'.$images[$i].'" width="40px" height="40px" style="margin-left:5px;margin-top:5px;">';
                        }
                        $result[$key]['image'] = $img;
                    }
                }
                
                // 优化时间
                if(null != $vo['add_time']){
                    $result[$key]['add_time'] = date('Y-m-d H:m:s',$result[$key]['add_time']);
                }
                if(null != $vo['dealWith_time']){
                    $result[$key]['dealWith_time'] = date('Y-m-d H:m:s',$result[$key]['dealWith_time']);
                }

                // 优化显示状态
                if(1 == $vo['message_status']) {
                    $result[$key]['status'] = '<span style="color: #2fbe1b">已处理</span>';
                } else {
                    $result[$key]['status'] = '<span style="color: red">未处理</span>';
                }

                // 是否公开
                if(1 == $vo['if_public']){
                    $result[$key]['if_public'] = '公开';
                }else{
                    $result[$key]['if_public'] = '不公开';
                }
                // 生成操作按钮
                $result[$key]['operate'] = $this->makeBtn($vo['message_id']);
            }

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

            return json($return);

        }
        //所有客服
        $users = db('users')->select();
        $useroption = '';
        if(!empty($users)){
            $option = '<option value="0">处理人</option>';
            for($i=0;$i<count($users);$i++){
                $option = $option.'<option value="'.$users[$i]['id'].'">'.$users[$i]['user_name'].'</option>';
            }
            $useroption = '<select lay-verify="required" lay-filter="user_id">'.$option.'</select>';
        }

        //留言类型
        $type = db('messagetype')->where('status',1)->select();
        $optiontype = '';
        if(!empty($users)){
            $option = '<option value="0">留言类型</option>';
            for($i=0;$i<count($type);$i++){
                $option = $option.'<option value="'.$type[$i]['id'].'">'.$type[$i]['name'].'</option>';
            }
            $optiontype = '<select lay-verify="required" lay-filter="type_id">'.$option.'</select>';
        }

        $this->assign([
            'useroption' => $useroption,
            'optiontype' => $optiontype
        ]);

        return $this->fetch();
    }

    // 留言详情
    public function detail()
    {
        if(request()->isAjax()) {
            //设置留言公开/不公开
            $param = input('post.');
            $id = $param['id'];
            $if_public = $param['if_public'];
            $type_id = $param['type_id'];
            $message = db('accountsmessage')->where('message_id', $id)->find();
            if(!empty($message)){
                if($message['message_status'] == 0){
                    return json(['code' => -1, 'data' => '', 'msg' => '留言未处理']);
                }
            }

            if($type_id == -1){
                return json(['code' => -2, 'data' => '', 'msg' => '请选择留言类别']);
            }
            try{
                db('accountsmessage')->where('message_id', $id)->update(['if_public' => $if_public,'type_id' => $type_id]);
            }catch(\Exception $e){
                return json(['code' => -3, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => url('messages/index'), 'msg' => '设置成功']);
        }
        $id = input('param.id/d');
        $info = db('Accountsmessage')->where('message_id', $id)->find();
        //$account = db('Accounts')->where('id', $info['account_id'])->find();
        $user = db('Users')->where('id', $info['user_id'])->find();
        //$info['account_name'] = $account['account_name'];
        //$info['account_email'] = $account['account_email'];
        $info['user_name'] = $user['user_name'];

        $messagetype = db('messagetype')->select();

        // 优化显示附件
        $images = $info['image'];
        //转换成数组格式
        $images = explode(",", $images);
        if(!empty($images)){
            $img = '';
            for($i=0;$i<count($images);$i++){
                $img = $img.'<img src="'.$images[$i].'" width="240px" style="margin-top:20px;">';
            }
            $info['image'] = $img;
        }

        // 优化时间
        if (null != $info['add_time']) {
            $info['add_time'] = date('Y-m-d H:m:s', $info['add_time']);
        }
        if (null != $info['dealWith_time']) {
            $info['dealWith_time'] = date('Y-m-d H:m:s', $info['dealWith_time']);
        }

        // 优化显示状态
        if (1 == $info['message_status']) {
            $info['message_status'] = '已处理';
        } else {
            $info['message_status'] = '未处理';
        }

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

    //删除留言
    public function delMessage(){
        if (request()->isAjax()) {
            //留言类型id
            $id = input('param.id/d');

            try {
                db('accountsmessage')->where('message_id', $id)->delete();
            } catch (\Exception $e) {
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => '', 'msg' => '删除留言成功']);
        }
    }

    // 上传客服头像
    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('Messages/detail', ['id' => $id]) . '">';

        $operate .= '<button type="button" class="btn btn-info btn-sm">详情</button></a>';

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

        return $operate;
    }



    // 留言类型列表
    public function type()
    {
        if(request()->isAjax()){

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

//            $where  = [];
//            if (strlen($param['searchText'])) {
//                $where['account_name'] = $param['searchText'];
//            }

            $result = db('messagetype')->limit($offset, $limit)->select();
            foreach($result as $key=>$vo){
                // 优化时间
                if(null != $vo['addtime']){
                    $result[$key]['addtime'] = date('Y-m-d H:m:s',$result[$key]['addtime']);
                }

//                // 优化显示状态
//                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>';
                }

                // 生成操作按钮
                $result[$key]['operate'] = $this->makeBtnType($vo['id']);
            }
            $return['total'] = db('messagetype')->count();  //总数据
            $return['rows'] = $result;

            return json($return);
        }
        return $this->fetch();
    }

    // 添加留言类型
    public function add()
    {
        if (request()->isAjax()) {
            $param = input('post.');
            $has = db('messagetype')->where('name',$param['name'])->find();
            if(!empty($has)){
                return json(['code' => -1, 'data' => '', 'msg' => '此留言类型已存在']);
            }
            $info = array();
            $info['name'] = $param['name'];
            $info['addtime'] = time();
            $info['status'] = $param['status'];
            try {
                db('messagetype')->insert($info);
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => url('messages/type'), 'msg' => '添加留言类型成功']);
        }
        $this->assign([
            'status' => config('kf_status')
        ]);
        return $this->fetch();
    }

    // 编辑留言类型
    public function edit()
    {
        // 菜单id
        $id = input('param.id/d');
        if (request()->isAjax()) {
            $param = input('post.');
            $has = db('messagetype')->where('name',$param['name'])->where('id','<>',$id)->find();
            if(!empty($has)){
                return json(['code' => -1, 'data' => '', 'msg' => '此留言类型已存在']);
            }
            $info = array();
            $info['name'] = $param['name'];
            $info['status'] = $param['status'];

            try {
                db('messagetype')->where('id', $param['id'])->update($info);
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => url('messages/type'), 'msg' => '编辑留言类型成功']);
        }
        $type = db('messagetype')->where('id',$id)->find();

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

    // 删除留言类型
    public function delType()
    {
        if (request()->isAjax()) {
            //留言类型id
            $id = input('param.id/d');

            try {
                db('messagetype')->where('id', $id)->delete();
            } catch (\Exception $e) {
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => '', 'msg' => '删除留言类型成功']);
        }
    }

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

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

        return $operate;
    }
}
