<?php

namespace App\Http\Services\V1_1;

use App\Generated\V1_1\Messages\Invite\LastInviteMessage;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Core\Auth;
use App\Models\Fpdx\PairModel;
use App\Models\Fpdx\ActivityModel;
use App\Models\Fpdx\InviteModel;
use App\Models\User\UserModel;
use App\Models\User\AuthKey;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;

class InviteService
{
    public function lastInvite(LastInviteMessage $message)
    {
        $ings = ActivityModel::getActivitys();
        $invites = InviteModel::where([
            ['stage_id', $ings['next']],
            ['state', '!=', 2]
        ])->take(30)->groupBy('pair_id')->get(['uid', 'pair_id']);
        foreach ($invites as &$invite) {
            $invite->user = UserModel::find($invite->uid, ['uid', 'headimgurl', 'nickname', 'sex', 'address', 'home']);
            $refund = InviteModel::where([
                ['state', 1],
                ['pair_id', $invite->pair_id]
            ])->count();
            if ($refund > 0) {
                $invite->invite = array(
                    'type' => 1,
                    'count' => $refund,
                    'dis_count' => InviteModel::where([
                        ['state', 1],
                        ['pair_id', $invite->pair_id]
                    ])->sum('dis_score')
                );
            } else {
                $invite->invite = array(
                    'type' => 0,
                    'count' => InviteModel::where([
                        ['state', 0],
                        ['pair_id', $invite->pair_id]
                    ])->count(),
                    'dis_score' => InviteModel::where([
                        ['state', 0],
                        ['pair_id', $invite->pair_id]
                    ])->sum('dis_score')
                );
            }
        }

        $message->setResponse($invites);
    }
}
