<?php

namespace app\admin\controller;

use think\Db;
use app\api\model\Gateway;

/**
 * 用户列表页
 */
class Message extends Base
{
    /**
     * 聊天监控页
     * @return mixed
     */
    public function index()
    {
        $setting = Db::table('setting')->find();
        $this->assign('setting', $setting);
        $this->assign('section', 'message');
        $this->assign('limit', 500);
        return $this->fetch();
    }



    /**
     * 获得聊天日志
     */
    public function chatget()
    {
        $get = $this->request->get();
        
        $limit = isset($get['limit']) ? $get['limit'] : 100;

        $message_list = (array)Db::table('message')->query("select * from message where sub_type!='notice' or original_content is not null order by mid desc limit $limit");

        $uid_list = $gid_list = $group_list = $user_list= [];

        foreach ($message_list as $item) {
            if ($item['type'] == 'friend') {
                $uid_list[$item['from']] = $item['from'];
                $uid_list[$item['to']] = $item['to'];
            } else {
                $uid_list[$item['from']] = $item['from'];
                $gid_list[$item['to']] = $item['to'];
            }
        }

        if ($uid_list) {
            $user_list = Db::table('user')->where('uid', 'in', $uid_list)->column('uid,nickname as name,avatar', 'uid');
        }
        if ($gid_list) {
            $group_list = Db::table('groups')->where('gid', 'in', $gid_list)->column('gid,groupname as name,avatar', 'gid');
        }

        foreach ($message_list as $key=>$item) {
            if ($item['type'] == 'friend') {
                $to_uid = $item['to'];
                $from_uid = $item['from'];
                $message_list[$key]['name'] = isset($user_list[$from_uid]) ? $user_list[$from_uid]['name'] : '';
                $message_list[$key]['avatar'] = isset($user_list[$from_uid]) ? $user_list[$from_uid]['avatar'] : '';
                $message_list[$key]['to_name'] = isset($user_list[$to_uid]) ? $user_list[$to_uid]['name'] : '';
                $message_list[$key]['to_avatar'] = isset($user_list[$to_uid]) ? $user_list[$to_uid]['avatar'] : '';
            } else {
                $gid = $item['to'];
                $from_uid = $item['from'];
                $message_list[$key]['name'] = isset($user_list[$from_uid]) ? $user_list[$from_uid]['name'] : '';
                $message_list[$key]['avatar'] = isset($user_list[$from_uid]) ? $user_list[$from_uid]['avatar'] : '';
                $message_list[$key]['to_name'] = isset($group_list[$gid]) ? $group_list[$gid]['name'] : '';
                $message_list[$key]['to_avatar'] = isset($group_list[$gid]) ? $group_list[$gid]['avatar'] : '';
            }
            if (!empty($message_list[$key]['original_content'])) {
                if ($message_list[$key]['content'] != $message_list[$key]['original_content']) {
                    $message_list[$key]['revoke'] = $message_list[$key]['content'];
                    $message_list[$key]['content'] = $message_list[$key]['original_content'];
                }
                $message_list[$key]['sub_type'] = 'message';
            }

        }

        $message_list = array_reverse($message_list);

        return $this->json(0, 'ok', $message_list);
    }

    /**
     * 消息撤回接口
     *
     * @return array
     */
    public function revoke()
    {
        $post = $this->request->post();
        // 检查必要字段是否为空
        $required = ['type', 'to', 'mid', 'from'];
        foreach ($required as $key) {
            if (empty($post[$key])) {
                return $this->json(1, '缺少参数');
            }
        }

        // 判断类型
        $type = $post['type'];
        if ($type !== 'friend' && $type !== 'group') {
            return $this->json(2, "参数非法");
        }

        $from      = $post['from'];
        $to        = $post['to'];
        $mid       = $post['mid'];
        $type      = $post['type'];

        // 获得消息
        $message = Db::table('message')->where(['mid'=> $mid])->find();
        if (!$message) {
            return $this->json(404, '消息不存在');
        }

        Db::table('message')->where(['mid'=> $mid, 'to' => $to])->update([
            'sub_type'    => 'notice',
            'content'     => '此消息已撤回',
        ]);

        // 执行推送
        $push    = new Gateway();
        $channel1 = $type == 'friend' ? "user-$to" : "group-$to";
        $event   = 'revoke';
        $data    = [
            'type'     => $type,
            'id'       => $to,
            'mid'      => $mid,
            'uid'      => $from,
            'operator' => 'admin'
        ];

        // 给群推送或者对方推送
        $result = Gateway::sendToGroup($channel1, $event, $data);
        if ($result['status'] != 200) {
            return $this->json(500, '服务器错误，推送失败：'.$result['body']);
        }

        // 如果是单聊，给发起者也推送一次
        if ($type == 'friend') {
            Gateway::sendToGroup("user-$from", $event, $data);
        }

        return $this->json(0, 'ok');
    }

}
