<?php

namespace app\admin\controller\game;

use app\common\controller\Backend;
use app\common\service\GameRecordService;
use support\Response;
use Throwable;
use Webman\Http\Request as WebmanRequest;

/**
 * 游戏对局（期号）
 */
class Period extends Backend
{
    protected ?object $model = null;

    protected string|array $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = ['id', 'period_no'];

    protected string|array $defaultSortField = ['id' => 'desc'];

    protected string|array $orderGuarantee = ['id' => 'desc'];

    protected bool $modelValidate = true;

    protected bool $modelSceneValidate = true;

    protected function initController(WebmanRequest $request): ?Response
    {
        $this->model = new \app\common\model\GameRecord();
        return null;
    }

    /**
     * 读取 / 保存：自动创建下一期、手动创建下一期 开关（存 game_config）
     */
    public function periodSettings(WebmanRequest $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) {
            return $response;
        }
        $method = $request->method();
        if ($method === 'GET') {
            return $this->success('', GameRecordService::getRecordSettings());
        }
        if ($method === 'POST') {
            $data = $request->post();
            if (!is_array($data)) {
                return $this->error(__('Parameter %s can not be empty', ['']));
            }
            try {
                GameRecordService::saveRecordSettings($data);
            } catch (Throwable $e) {
                return $this->error($e->getMessage());
            }
            return $this->success(__('Saved successfully'));
        }
        return $this->error(__('Parameter error'));
    }

    /**
     * 手动创建下一期（受开关与「存在进行中期号」约束）
     */
    public function createNextManual(WebmanRequest $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) {
            return $response;
        }
        if ($request->method() !== 'POST') {
            return $this->error(__('Parameter error'));
        }
        $result = GameRecordService::createNextRecordForManual();
        if ($result['ok']) {
            return $this->success($result['msg'], ['period_no' => $result['period_no'] ?? '']);
        }
        return $this->error($result['msg']);
    }

    protected function _add(): Response
    {
        if ($this->request && $this->request->method() === 'POST') {
            $data = $this->request->post();
            if (!is_array($data)) {
                return $this->error(__('Parameter %s can not be empty', ['']));
            }
            $data = $this->applyInputFilter($data);
            $data = $this->excludeFields($data);
            if (!isset($data['period_start_at']) || $data['period_start_at'] === '' || $data['period_start_at'] === null) {
                $data['period_start_at'] = time();
            }
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $result = false;
            $this->model->startTrans();
            try {
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            if ($result !== false) {
                return $this->success(__('Added successfully'));
            }
            return $this->error(__('No rows were added'));
        }
        return $this->error(__('Parameter error'));
    }
}
