<?php

namespace App\Http\Middleware;

use App\Models\Group;
use Closure;
use Illuminate\Http\Request;
use App\Http\Response\ResponseJson;

class CheckWorkGroup
{
    use ResponseJson;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $chat_id = $request->input('chat_id');
        if (empty($chat_id))
            return $this->failure('缺少参数群id');
        //群信息
        $service_user_id = $request->input('service_user_id');
        $is_im = $request->input('is_im');
        // if ($service_user_id || $is_im) {
        $group = Group::with('order')->where('im_chat_id', $chat_id)->first();
        // } else {
        //     $group = Group::with('order')->where('chat_id', $chat_id)->first();
        // }
        if (empty($group)) {
            return $this->failure('群id对应群不存在');
        }
        if ($group->service_type == 1) {
            if (empty($group->order))
                return $this->failure('群id群订单不存在');
        }
        $request->group = $group;
        return $next($request);
    }
}
