<?php
declare(strict_types=1);

/**
 * 属性值管理
 * 页面: admin/attrValue/index
 * 接口:
 *   attrValue/tree   { typeId }  → 树型类型专用，返回平铺数组（dxTreeList 客户端组树）
 *   attrValue/grid   { typeId, ...loadOptions }  → 平铺类型专用，分页/过滤
 *   attrValue/save   { key?, values }  → GridActions
 *   attrValue/remove { key }           → GridActions
 */
class attrValueAction extends Action
{
    use GridActions;

    protected function gridModel(): Model
    {
        return new AttrValue();
    }

    public function index(): void
    {
        View::set([
            'pageTitle' => lg('属性值'),
            'types'     => (new AttrType())->listAll(),
        ]);
        View::put();
    }

    /**
     * 树型类型专用：返回指定类型的全量平铺数组，dxTreeList 客户端组树
     * 请求体: { typeId: int }
     */
    public function tree(): void
    {
        $typeId = (int) ($this->request['typeId'] ?? 0);

        if ($typeId <= 0) {
            $this->error(1, lg('参数不完整'));
        }

        $this->success((new AttrValue())->treeByType($typeId));
    }

    /**
     * 平铺类型专用：注入 typeId 过滤后走标准 grid()
     * 请求体: { typeId: int, filter?, sort?, skip?, take?, requireTotalCount? }
     */
    public function grid(): void
    {
        $typeId = (int) ($this->request['typeId'] ?? 0);

        if ($typeId <= 0) {
            $this->error(1, lg('参数不完整'));
        }

        $loadOptions = $this->request;
        unset($loadOptions['typeId']);

        $typeFilter = ['attr_value_lnk_type_id', '=', $typeId];
        if (!empty($loadOptions['filter'])) {
            $loadOptions['filter'] = [$typeFilter, 'and', $loadOptions['filter']];
        } else {
            $loadOptions['filter'] = $typeFilter;
        }

        $this->success((new AttrValue())->grid($loadOptions));
    }
}
