<?php
/**
 * User: nickbai
 * Date: 2017/10/23 13:33
 * Email: 1902822973@qq.com
 */

namespace app\admin\controller;

use app\admin\model\Servicenotice as ServicenoticeModel;
use app\admin\model\Users as Usersmodel;
use app\admin\model\Groups as GroupsModel;

class Kfnotice extends Base
{
    // 管理员列表
    public function index()
    {

        if (request()->isAjax()) {

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


            $where = [];
            $bibao = false;
            if (!empty($param['searchText'])) {
                $arr = explode("|", $param['searchText']);
                if (count($arr) == 5) {
                    list($timerang, $sendtype, $groupid, $txttype, $txttext) = $arr;
                    if (!empty($timerang)) {
                        list($tbegin, $tend) = explode(",", $timerang);
                         $bibao = true;
                         $biaaodata =  [$tbegin, $tend.' 23:59:59'];
                    }

                    if ($sendtype) {
                        $where['sendtype'] = intval($sendtype);
                    }

                    if ($groupid) {
                        $gm = (new GroupsModel())->with('users')->where(['id' => $groupid])->find();
                        $uids = [0];
                        if ($gm && count($gm->users)) {
                            foreach ($gm->users as $u) {
                                $uids[] = $u->id;
                            }
                        }
                        $where['uid'] = ['IN', $uids];
                    }


                    if (!empty($txttext)) {
                        if ($txttype == 1) {
                            $where['title'] = ['like', '%' . $txttext . '%'];
                        } else {
                            $where['atext'] = ['like', '%' . $txttext . '%'];
                        }
                    }

                }
            }

            $model = new ServicenoticeModel();
            if (!$bibao){
                $result = $model->where($where)->limit($offset, $limit)->order('id', 'desc')->select();
            }else{
                $result = $model->where($where)->where(function($query)use ($biaaodata){ $query->where(['sendtime'=>['>=',$biaaodata['0']]])->where(['sendtime'=>['<=',$biaaodata['1']]]);  })->limit($offset, $limit)->order('id', 'desc')->select();
            }

            foreach ($result as $key => $vo) {
                $vo->readtime = empty($vo->readtime) ? '' : date('Y-m-d H:i:s', $vo->readtime);
                $vo->uid = $vo->kfuser->user_name;
                unset($vo->kfuser);
                $vo->sendtype = $vo->sendtype == 1 ? '即时发送' : '预约发送';
                $result[$key] = array_merge($vo->toArray(), ['operate' => $this->makeBtn($vo->id)]);
            }

            if (!$bibao){
                $return['total'] = db('servicenotice')->where($where)->count();  //总数据
            }else{
                $return['total'] = $model->where($where)->where(function($query)use ($biaaodata){ $query->where(['sendtime'=>['>=',$biaaodata['0']]])->where(['sendtime'=>['<=',$biaaodata['1']]]);  })->count();
            }

            $return['rows'] = $result;

            return json($return);

        }

        $goups = (new GroupsModel)->where(['status' => 1])->select();
        $this->assign('groups', $goups);

        return $this->fetch();
    }

    // 添加留言
    public function add()
    {
        $uid = intval(input('param.uid', 0));

        if (request()->isPost()) {

            $atext = input('post.atext');
            $title = input('post.title', 0);
            $group = intval(input('post.groupid', 0));


            if (empty($atext) || empty($title)) {
                return json(['code' => -1, 'data' => '', 'msg' => '标题和内容不能为空']);
            }

            $sendtime = input('post.sendtime');
            if (empty($sendtime)) {
                $sendtime = date("Y-m-d H:i:s", time() + 10);
            }
            $sendtype = (strtotime($sendtime) >= (time() + 60)) ? 2 : 1;
            if (strtotime($sendtime) < time()) {
                return json(['code' => -1, 'data' => '', 'msg' => '时间不能小于当前时间!']);
            }


            if ($uid) {
                $arr = [
                    'uid' => $uid,
                    'title' => $title,
                    'atext' => $atext,
                    'sendtime' => $sendtime,
                    'sendtype' => $sendtype,
                ];
                $datas[] = $arr;
            } else {
                $where = $group ? ['status' => 1, 'group_id' => $group] : ['status' => 1];
                $Users = (new Usersmodel())->where($where)->select();

                if (!$Users) {
                    return json(['code' => -2, 'data' => '', 'msg' => '没有可用客服']);
                }

                $datas = [];
                foreach ($Users as $val) {
                    $arr = [
                        'uid' => $val->id,
                        'title' => $title,
                        'atext' => $atext,
                        'sendtime' => $sendtime,
                        'sendtype' => $sendtype,
                    ];
                    $datas[] = $arr;
                }
            }

            try {
                db('servicenotice')->insertAll($datas);
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => '', 'msg' => '添加公告成功']);
        }

        $goups = (new GroupsModel)->where(['status' => 1])->select();
        $this->assign('groups', $goups);
        $this->assign('userid', $uid);

        return $this->fetch();
    }


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

            try {
                db('servicenotice')->where('id', $id)->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="javascript:View(' . $id . ')"><button type="button" class="btn btn-info btn-sm">详细内容 </button></a>';
        $operate .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:Del(' . $id . ')"><button type="button" class="btn btn-danger btn-sm">';
        $operate .= '<i class="fa fa-trash-o"></i> 删除</button></a> ';

        return $operate;
    }
}