<?php

namespace App\Http\Controllers\Main;

use App\Http\Controllers\Support\BaseController;
use App\Types\EventOrderStatus;
use App\Types\EventStatus;
use Edwin404\Banner\Services\BannerService;
use Edwin404\Base\Support\InputHelper;
use Edwin404\Base\Support\ModelHelper;
use Edwin404\Base\Support\Response;
use Edwin404\Forum\Services\ForumService;
use Edwin404\Shop\Helpers\OrderHelper;
use Edwin404\Tecmz\Traits\MemberAccountTrait;

class EventController extends BaseController
{
    public function index($id)
    {
        $event = ModelHelper::load('event', ['id' => $id]);
        if (empty($event)) {
            return Response::send(-1, 'no record', null, '/');
        }
        $event['_category'] = ModelHelper::load('event_category', ['id' => $event['categoryId']]);

        ModelHelper::decodeRecordJson($event, 'photos');
        ModelHelper::decodeRecordJson($event, 'param');
        ModelHelper::decodeRecordJson($event, 'applyInfo');

        return $this->_view('event.index', compact('event'));
    }

    public function submit($id)
    {
        if (!$this->memberUserId()) {
            return Response::send(-1, '还没有登录', null, '/login?redirect=' . urlencode('/event/' . $id));
        }

        $event = ModelHelper::load('event', ['id' => $id]);
        if (empty($event)) {
            return Response::send(-1, 'no record', null, '/');
        }

        ModelHelper::decodeRecordJson($event, 'applyInfo');

        $applyInfo = [];
        $applyInfoValues = InputHelper::getArray('applyInfo', []);
        foreach ($applyInfoValues as $index => $item) {
            if (empty($item)) {
                return Response::send(-1, $event['applyInfo'][$index]['name'] . '不能为空');
            }
            $applyInfo[] = ['name' => $event['applyInfo'][$index]['name'], 'value' => $item];
        }

        if ($event['status'] != EventStatus::APPLYING) {
            return Response::send(-1, '当前状态不能报名');
        }

        if ($event['applyTimeLimit'] && (time() < strtotime($event['applyStartTime']) || time() > strtotime($event['applyEndTime']))) {
            return Response::send(-1, '已经不能报名');
        }

        try {
            ModelHelper::transactionBegin();
            $event = ModelHelper::loadWithLock('event', ['id' => $id]);
            // 判断报名人数
            if ($event['applyNumberLimit']) {
                $payedTotal = ModelHelper::count('event_order', ['eventId' => $event['id'], 'status' => EventOrderStatus::WAIT_PAY]);
                $unpayedTotal = ModelHelper::count('event_order', ['eventId' => $event['id'], 'status' => EventOrderStatus::COMPLETED]);
                if ($payedTotal + $unpayedTotal >= $event['applyNumberMax']) {
                    ModelHelper::transactionCommit();
                    return Response::send(-1, '报名人数已满');
                }
            }
            $order = [];
            $order['sn'] = OrderHelper::generateSN();
            $order['memberUserId'] = $this->memberUserId();
            $order['eventId'] = $event['id'];
            $order['status'] = EventOrderStatus::WAIT_PAY;
            $order['totalFee'] = $event['price'];
            $order['payFee'] = $event['price'];
            $order['applyInfo'] = json_encode($applyInfo);
            $order = ModelHelper::add('event_order', $order);
            ModelHelper::transactionCommit();
            return Response::send(0, null, null, '/member/order_pay/' . $order['id']);

        } catch (\Exception $e) {
            ModelHelper::transactionRollback();
            throw $e;
        }
    }

}