<template>
    <div v-if="tagLabels.length" class="game-user-ticket-tags">
        <el-tag v-for="(label, idx) in tagLabels" :key="idx" class="m-4" effect="light" type="success" size="default">
            {{ label }}
        </el-tag>
    </div>
    <span v-else class="game-user-json-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
}>()

/** [{"ante":1,"count":1},...] */
function parseTicketTagLabels(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)) {
            const o = item as Record<string, unknown>
            const ante = o.ante
            const count = o.count
            labels.push(`ante:${String(ante)} count:${String(count)}`)
        }
    }
    return labels
}

const tagLabels = computed(() => parseTicketTagLabels(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-user-ticket-tags {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 4px 0;
}
.m-4 {
    margin: 4px;
}
.game-user-json-plain {
    word-break: break-all;
}
</style>
