<?php

namespace App\Services\V2_17_3\Friends;

use App\Exceptions\AlertException;
use App\Jobs\GrowingIO\FriendInvitationReportJob;
use App\Models\Deed\InvitationCardModel;
use App\Models\Friends\FriendApplyModel;
use App\Models\Friends\FriendModel;
use App\Models\Friends\LogModel;
use App\Services\Service;
use Illuminate\Support\Facades\DB;

class ApplyService extends Service
{
    /**
     * 发起好友申请
     * @param  int  $uid
     * @param  int  $to_uid
     * @param  array  $questions
     * @return bool
     * @throws AlertException
     */
    public function send(int $uid, int $to_uid, array $questions)
    {
        if ($uid == $to_uid) {
            throw new AlertException("不能邀请自己参加活动哦", 422);
        }
        try {
            DB::beginTransaction();
            $invitationCard = InvitationCardModel::create([
                'uid' => $uid,
                'invite_uid' => $to_uid,
            ]);
            foreach ($questions as $question) {
                LogModel::create([
                    'uid' => $uid,
                    'tuid' => $to_uid,
                    'do' => 3,
                    'attach' => [$question],
                ]);
            }
            FriendApplyModel::send($uid, $to_uid);
            dispatch_now(new FriendInvitationReportJob($invitationCard, $questions));
            DB::commit();

            return true;
        } catch (\Exception $exception) {
            DB::rollBack();

            return false;
        }
    }

    public function agree(int $uid, int $apply_uid)
    {
        if ($uid == $apply_uid) {
            throw new AlertException("参数错误", 422);
        }
        $applyOrFriend = FriendModel::applyOrFriend($uid, $apply_uid);
        if (1 == $applyOrFriend) {
        } else {
            throw new AlertException("没有收到新未处理的好友申请", 423);
        }
    }
}
