<template>
  <el-dialog
    v-model="visible"
    title="类型切换确认"
    width="600px"
    :close-on-click-modal="false"
  >
    <div class="type-change-handler">
      <el-alert
        type="warning"
        :closable="false"
        show-icon
        class="change-alert"
      >
        <template #title>
          检测到类型变更，部分元数据字段可能需要处理
        </template>
      </el-alert>

      <div v-if="conflicts.length > 0" class="conflicts-section">
        <h4 class="section-title">需要处理的字段</h4>
        <el-table :data="conflicts" stripe size="small">
          <el-table-column prop="label" label="字段名" width="120" />
          <el-table-column label="当前值" width="150">
            <template #default="{ row }">
              {{ formatValue(row.old_value) }}
            </template>
          </el-table-column>
          <el-table-column label="冲突原因" min-width="120">
            <template #default="{ row }">
              <el-tag :type="row.conflict_type === 'removed' ? 'danger' : 'warning'" size="small">
                {{ row.conflict_type === 'removed' ? '字段不存在' : '类型不匹配' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="处理方式" width="140">
            <template #default="{ row }">
              <el-select v-model="row.action" size="small" style="width: 100%">
                <el-option label="移除" value="remove" />
                <el-option
                  v-if="row.map_to"
                  :label="`映射到 ${row.map_to}`"
                  value="map"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="preserved.length > 0" class="preserved-section">
        <h4 class="section-title">
          <el-icon class="success-icon"><CircleCheckFilled /></el-icon>
          保留的字段 ({{ preserved.length }})
        </h4>
        <div class="preserved-tags">
          <el-tag
            v-for="item in preserved"
            :key="item.field_key"
            type="success"
            size="small"
            class="preserved-tag"
          >
            {{ item.field_key }}: {{ formatValue(item.value) }}
          </el-tag>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleCancel">取消切换</el-button>
      <el-button type="primary" @click="handleConfirm">
        确认切换
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { CircleCheckFilled } from '@element-plus/icons-vue'
import type { MetadataFieldDefinition, MetadataPayload, MetadataScope, TypeChangeConflict } from '@/types/metadata'

interface ConflictItem extends TypeChangeConflict {
  action: 'remove' | 'map'
}

const props = defineProps<{
  show: boolean
  oldScope: MetadataScope
  newScope: MetadataScope
  currentMetadata: MetadataPayload
  oldFields: MetadataFieldDefinition[]
  newFields: MetadataFieldDefinition[]
}>()

const emit = defineEmits<{
  (e: 'update:show', value: boolean): void
  (e: 'confirm', result: { metadata: MetadataPayload; removed: string[] }): void
  (e: 'cancel'): void
}>()

const visible = computed({
  get: () => props.show,
  set: (val) => emit('update:show', val)
})

const conflicts = ref<ConflictItem[]>([])
const preserved = ref<{ field_key: string; value: string | number | boolean | string[] | undefined }[]>([])

const analyzeCompatibility = () => {
  conflicts.value = []
  preserved.value = []

  const newFieldKeys = new Set(props.newFields.map(f => f.field_key))
  const newFieldTypes = new Map(props.newFields.map(f => [f.field_key, f.type]))

  Object.entries(props.currentMetadata).forEach(([key, value]) => {
    if (value === undefined || value === null) return

    if (!newFieldKeys.has(key)) {
      const oldField = props.oldFields.find(f => f.field_key === key)
      conflicts.value.push({
        field_key: key,
        label: oldField?.label || key,
        conflict_type: 'removed',
        old_value: value,
        suggested_action: 'remove',
        action: 'remove'
      })
    } else {
      const newType = newFieldTypes.get(key)
      const oldField = props.oldFields.find(f => f.field_key === key)
      const oldType = oldField?.type

      if (oldType !== newType) {
        conflicts.value.push({
          field_key: key,
          label: oldField?.label || key,
          conflict_type: 'type_mismatch',
          old_value: value,
          suggested_action: 'remove',
          action: 'remove'
        })
      } else {
        preserved.value.push({ field_key: key, value })
      }
    }
  })
}

const formatValue = (value: string | number | boolean | string[] | undefined): string => {
  if (value === undefined || value === null) return '无'
  if (Array.isArray(value)) return value.join(', ')
  return String(value)
}

const handleConfirm = () => {
  const newMetadata: MetadataPayload = {}
  const removed: string[] = []

  preserved.value.forEach(item => {
    newMetadata[item.field_key] = item.value
  })

  conflicts.value.forEach(item => {
    if (item.action === 'remove') {
      removed.push(item.field_key)
    } else if (item.action === 'map' && item.map_to) {
      newMetadata[item.map_to] = item.old_value
    }
  })

  emit('confirm', { metadata: newMetadata, removed })
  visible.value = false
}

const handleCancel = () => {
  emit('cancel')
  visible.value = false
}

watch(() => props.show, (show) => {
  if (show) {
    analyzeCompatibility()
  }
})
</script>

<style scoped>
.type-change-handler {
  max-height: 400px;
  overflow-y: auto;
}

.change-alert {
  margin-bottom: 16px;
}

.section-title {
  margin: 16px 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 6px;
}

.success-icon {
  color: var(--el-color-success);
}

.conflicts-section {
  margin-bottom: 16px;
}

.preserved-section {
  margin-top: 16px;
}

.preserved-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.preserved-tag {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
