<?php

namespace App\Services\Goodnight;

use App\Exceptions\AlertException;
use App\Exceptions\DBException;
use App\Models\Goodnight\InviteLogModel;
use App\Models\Goodnight\UserModel;
use App\Services\Service;

class InviteService extends Service
{
    public function invite(int $uid, int $invite_uid)
    {
        $user = UserModel::findOrFail($uid);
        if ($user->subscribed_at > 0) {
            throw new AlertException("新用户专享", 202);
        }
        if ($user->invite_uid == $invite_uid) {
            throw new AlertException("已经邀请过了", 203);
        }
        $user->invite_uid = $invite_uid;
        if ($user->save()) {
            return true;
        } else {
            throw new DBException("系统异常", 500);
        }
    }

    /**
     * 邀请历史列表
     * @param  int  $page
     * @param  int  $limit
     * @param  int  $uid
     * @return array
     */
    public function invitelist(int $page, int $limit, int $uid): array
    {
        $total = InviteLogModel::where('uid', $uid)->count();
        $invites = InviteLogModel::where('uid', $uid)->orderBy(
            'created_at',
            'desc'
        )->skip(($page - 1) * $limit)->take($limit)->get(['invite_uid', 'id', 'created_at', 'gnight_coin']);
        foreach ($invites as &$invite) {
            $user = \App\Models\User\UserModel::findOrFail($invite->invite_uid);
            $invite->nickname = $user->nickname;
            $invite->headimgurl = $user->headimgurl;
        }

        return array(
            'total' => $total,
            'list' => $invites,
        );
    }
}
