<template>
  <a-drawer
    v-model:visible="visible"
    title="设置"
    width="600px"
    :footer="false"
    unmount-on-close
  >
    <a-tabs default-active-key="tab-config">
      <!-- Tab 配置 -->
      <a-tab-pane key="tab-config" title="Tab 配置">
        <a-space direction="vertical" style="width: 100%" :size="16">

          <!-- 说明文字 -->
          <a-alert type="info" :show-icon="true">
            拖拽可调整 Tab 顺序，勾选复选框控制显示，单选按钮设置默认打开的 Tab
          </a-alert>

          <!-- 统一的 Tab 配置列表 -->
          <div class="tab-config-list">
            <div
              v-for="(tabKey, index) in localConfig.visibleTabs"
              :key="tabKey"
              class="tab-config-item"
              draggable="true"
              @dragstart="handleDragStart(index, $event)"
              @dragover.prevent="handleDragOver(index, $event)"
              @drop="handleDrop(index, $event)"
              @dragend="handleDragEnd"
            >
              <!-- 拖拽手柄 -->
              <icon-drag-arrow class="drag-handle" />

              <!-- 显示/隐藏复选框 -->
              <a-checkbox
                :model-value="isTabVisible(tabKey)"
                :disabled="!isTabEnabled(tabKey) || isLastVisibleTab(tabKey)"
                @change="(value) => handleTabVisibilityChange(tabKey, value)"
              />

              <!-- Tab 标题 -->
              <span class="tab-title">{{ getTabTitle(tabKey) }}</span>

              <!-- 默认 Tab 单选按钮 -->
              <a-radio
                :model-value="localConfig.defaultTab"
                :value="tabKey"
                @change="() => localConfig.defaultTab = tabKey"
              >
                默认
              </a-radio>
            </div>

            <!-- 隐藏的 Tabs -->
            <a-divider v-if="hasHiddenTabs">隐藏的 Tabs</a-divider>
            <div
              v-for="tab in hiddenTabs"
              :key="'hidden-' + tab.key"
              class="tab-config-item hidden"
            >
              <icon-drag-arrow class="drag-handle disabled" />
              <a-checkbox
                :model-value="false"
                :disabled="!tab.enabled"
                @change="(value) => handleTabVisibilityChange(tab.key, value)"
              />
              <span class="tab-title">{{ tab.title }}</span>
              <span class="hidden-tag">已隐藏</span>
            </div>
          </div>

          <a-alert
            v-if="localConfig.visibleTabs.length === 0"
            type="warning"
          >
            至少需要保留一个可见的 Tab
          </a-alert>

          <!-- 保存按钮 -->
          <a-space>
            <a-button type="primary" @click="handleSave" :loading="saving">
              <template #icon>
                <icon-check />
              </template>
              保存配置
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>

        </a-space>
      </a-tab-pane>

      <!-- 版本更新 -->
      <a-tab-pane key="update" title="版本更新">
        <UpdatePanel @open-version-history="handleOpenVersionHistory" />
      </a-tab-pane>
    </a-tabs>
  </a-drawer>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconDragArrow, IconCheck, IconRefresh } from '@arco-design/web-vue/es/icon'
import UpdatePanel from './UpdatePanel.vue'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  config: {
    type: Object,
    required: true
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'save', 'open-version-history'])

// 状态
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const localConfig = ref({
  tabs: [],
  visibleTabs: [],
  defaultTab: ''
})

const saving = ref(false)
const draggedIndex = ref(null)

// 隐藏的 Tabs（不在 visibleTabs 中）
const hiddenTabs = computed(() => {
  return localConfig.value.tabs.filter(tab => !localConfig.value.visibleTabs.includes(tab.key))
})

// 是否有隐藏的 Tabs
const hasHiddenTabs = computed(() => {
  return hiddenTabs.value.length > 0
})

// 初始化本地配置
watch(() => props.config, (newConfig) => {
  if (newConfig && newConfig.tabs) {
    localConfig.value = {
      tabs: [...newConfig.tabs],
      visibleTabs: [...newConfig.visibleTabs],
      defaultTab: newConfig.defaultTab
    }
  }
}, { immediate: true, deep: true })

// 获取 Tab 标题
const getTabTitle = (key) => {
  const tab = localConfig.value.tabs.find(t => t.key === key)
  return tab ? tab.title : key
}

// 判断 Tab 是否可见
const isTabVisible = (key) => {
  return localConfig.value.visibleTabs.includes(key)
}

// 判断 Tab 是否启用
const isTabEnabled = (key) => {
  const tab = localConfig.value.tabs.find(t => t.key === key)
  return tab ? tab.enabled : false
}

