<template>
  <div class="platform-label-override-page art-full-height">
    <ElCard class="override-card" shadow="never">
      <!-- 1. 顶部工具栏 -->
      <div class="page-toolbar">
        <!-- 1.1 租户选择器 -->
        <div class="tenant-selector">
          <span class="selector-label">{{ t('dictionary.labelOverride.selectTenant') }}:</span>
          <ElSelect
            v-model="selectedTenantId"
            :placeholder="t('dictionary.labelOverride.selectTenantHint')"
            filterable
            remote
            :remote-method="searchTenants"
            :loading="loadingTenants"
            clearable
            style="min-width: 300px"
            @change="handleTenantChange"
          >
            <ElOption
              v-for="tenant in tenantOptions"
              :key="tenant.id"
              :label="`${tenant.name} (${tenant.code})`"
              :value="tenant.id"
            />
          </ElSelect>
        </div>

        <!-- 1.2 覆盖类型筛选 -->
        <div class="filter-group">
          <ElRadioGroup v-model="overrideTypeFilter" @change="handleFilterChange">
            <ElRadioButton :value="undefined">{{
              t('dictionary.labelOverride.filterAll')
            }}</ElRadioButton>
            <ElRadioButton :value="1">{{
              t('dictionary.labelOverride.filterTenantCustomization')
            }}</ElRadioButton>
            <ElRadioButton :value="2">{{
              t('dictionary.labelOverride.filterPlatformEnforcement')
            }}</ElRadioButton>
          </ElRadioGroup>
        </div>
      </div>

      <!-- 2. 覆盖列表 -->
      <div v-if="selectedTenantId" class="override-content">
        <!-- 2.1 操作按钮 -->
        <div class="content-toolbar">
          <ElButton type="primary" :icon="Plus" @click="handleAdd">
            {{ t('dictionary.labelOverride.newOverride') }}
          </ElButton>
          <ElButton :icon="Refresh" @click="handleRefresh">
            {{ t('dictionary.common.refresh') }}
          </ElButton>
        </div>

        <!-- 2.2 覆盖表格 -->
        <ElTable
          v-loading="loading"
          :data="overrides"
          stripe
          border
          class="override-table"
          empty-text=" "
        >
          <!-- 字典项键 -->
          <ElTableColumn
            prop="dictionaryItemKey"
            :label="t('dictionary.labelOverride.dictionaryItemKey')"
            min-width="120"
          />

          <!-- 原始值 -->
          <ElTableColumn :label="t('dictionary.labelOverride.originalValue')" min-width="180">
            <template #default="{ row }">
              <div class="i18n-cell">
                <div v-for="(val, lang) in row.originalValue" :key="lang" class="i18n-item">
                  <span class="lang-tag">{{ lang }}</span>
                  <span class="lang-text">{{ val }}</span>
                </div>
              </div>
            </template>
          </ElTableColumn>

          <!-- 覆盖值 -->
          <ElTableColumn :label="t('dictionary.labelOverride.overrideValue')" min-width="180">
            <template #default="{ row }">
              <div class="i18n-cell override-value">
                <div v-for="(val, lang) in row.overrideValue" :key="lang" class="i18n-item">
                  <span class="lang-tag">{{ lang }}</span>
                  <span class="lang-text">{{ val }}</span>
                </div>
              </div>
            </template>
          </ElTableColumn>

          <!-- 覆盖类型 -->
          <ElTableColumn :label="t('dictionary.labelOverride.overrideType')" width="120">
            <template #default="{ row }">
              <ElTag :type="getOverrideTypeTag(row.overrideType)">
                {{ row.overrideTypeName }}
              </ElTag>
            </template>
          </ElTableColumn>

          <!-- 原因 -->
          <ElTableColumn
            prop="reason"
            :label="t('dictionary.labelOverride.reason')"
            min-width="150"
          >
            <template #default="{ row }">
              <span v-if="row.reason">{{ row.reason }}</span>
              <span v-else class="text-secondary">-</span>
            </template>
          </ElTableColumn>

          <!-- 更新时间 -->
          <ElTableColumn :label="t('dictionary.labelOverride.updatedAt')" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.updatedAt || row.createdAt) }}
            </template>
          </ElTableColumn>

          <!-- 操作 -->
          <ElTableColumn :label="t('dictionary.common.actions')" width="140" fixed="right">
            <template #default="{ row }">
              <div class="action-wrap">
                <button class="art-action-btn primary" @click="handleEdit(row)">
                  <ArtSvgIcon icon="ri:edit-2-line" class="art-action-icon" />
                  <span>{{ t('dictionary.common.edit') }}</span>
                </button>
                <ElDropdown
                  trigger="click"
                  @command="(cmd) => cmd === 'delete' && handleDelete(row)"
                >
                  <button class="art-action-btn info">
                    <ArtSvgIcon icon="ri:more-2-line" class="art-action-icon" />
                    <span>{{ t('user.action.more') }}</span>
                  </button>
                  <template #dropdown>
                    <ElDropdownMenu>
                      <ElDropdownItem command="delete">
                        <div class="flex items-center gap-2 text-danger">
                          <ArtSvgIcon icon="ri:delete-bin-line" />
                          <span>{{ t('dictionary.common.delete') }}</span>
                        </div>
                      </ElDropdownItem>
                    </ElDropdownMenu>
                  </template>
                </ElDropdown>
              </div>
            </template>
          </ElTableColumn>

          <!-- 空状态 -->
          <template #empty>
            <ElEmpty :description="t('dictionary.labelOverride.noOverrides')" />
          </template>
        </ElTable>
      </div>

      <!-- 3. 未选择租户提示 -->
      <div v-else class="override-empty">
        {{ t('dictionary.labelOverride.selectTenantHint') }}
      </div>

      <!-- 4. 表单对话框 -->
      <PlatformLabelOverrideFormDialog
        ref="formDialogRef"
        v-model="dialogVisible"
        :edit-item="editingItem"
        :target-tenant-id="selectedTenantId"
        @submit="handleSubmit"
      />
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { Plus, Refresh } from '@element-plus/icons-vue'
  import { fetchGetTenantList } from '@/api/tenant'
  import { useLabelOverrideStore } from '@/store/modules/labelOverride'
  import PlatformLabelOverrideFormDialog from './components/PlatformLabelOverrideFormDialog.vue'

  defineOptions({ name: 'PlatformLabelOverride' })

  const { t } = useI18n()
  const labelOverrideStore = useLabelOverrideStore()

  // 1. 状态
  const selectedTenantId = ref<string | null>(null)
  const tenantOptions = ref<Api.Tenant.TenantDto[]>([])
  const loadingTenants = ref(false)
  const overrideTypeFilter = ref<number | undefined>(undefined)
  const dialogVisible = ref(false)
  const editingItem = ref<Api.Dictionary.LabelOverrideDto | null>(null)
  const formDialogRef = ref<InstanceType<typeof PlatformLabelOverrideFormDialog>>()

  // 2. 计算属性
  const loading = computed(() => labelOverrideStore.loading)
  const overrides = computed(() => labelOverrideStore.platformOverrides)

  // 3. 辅助方法
  const formatDateTime = (dateStr: string) => {
    if (!dateStr) return '-'
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  const getOverrideTypeTag = (type: number) => {
    // TenantCustomization = 1, PlatformEnforcement = 2
    return type === 2 ? 'danger' : 'success'
  }

  // 4. 租户搜索
  const searchTenants = async (keyword: string) => {
    if (!keyword && tenantOptions.value.length > 0) return

    loadingTenants.value = true
    try {
      const result = await fetchGetTenantList({
        Page: 1,
        PageSize: 50,
        Keyword: keyword || undefined
      })
      tenantOptions.value = result.items
    } catch {
      tenantOptions.value = []
    } finally {
      loadingTenants.value = false
    }
  }

  // 5. 加载数据
  const loadOverrides = async () => {
    if (!selectedTenantId.value) return
    await labelOverrideStore.fetchPlatformOverrides(
      selectedTenantId.value,
      overrideTypeFilter.value
    )
  }

  // 6. 事件处理
  const handleTenantChange = async () => {
    if (selectedTenantId.value) {
      await loadOverrides()
    } else {
      labelOverrideStore.setSelectedTenant(null)
    }
  }

  const handleFilterChange = async () => {
    await loadOverrides()
  }

  const handleRefresh = async () => {
    await loadOverrides()
  }

  const handleAdd = () => {
    editingItem.value = null
    dialogVisible.value = true
  }

  const handleEdit = (row: Api.Dictionary.LabelOverrideDto) => {
    editingItem.value = row
    dialogVisible.value = true
  }

  const handleDelete = async (row: Api.Dictionary.LabelOverrideDto) => {
    if (!selectedTenantId.value) return
    await labelOverrideStore.deletePlatformOverride(selectedTenantId.value, row.dictionaryItemId)
  }

  const handleSubmit = async (data: Api.Dictionary.UpsertLabelOverrideRequest) => {
    if (!selectedTenantId.value) return

    formDialogRef.value?.setLoading(true)
    const result = await labelOverrideStore.upsertPlatformOverride(selectedTenantId.value, data)
    formDialogRef.value?.setLoading(false)

    if (result) {
      formDialogRef.value?.close()
    }
  }

  // 7. 生命周期
  onMounted(async () => {
    // 加载初始租户列表
    await searchTenants('')
  })

  // 8. 监听租户变化
  watch(
    () => selectedTenantId.value,
    (newVal) => {
      if (!newVal) {
        labelOverrideStore.setSelectedTenant(null)
      }
    }
  )
</script>

<style scoped>
  .platform-label-override-page {
    height: 100%;
  }

  .override-card {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .page-toolbar {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
  }

  .tenant-selector {
    display: flex;
    gap: 8px;
    align-items: center;
  }

  .selector-label {
    flex-shrink: 0;
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  .override-content {
    display: flex;
    flex: 1;
    flex-direction: column;
    gap: 16px;
  }

  .content-toolbar {
    display: flex;
    gap: 12px;
  }

  .override-table {
    flex: 1;
  }

  .i18n-cell {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .i18n-item {
    display: flex;
    gap: 8px;
    align-items: center;
  }

  .lang-tag {
    flex-shrink: 0;
    padding: 2px 6px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
    background: var(--el-fill-color);
    border-radius: 4px;
  }

  .lang-text {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .override-value .lang-text {
    font-weight: 500;
    color: var(--el-color-primary);
  }

  .text-secondary {
    color: var(--el-text-color-secondary);
  }

  .override-empty {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: center;
    color: var(--el-text-color-secondary);
  }
</style>
