<template>
  <ElTable v-if="records.length" :data="records" border style="width: 100%">
    <ElTableColumn prop="fieldName" :label="t('merchant.change.field')" min-width="160">
      <template #default="{ row }">
        {{ resolveFieldLabel(row.fieldName) }}
      </template>
    </ElTableColumn>
    <ElTableColumn prop="oldValue" :label="t('merchant.change.oldValue')" min-width="180" />
    <ElTableColumn prop="newValue" :label="t('merchant.change.newValue')" min-width="180" />
    <ElTableColumn prop="changedByName" :label="t('merchant.change.changedBy')" width="160" />
    <ElTableColumn prop="changedAt" :label="t('merchant.change.changedAt')" width="180">
      <template #default="{ row }">
        {{ formatDateTime(row.changedAt) }}
      </template>
    </ElTableColumn>
  </ElTable>
  <ElEmpty v-else :description="t('merchant.change.empty')" />
</template>

<script setup lang="ts">
  import { computed, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElEmpty, ElTable, ElTableColumn } from 'element-plus'
  import { fetchMerchantChangeLogs } from '@/api/merchant'

  interface Props {
    merchantId?: string
    refreshKey?: number
  }

  const props = defineProps<Props>()
  const { t } = useI18n()
  const records = ref<Api.Merchant.MerchantChangeLogRecord[]>([])

  const fieldLabelMap = computed<Record<string, string>>(() => ({
    name: t('merchant.fields.name'),
    licenseNumber: t('merchant.fields.licenseNumber'),
    legalRepresentative: t('merchant.fields.legalRepresentative'),
    registeredAddress: t('merchant.fields.registeredAddress'),
    contactPhone: t('merchant.fields.contactPhone'),
    contactEmail: t('merchant.fields.contactEmail')
  }))

  const resolveFieldLabel = (fieldName: string) => {
    return fieldLabelMap.value[fieldName] || fieldName
  }

  const formatDateTime = (value?: string | null) => {
    if (!value) return '-'
    const date = new Date(value)
    return Number.isNaN(date.getTime()) ? value : date.toLocaleString()
  }

  const load = async () => {
    if (!props.merchantId) {
      records.value = []
      return
    }

    const result = await fetchMerchantChangeLogs(props.merchantId)
    records.value = result || []
  }

  watch(
    () => [props.merchantId, props.refreshKey],
    () => {
      load()
    },
    { immediate: true }
  )
</script>