// 判断是否是最后一个可见 Tab
const isLastVisibleTab = (key) => {
  return localConfig.value.visibleTabs.length === 1 && localConfig.value.visibleTabs[0] === key
}

// 处理单个 Tab 可见性变化
const handleTabVisibilityChange = (tabKey, visible) => {
  if (visible) {
    // 显示 Tab：添加到 visibleTabs 末尾
    if (!localConfig.value.visibleTabs.includes(tabKey)) {
      localConfig.value.visibleTabs.push(tabKey)
    }
  } else {
    // 隐藏 Tab：从 visibleTabs 中移除
    // 至少保留一个 Tab
    if (localConfig.value.visibleTabs.length <= 1) {
      Message.warning('至少需要保留一个可见的 Tab')
      return
    }

    // 如果隐藏的是默认 Tab，需要更改默认 Tab
    if (localConfig.value.defaultTab === tabKey) {
      const remainingTabs = localConfig.value.visibleTabs.filter(k => k !== tabKey)
      localConfig.value.defaultTab = remainingTabs[0] || ''
    }

    localConfig.value.visibleTabs = localConfig.value.visibleTabs.filter(k => k !== tabKey)
  }

  // 同步更新 tabs 数组中的 visible 属性
  localConfig.value.tabs = localConfig.value.tabs.map(tab => ({
    ...tab,
    visible: localConfig.value.visibleTabs.includes(tab.key)
  }))
}

// 拖拽开始
const handleDragStart = (index, event) => {
  draggedIndex.value = index
  event.dataTransfer.effectAllowed = 'move'
  event.target.classList.add('dragging')
}

// 拖拽经过
const handleDragOver = (index, event) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'move'
}

// 放置
const handleDrop = (index, event) => {
  event.preventDefault()
  if (draggedIndex.value === null || draggedIndex.value === index) return

  const list = [...localConfig.value.visibleTabs]
  const [removed] = list.splice(draggedIndex.value, 1)
  list.splice(index, 0, removed)
  localConfig.value.visibleTabs = list
}

// 拖拽结束
const handleDragEnd = (event) => {
  event.target.classList.remove('dragging')
  draggedIndex.value = null
}

// 保存配置
const handleSave = async () => {
  // 验证：至少保留一个可见 Tab
  if (localConfig.value.visibleTabs.length < 1) {
    Message.error('至少需要保留一个可见的 Tab')
    return
  }

  // 验证：默认 Tab 必须在可见列表中
  if (!localConfig.value.visibleTabs.includes(localConfig.value.defaultTab)) {
    Message.error('默认 Tab 必须在可见列表中')
    return
  }

  // 确保 tabs 数组中的 visible 属性与 visibleTabs 完全同步
  const syncedTabs = localConfig.value.tabs.map(tab => ({
    ...tab,
    visible: localConfig.value.visibleTabs.includes(tab.key)
  }))

  const configToSave = {
    tabs: syncedTabs,
    visibleTabs: [...localConfig.value.visibleTabs],
    defaultTab: localConfig.value.defaultTab
  }

  saving.value = true

  try {
    await emit('save', configToSave)
  } catch (error) {
    console.error('保存配置失败:', error)
    Message.error('保存配置失败：' + (error.message || error))
  } finally {
    saving.value = false
  }
}

// 重置配置
const handleReset = () => {
  if (props.config) {
    localConfig.value = {
      tabs: [...props.config.tabs],
      visibleTabs: [...props.config.visibleTabs],
      defaultTab: props.config.defaultTab
    }
  }
}

// 打开版本历史
const handleOpenVersionHistory = () => {
  emit('open-version-history')
}
</script>

<style scoped>
.tab-config-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tab-config-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: var(--color-fill-1);
  border: 1px solid var(--color-border);
  border-radius: 6px;
  cursor: move;
  transition: all 0.2s;
  user-select: none;
}

.tab-config-item.dragging {
  opacity: 0.5;
  background: var(--color-fill-2);
  transform: scale(0.98);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.tab-config-item:hover {
  background: var(--color-fill-2);
  border-color: var(--color-border-2);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.tab-config-item.hidden {
  opacity: 0.6;
  cursor: default;
}

.tab-config-item.hidden:hover {
  border-color: var(--color-border);
  box-shadow: none;
}

.drag-handle {
  color: var(--color-text-3);
  cursor: grab;
  flex-shrink: 0;
  font-size: 18px;
}

.drag-handle.disabled {
  cursor: not-allowed;
  opacity: 0.3;
}

.tab-config-item:hover .drag-handle:not(.disabled) {
  color: var(--color-text-1);
}

.tab-title {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text-1);
}

.hidden-tag {
  font-size: 12px;
  color: var(--color-text-3);
  padding: 2px 8px;
  background: var(--color-fill-3);
  border-radius: 4px;
}
</style>
