<?php

namespace App\Services\Goodnight;

use App\Exceptions\AlertException;
use App\Models\Goodnight\ActivityModel;
use App\Models\Goodnight\EnterModel;

class EnterService
{


    private $type;

    private $uid;


    /**
     * 报名
     * @param $uid
     * @param $type
     * @return mixed
     * @throws AlertException
     */
    public function enter($uid, $type)
    {
        $activity = $this->getActivity("报名");

        if ($this->repeatedly($type, $uid, $activity->id)) {
            throw new AlertException("不可重复报名", 101);
        }

        $enter = $this->createEnter($type, $uid, $activity->id);

        return $enter;
    }


    /**
     * 获取当前可报名的活动
     * @return mixed
     */
    public function getActivity($type = '报名')
    {
        switch ($type) {
            case "报名":
                $activity = ActivityModel::where([
                    ['opened_at', '<', time()],
                    ['closed_at', '>', time()],
                ])->firstOrFail();
                break;
            case "邀请":
                $activity = ActivityModel::whereRaw(
                    "from_unixtime(`showed_at`, '%Y-%m-%d') = ?",
                    [
                        date('Y-m-d'),
                    ]
                )->firstOrFail();
                break;
            case "匹配":
                $activity = ActivityModel::where([
                    ['closed_at', '<', time()],
                    ['showed_at', '>', time()],
                ])->firstOrFail();
                break;
        }

        return $activity;
    }


    /**
     * 是否重复报名
     * @param $type
     * @param $uid
     * @param $activity_id
     * @return bool
     */
    private function repeatedly($type, $uid, $activity_id)
    {
        switch ($type) {
            case "报名":
                return EnterModel::where("uid", $uid)
                    ->where("type", $type)
                    ->where("activity_id", $activity_id)
                    ->first() ? true : false;
                break;
            case "邀请":
                return false;
        }
    }


    /**
     * 插入报名列表
     * @param $type
     * @param $uid
     * @param $activity_id
     * @return mixed
     */
    public function createEnter($type, $uid, $activity_id)
    {
        $enter = EnterModel::create([
            'type' => $type,
            'activity_id' => $activity_id,
            'uid' => $uid,
        ]);

        return $enter;
    }
}
