<?php

namespace App\Modules\Scratch\Mobile;


use App\Modules\Activity\JoinMode;
use App\Modules\Base\ActivityBaseTrait;
use App\Modules\Base\BaseMobileController;
use App\Modules\PrizePool\Services\PrizePoolService;
use Edwin404\Base\Support\DatetimeHelper;
use Edwin404\Base\Support\ModelHelper;
use Edwin404\Base\Support\Response;
use Edwin404\Member\Support\MemberLoginCheck;
use Edwin404\User\Support\UserLoginCheck;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\View;

class HomeController extends BaseMobileController implements MemberLoginCheck
{
    use ActivityBaseTrait;
    const MODULE = 'scratch';
    const MODULE_UNDERSCORE = 'scratch';

    public static function owner()
    {
        $alias = Request::route('alias');
        if (empty($alias)) {
            return 0;
        }
        $setting = ModelHelper::load('module_' . self::MODULE_UNDERSCORE . '_activity', ['alias' => $alias]);
        if (empty($setting)) {
            return 0;
        }
        return $setting['memberUserId'];
    }

    public function home(PrizePoolService $prizePoolService)
    {
        $prizes = $prizePoolService->listUserShownPrizes(self::MODULE, $this->activity['id'], null, 0);
        return $this->_view('home', [
            'prizes' => $prizes,
        ]);
    }

    public function draw(PrizePoolService $prizePoolService)
    {
        if (!$this->activity['enable']) {
            return Response::send(-1, '刮刮卡活动未开启');
        }
        if (!DatetimeHelper::isDatetimeEmpty($this->activity['startTime'])) {
            if (time() < strtotime($this->activity['startTime'])) {
                return Response::send(-1, '刮刮卡未开始');
            }
        }
        if (!DatetimeHelper::isDatetimeEmpty($this->activity['endTime'])) {
            if (time() > strtotime($this->activity['endTime'])) {
                return Response::send(-1, '刮刮卡已经结束');
            }
        }

        ModelHelper::transactionBegin();
        try {
            $activity = ModelHelper::loadWithLock('module_' . self::MODULE_UNDERSCORE . '_activity', ['id' => $this->activity['id']]);
            switch ($this->activity['joinMode']) {
                case JoinMode::ONCE_PER_ACCOUNT:
                    if (ModelHelper::exists('module_' . self::MODULE_UNDERSCORE . '_drawn', ['activityId' => $this->activity['id'], 'userId' => $this->userId()])) {
                        ModelHelper::transactionCommit();
                        return Response::send(-1, '您已经抽过奖了');
                    }
                    break;
                case JoinMode::LIMIT_DAILY:
                    $todayCount = ModelHelper::model('module_' . self::MODULE_UNDERSCORE . '_drawn')
                        ->where(['activityId' => $this->activity['id'], 'userId' => $this->userId()])
                        ->where('created_at', '>=', date('Y-m-d 00:00:00', time()))
                        ->where('created_at', '<=', date('Y-m-d 23:59:59', time()))
                        ->count();
                    if ($todayCount >= $this->activity['joinDailyLimit']) {
                        ModelHelper::transactionCommit();
                        return Response::send(-1, '每天最多只能抽' . $this->activity['joinDailyLimit'] . '次奖哦~');
                    }
                    break;
                case JoinMode::NOT_LIMIT:
                    break;
            }
            ModelHelper::add('module_' . self::MODULE_UNDERSCORE . '_drawn', ['activityId' => $this->activity['id'], 'userId' => $this->userId()]);
            $drawn = $prizePoolService->drawPrize(
                $this->memberUserId,
                $this->userId(),
                self::MODULE,
                $this->activity['id']
            );
            ModelHelper::transactionCommit();
        } catch (\Exception $e) {
            ModelHelper::transactionRollback();
            return Response::send(-1, $e->getMessage());
        }

        $html = View::make('res::activity.drawn', [
            'activity' => $activity,
            'drawn' => $drawn,
        ])->render();

        return Response::send(0, null, [
            'prizeId' => $drawn ? $drawn['prizeId'] : 0,
            'prizeName' => $drawn ? $drawn['name'] : null,
            'prizeCover' => $drawn ? $drawn['cover'] : null,
            'html' => $html
        ]);
    }
}