<?php

namespace App\Http\Controllers;

use App\Facades\ChatService;
use App\Http\Response\ResponseJson;
use App\Models\Group;
use App\Models\GroupMessage;
use App\Models\GroupMessageConfig;
use App\Models\GroupUser;
use App\Models\Guide;
use App\Models\Order;
use GatewayClient\Gateway;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class ChatController extends Controller
{
    use ResponseJson;
    public function __construct()
    {
        if (config('app.env') == 'production'){
            Gateway::$registerAddress = '192.168.1.204:1238';
        }else {
            Gateway::$registerAddress = '192.168.62.13:1238';
        }
    }

    public function bindClient(Request $request, $client_id)
    {
        ChatService::bindUid($client_id, auth()->id());
        return $this->success('ok');
    }

    public function joinGroup(Request $request)
    {
        $user_id = auth()->id();
        //最近订单
        $order = Order::with('group')->where('user_id', $user_id)->where('pay_status', 'PAID')->orderByDesc('id')->first();
        $client_id = ChatService::getClientIdByUid($user_id);
        if (empty($client_id)) return $this->failure("已断开连接");
        ChatService::joinGroup($client_id, $order->group->id);
        $order->group->order_user_id = $user_id;
        return $this->success('ok', $order->group);
    }

    public function groupInfo(Request $request, Group $group)
    {
        //群成员
        $group->users;
        return $this->success('ok', $group);
    }

    public function leaveGroup(Request $request)
    {
        $client_id = ChatService::getClientIdByUid(auth()->id());
        $group_id = $request->input('group_id');
        ChatService::leaveGroup($client_id, $group_id);
        return $this->success('ok');
    }

    public function sendMessage(Request $request, $group_id)
    {
        $user = auth()->user();
        $content_type = $request->input('content_type');
        $content = $request->input('content');
        //记录数据库 todo
        $message = [
            'group_id'=>$group_id,
            'user_id'=>$user->id,
            'content'=>$content,
            'content_type'=>$content_type,
        ];
        DB::beginTransaction();
        $msg = GroupMessage::create($message);
        //获取某个分组所有在线uid列表。
        $uid_infos = ChatService::getUidListByGroup($group_id);
        if (is_array($uid_infos) && count($uid_infos)) {
            //在线用户
            $uids = array_keys($uid_infos);
            //所有用户
            $group_user_ids = GroupUser::where('group_id', $group_id)->pluck('user_id')->toArray();
            $diff_user_ids = array_diff($group_user_ids, $uids);
            foreach ($diff_user_ids as $uid) {
                if ($uid == $user->id) continue;
                $config = GroupMessageConfig::firstOrCreate(['group_id'=>$group_id, 'user_id'=>$uid]);
                GroupMessageConfig::where(['id'=>$config->id])->update(['last_msg_id'=>$msg->id]);
            }
        }
        DB::commit();
        //获取客户端id
        $res = ChatService::getClientIdByUid($user->id);
        if (empty($res)) return $this->failure("已断开连接");
//        Log::info('用户id: '.$user->id);
//        Log::info('客户端id: '.$res);
        //发送socket消息
        $role_name = GroupUser::where(['group_id'=>$group_id, 'user_id'=>$user->id])->value('role_name');
        $message = ['type'=>'say', 'from_client_id'=>$res, 'from_client_name'=>$user->name, 'from_client_avatar'=>$user->avatar, 'from_user_id'=>$user->id, 'content'=>$content, 'content_type'=>$content_type,'created_at'=>$msg->created_at->toDateTimeString(), 'message_id'=>$msg->id, 'role_name'=>$role_name];
        ChatService::sendToGroup($group_id, $message);
        return $this->success('ok');
    }

    public function chatMessages(Request $request, $group_id)
    {
        $group_users = GroupUser::where('group_id', $group_id)->get();
        $messages = GroupMessage::with('user')->where('group_id', $group_id)->orderByDesc('id')->simplePaginate(30);
        foreach ($messages as $message) {
            $role = $group_users->where('user_id', $message->user_id)->first();
            $message->role_name = $role? $role->role_name:'';
        }
        return $this->success('ok', $messages);
    }

    /**
     * 服务人员进入群聊
     * @param Request $request
     * @param Order $order
     */
    public function serviceJoinGroup(Request $request, Order $order)
    {
        $client_id = ChatService::getClientIdByUid(auth()->id());
        ChatService::joinGroup($client_id, $order->group->id);
        return $this->success('ok', $order->group);
    }

    public function serviceJoinGroupV2(Request $request, Group $group)
    {
        $group->order_user_id = $group->order->user_id;
        $client_id = ChatService::getClientIdByUid(auth()->id());
        ChatService::joinGroup($client_id, $group->id);
        unset($group->order);
        return $this->success('ok', $group);
    }
}
