<?php
declare(strict_types=1);

/**
 * dxDataGrid 布局方案存取，跟具体业务 Model 无关，所有 grid 共用这一套接口
 * 要求登录（继承 Action 默认的 requiresLogin），按 Auth::id() 区分用户
 */
class gridLayoutAction extends Action
{
    private function model(): GridLayout
    {
        return new GridLayout();
    }

    /**
     * 保存布局，请求体: { gridName, schemeName, state: object }
     */
    public function save(): void
    {
        $gridName = trim((string) ($this->request['gridName'] ?? ''));
        $schemeName = trim((string) ($this->request['schemeName'] ?? ''));
        $state = $this->request['state'] ?? null;

        if ($gridName === '' || $schemeName === '' || $state === null) {
            $this->error(1, lg('参数不完整'));
        }

        $this->model()->save(Auth::id(), $gridName, $schemeName, json_encode($state, JSON_UNESCAPED_UNICODE));
        $this->success();
    }

    /**
     * 加载布局，请求体: { gridName, schemeName }
     */
    public function load(): void
    {
        $gridName = trim((string) ($this->request['gridName'] ?? ''));
        $schemeName = trim((string) ($this->request['schemeName'] ?? ''));

        $stateJson = $this->model()->load(Auth::id(), $gridName, $schemeName);
        $this->success(['state' => $stateJson !== null ? json_decode($stateJson, true) : null]);
    }

    /**
     * 列出某个 grid 已保存的方案名（"更多布局"弹窗用），请求体: { gridName }
     */
    public function list(): void
    {
        $gridName = trim((string) ($this->request['gridName'] ?? ''));
        $this->success($this->model()->listSchemes(Auth::id(), $gridName));
    }

    /**
     * 删除布局方案，请求体: { gridName, schemeName }
     */
    public function remove(): void
    {
        $gridName = trim((string) ($this->request['gridName'] ?? ''));
        $schemeName = trim((string) ($this->request['schemeName'] ?? ''));

        $this->model()->remove(Auth::id(), $gridName, $schemeName);
        $this->success();
    }
}
