<template>
    <div v-if="isGameWeight && weightTagLabels.length" class="game-config-value-tags">
        <el-tag
            v-for="(label, idx) in weightTagLabels"
            :key="idx"
            class="m-4"
            effect="light"
            type="primary"
            size="default"
        >
            {{ label }}
        </el-tag>
    </div>
    <span v-else class="game-config-value-plain">{{ plainText }}</span>
</template>

<script setup lang="ts">
import { computed } from 'vue'

const props = defineProps<{
    renderRow: TableRow
    renderField: TableColumn
    renderValue: unknown
    renderColumn: import('element-plus').TableColumnCtx<TableRow>
    renderIndex: number
}>()

const isGameWeight = computed(() => props.renderRow?.group === 'game_weight')

/**
 * value 形如 [{"T1":"5"},{"T2":"20"},...] 或同结构的 JSON 字符串
 */
function parseWeightTagLabels(raw: unknown): string[] {
    if (raw === null || raw === undefined || raw === '') {
        return []
    }
    let arr: unknown[] = []
    if (typeof raw === 'string') {
        const s = raw.trim()
        if (!s) return []
        try {
            const parsed = JSON.parse(s)
            arr = Array.isArray(parsed) ? parsed : []
        } catch {
            return []
        }
    } else if (Array.isArray(raw)) {
        arr = raw
    } else {
        return []
    }

    const labels: string[] = []
    for (const item of arr) {
        if (item !== null && typeof item === 'object' && !Array.isArray(item)) {
            for (const [k, v] of Object.entries(item as Record<string, unknown>)) {
                labels.push(`${k}:${String(v)}`)
            }
        }
    }
    return labels
}

const weightTagLabels = computed(() => parseWeightTagLabels(props.renderValue))

const plainText = computed(() => {
    const v = props.renderValue
    if (v === null || v === undefined) return ''
    if (typeof v === 'object') {
        try {
            return JSON.stringify(v)
        } catch {
            return String(v)
        }
    }
    return String(v)
})
</script>

<style scoped lang="scss">
.game-config-value-tags {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 4px 0;
}
.m-4 {
    margin: 4px;
}
.game-config-value-plain {
    word-break: break-all;
}
</style>
