<?php

namespace App\Http\Controllers\Fpdx;

use App\Http\Controllers\Core\Auth;
use App\Http\Resources\Fpdx\ActivityCollection;
use App\Http\Resources\Fpdx\ActivityResource;
use App\Models\Fpdx\ActivityModel;
use App\Models\Fpdx\PairModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Exceptions\JWTException;

class ActivityController extends Controller
{


    /** 活动列表
     * @return ActivityCollection
     */
    public function index(Request $request)
    {
        $activities = ActivityModel::OrderBy('stage_id', 'desc')->paginate(10);
        return new ActivityCollection($activities);
    }


    /**
     * 查看指定的活动
     * @param  Request  $request
     * @param  int  $stage_id
     * @return ActivityResource
     */
    public function show(Request $request, int $stage_id)
    {
        $activity = ActivityModel::find($stage_id);
        return new ActivityResource($activity);
    }


    /**
     * 最近一期
     * @param  Request  $request
     * @return ActivityResource
     * @deprecated Pair/ActivityLast
     */
    public function last(Request $request)
    {
        $activity_type = $request->get('activity_type', '72h');
        $activity = ActivityModel::where(function ($query) use ($activity_type) {
            if ($activity_type == 'qbj') {
                return $query->where('qbj_stage_id', '>', 0);
            }
        })->orderBy('stage_id', 'desc')->first();
        try {
            $uid = Auth::auth();
            $first_pair = PairModel::where('uid', $uid)->where(function ($query) {
                return $query->whereNotNull('assoc_id')
                    ->orWhere('last_assoc', '>', 0);
            })->first();
            $activity->first_pair = $first_pair ? false : true;
        } catch (JWTException $e) {
        }
        return new ActivityResource($activity);
    }


    /**
     * 当前活动正在进行中
     * @return ActivityResource
     */
    public function currently(Request $request)
    {
        $activity = ActivityModel::currently()->first();
        return new ActivityResource($activity);
    }
}
