<?php

namespace App\Http\Controllers\Syj;

use App\Http\Controllers\Core\Auth;
use App\Models\Syj\GroupModel;
use App\Models\Syj\GroupMemberModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class GroupController extends Controller
{


    /**
     * 显示分配的群组
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function show(Request $request)
    {
        $uid = Auth::auth();
        if (!$group_user = GroupMemberModel::where('uid', $uid)->first()) {
            $group = GroupModel::where('state', '1')
                ->where('expired_at', '>', time())
                ->whereRaw("capacity_number > total_number")->first();
            if (!$group) {
                return response([
                    'code' => 404,
                    'message' => '暂时群已满员'
                ]);
            }
            $group->increment('total_number');
            $group->save();
            GroupMemberModel::create([
                'uid' => $uid,
                'group_id' => $group->id,
            ]);
        } else {
            $group = GroupModel::find($group_user->group_id);
            if ($group->expired_at < time()) {
                return response([
                    'code' => 410,
                    'message' => '当前已暂停入群'
                ]);
            }
        }
        return response([
            'code' => 200,
            'message' => 'OK',
            'data' => $group
        ]);
    }
}
