<?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 (strlen($param['searchText'])) {
                $arr = explode("|", $param['searchText']);
                if (count($arr) == 5) {
                    list($timerang, $sendtype, $groupid, $txttype, $txttext) = $arr;
                    if (strlen($timerang)) {
                        list($tbegin, $tend) = explode(",", $timerang);
                        $bibao = true;
                        $biaaodata = [trim($tbegin . '00:00:00'), trim($tend . ' 23:59:59')];
                    }

                    if (intval($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 (strlen($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('sendtime', '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('sendtime', 'desc')->select();
            }

            //管理员
            $admins = db('admins')->select();
            $adminKey = [] ;
            foreach ($admins as $nowadmin){
                $adminKey[$nowadmin['id']] = $nowadmin;
            }

            //客服
            $users = db('users')->select();
            $userKey = [] ;
            foreach ($users as $nowuser){
                $userKey[$nowuser['id']] = $nowuser;
            }


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

                $result[$key]['user_name'] =  isset($userKey[$vo['uid']]) ? $userKey[$vo['uid']]['user_name'] : $result[$key]['uid'] ;


                $date = explode(' ',$vo->ctime);
                $year = explode('-',$vo->ctime);
                if($date[0] == date('Y-m-d',time())){
                    $result[$key]['ctime'] = '<span style="float: right;">'.$date[1].'</span>';
                }else if($date[0] == date('Y-m-d',strtotime("-1 day"))){
                    $result[$key]['ctime'] = '<span style="float: right;">'.'昨天 '.$date[1].'</span>';
                }else{
                    if($year[0] == date('Y',time())){
                        $result[$key]['ctime'] = '<span style="float: right;">'.date('m-d H:i:s',strtotime($vo->ctime)).'</span>';
                    }
                }

                $date = explode(' ',$vo->readtime);
                $year = explode('-',$vo->readtime);
                if($date[0] == date('Y-m-d',time())){
                    $result[$key]['readtime'] = '<span style="float: right;">'.$date[1].'</span>';
                }else if($date[0] == date('Y-m-d',strtotime("-1 day"))){
                    $result[$key]['readtime'] = '<span style="float: right;">'.'昨天 '.$date[1].'</span>';
                }else{
                    if($year[0] == date('Y',time())){
                        $result[$key]['readtime'] = '<span style="float: right;">'.date('m-d H:i:s',strtotime($vo->readtime)).'</span>';
                    }
                }

                $date = explode(' ',$vo->sendtime);
                $year = explode('-',$vo->sendtime);
                if($date[0] == date('Y-m-d',time())){
                    $result[$key]['sendtime'] = '<span style="float: right;">'.$date[1].'</span>';
                }else if($date[0] == date('Y-m-d',strtotime("-1 day"))){
                    $result[$key]['sendtime'] = '<span style="float: right;">'.'昨天 '.$date[1].'</span>';
                }else{
                    if($year[0] == date('Y',time())){
                        $result[$key]['sendtime'] = '<span style="float: right;">'.date('m-d H:i:s',strtotime($vo->sendtime)).'</span>';
                    }
                }
            }

            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 (!strlen($atext) || !strlen($title)) {
                return json(['code' => -1, 'data' => '', 'msg' => '标题和内容不能为空']);
            }

            $sendtime = input('post.sendtime');
            if (!strlen($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,
                    'admin_id' => session('user_id'),
                ];
                $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,
                        'admin_id' => session('user_id'),
                    ];
                    $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 .= ' <a href="javascript:Del(' . $id . ')"><button type="button" class="btn btn-danger btn-sm">';
        $operate .= ' 删除</button></a> ';

        return $operate;
    }
}
