<?php

namespace App\Http\Controllers\Main;

use App\Http\Controllers\Support\BaseController;
use App\Types\EventOrderItemStatus;
use App\Types\EventOrderStatus;
use App\Types\EventStatus;
use Edwin404\Banner\Services\BannerService;
use Edwin404\Base\Support\InputHelper;
use Edwin404\Base\Support\InputPackage;
use Edwin404\Base\Support\ModelHelper;
use Edwin404\Base\Support\Response;
use Edwin404\EXField\EXFieldUtil;
use Edwin404\Forum\Services\ForumService;
use Edwin404\Shop\Helpers\OrderHelper;
use Edwin404\Tecmz\Traits\MemberAccountTrait;
use EdwinFound\Utils\RandomUtil;
use EdwinFound\Utils\StrUtil;

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');
        EXFieldUtil::unbuildTableFieldRow($event);

        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, '/');
        }

        for ($i = 1; $i < 5; $i++) {
            ModelHelper::decodeRecordJson($event, 'fieldCustom' . $i);
        }

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

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

        $input = InputPackage::buildFromInput();
        $eventOrderItem = [];
        for ($i = 1; $i < 5; $i++) {
            if (empty($event['fieldCustom' . $i])) {
                continue;
            }
            $eventOrderItem['fieldCustom' . $i] = $input->getTrimString('fieldCustom' . $i);
            if (empty($eventOrderItem['fieldCustom' . $i])) {
                return Response::send(-1, $event['fieldCustom' . $i]['title'] . '不能为空');
            }
        }

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

            $eventOrderItem['memberUserId'] = $this->memberUserId();
            $eventOrderItem['orderId'] = $order['id'];
            $eventOrderItem['eventId'] = $event['id'];
            $eventOrderItem['checkCode'] = RandomUtil::number(10);
            $eventOrderItem['orderStatus'] = $order['status'];
            $eventOrderItem['status'] = EventOrderItemStatus::WAIT_SIGN_IN;
            ModelHelper::add('event_order_item', $eventOrderItem);
            ModelHelper::transactionCommit();
            return Response::send(0, null, null, '/member/order_pay/' . $order['id']);

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

}