<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use app\common\model\Messages;
use think\Db;
use think\Log;

class Tomessages extends Permissions
{
    public function index()
    {
        if ($this->request->isAjax()) {

            $post = $this->request->param();
            $where = [];
            if (isset($post['id']) and $post['id'] != '') {
                $where['id'] = $post['id'];
            }
            if (isset($post['from_user_id']) and $post['from_user_id'] != '') {
                $where['from_user_id'] = $post['from_user_id'];
            }
            if (isset($post['to_user_id']) and $post['to_user_id'] != '') {
                $where['to_user_id'] = $post['to_user_id'];
            }
            if (isset($post['keywords']) and !empty($post['keywords'])) {
                $where['message'] = ['like', '%' . $post['keywords'] . '%'];
            }
            if (isset($post['ip']) and $post['ip'] != '') {
                $where['ip'] = $post['ip'];
            }
            if (isset($post['is_look']) and ($post['is_look'] == 1 or $post['is_look'] === '0')) {
                $where['is_look'] = $post['is_look'];
            }
            if (isset($post['status']) and in_array($post['status'], ["0", "1", "-1"], true)) {
                $where['status'] = $post['status'];
            }
            if (isset($post['create_time']) and !empty($post['create_time'])) {
                $timerang = explode(' - ', $post['create_time']);
                $min_time = strtotime($timerang[0]);
                $max_time = strtotime($timerang[1]);
                $where['create_time'] = [['>=', $min_time], ['<=', $max_time]];
            }

            $model = new Messages();
            $count = $model->where($where)->count();
            $data = $model->where($where)->page($post['page']??0, $post['limit']??15)->order('create_time desc')->select();

            foreach ($data as $k => $v) {
                $v['from_user'] = $v->fromUser->nickname??($v->from_user_id ?: "系统");
                $v['to_user'] = $v->toUser->nickname??($v->to_user_id ?: '');
                $v['status_text'] = $v->status_text;
                $data[$k] = $v;
            }

            return array('code' => 0, 'count' => $count, 'data' => $data);
        } else {
            return $this->fetch();
        }
    }


    public function publish()
    {
        $id = $this->request->param('id', 0, 'intval');
        $post = $this->request->post();
        if ($this->request->isPost()) {
            $validate = new \think\Validate([
                ['from_user_id|发送者id', 'number'],
                ['to_user_id|接收者id', 'number'],
                ['message', 'require', '消息不能为空'],
            ]);
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }
        }

        $model = new Messages();
        if ($id > 0) {
            //是修改操作
            $link = $model->where('id', $id)->find();
            if (empty($link)) {
                $this->error('记录id不存在');
            }
            if ($this->request->isPost()) {
                if (false == $model->allowField(true)->save($post, ['id' => $id])) {
                    $this->error('修改失败');
                } else {
                    $this->success('修改成功', 'index');
                }
            } else {
                $this->assign('link', $link);
                return $this->fetch();
            }
        } else {
            //是新增操作
            if ($this->request->isPost()) {
                $post['ip'] = $this->request->ip();
                $post['status'] = Messages::STATUS_PASS;
                if (false == $model->allowField(true)->save($post)) {
                    $this->error('失败');
                } else {
                    $this->success('发送成功，请查看消息管理', 'index');
                }
            } else {
                return $this->fetch();
            }
        }
    }

    //批量回复
    public function sysmessage()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ids = $post['ids'];
            $model = new Messages();
            $list = $model->where('id', 'in', $ids)->select();
            foreach ($list as $item) {
                $model = new Messages();
                $data = [
                    'from_user_id' => 0,
                    'to_user_id' => $item->from_user_id,
                    'to_msg_id' => $item->id,
                    'ip' => $this->request->ip(),
                    'message' => $post['message'],
                    'status' => Messages::STATUS_PASS,
                ];
                if (false == $model->allowField(true)->save($data)) {
                    Log::log("回复失败：" . $item->from_user_id);
                }
            }
            $this->success('回复成功');
        }
    }

    public function look()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', 0, 'intval');
            $model = new Messages();
            if ($id > 0) {
                $post = $this->request->post();
                //验证
                $message = $model->where('id', $id)->find();
                if (empty($message)) {
                    $this->error('id不正确');
                }
                $post['is_look'] = $post['status'];
                if (false == $model->allowField(true)->save($post, ['id' => $id])) {
                    $this->error('提交失败');
                } else {
                    $this->success('提交成功', 'admin/tomessages/index');
                }
            }
        }
    }

    public function status()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (false == Db::name('messages')->where('id', $post['id'])->update(['status' => $post['status']])) {
                $this->error('设置失败');
            } else {
                $this->success('设置成功', 'index');
            }
        }
    }


    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->param('id', 0, 'intval');
            if (false == Db::name('messages')->where('id', $id)->delete()) {
                $this->error('删除失败');
            } else {
                $this->success('删除成功', 'index');
            }
        }
    }

    public function deletes()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ids = $post['ids'];
            $model = new Messages();
            if ($model->where('id', 'in', $ids)->delete()) {
                $this->success('删除成功');
            }
        }
    }
}
