<?php
declare(strict_types=1);

/**
 * 通用属性值模型，对应 attr_value 表
 * 所有属性类型（币种、材质、区域…）的值都存这一张表，按 attr_value_lnk_type_id 区分
 */
class AttrValue extends Model
{
    protected string $table = 'attr_value';
    protected string $key   = 'attr_value_id';

    /**
     * 重写 grid()：基类直接返回原始 SQL 行，attr_value_ext_values 是 JSON 字符串；
     * 这里统一 decode 成数组，前端 flattenExt 才能正常按 key 读取扩展字段值
     */
    public function grid(array $loadOptions): array
    {
        $result = parent::grid($loadOptions);

        foreach ($result['data'] as &$row) {
            $row['attr_value_ext_values'] = $row['attr_value_ext_values']
                ? (json_decode($row['attr_value_ext_values'], true) ?: [])
                : [];
        }

        return $result;
    }

    /**
     * 供 dxTreeList 使用：返回指定类型的所有值（平铺，树形由前端 keyExpr/parentIdExpr 组装）
     * ext_values JSON 已 decode 为数组
     */
    public function treeByType(int $typeId): array
    {
        $rows = $this->db->select($this->table, '*', [
            'attr_value_lnk_type_id' => $typeId,
            'ORDER' => ['attr_value_sort' => 'ASC', 'attr_value_id' => 'ASC'],
        ]);

        foreach ($rows as &$row) {
            $row['attr_value_ext_values'] = $row['attr_value_ext_values']
                ? (json_decode($row['attr_value_ext_values'], true) ?: [])
                : [];
        }

        return $rows;
    }

    /**
     * gridInsert：自动 encode ext_values；前端可能传 array（已解析的对象）
     */
    public function gridInsert(array $values): mixed
    {
        $this->encodeExt($values);
        return parent::gridInsert($values);
    }

    /**
     * gridUpdate：encode ext_values
     */
    public function gridUpdate(mixed $key, array $values): int
    {
        $this->encodeExt($values);
        return parent::gridUpdate($key, $values);
    }

    private function encodeExt(array &$values): void
    {
        if (!array_key_exists('attr_value_ext_values', $values)) {
            return;
        }

        $v = $values['attr_value_ext_values'];

        if (is_array($v) && !empty($v)) {
            $values['attr_value_ext_values'] = json_encode($v, JSON_UNESCAPED_UNICODE);
        } elseif (is_string($v) && $v !== '' && $v !== 'null') {
            // 前端直接传了 JSON 字符串（极少情况），验证后存储
            if (json_decode($v) === null) {
                $values['attr_value_ext_values'] = null;
            }
        } else {
            $values['attr_value_ext_values'] = null;
        }
    }
}
