<script setup>
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'

import { useLinksStore } from '@/stores/links'
import { useSettingsStore } from '@/stores/settings'
import { tagService } from '@/services/tagService'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:modelValue'])

const linksStore = useLinksStore()
const settingsStore = useSettingsStore()
const { allTags } = storeToRefs(linksStore)
const { state } = storeToRefs(settingsStore)

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

// 标签列表（带序号的对象数组）
const tagList = ref([])

// 初始化标签列表
function initTagList() {
  const currentOrder = state.value?.tagOrder || []
  const tags = allTags.value || []
  
  // 合并当前顺序和所有标签
  const ordered = []
  const unordered = []
  
  // 先添加有顺序的标签
  currentOrder.forEach((tag) => {
    if (tags.includes(tag)) {
      ordered.push(tag)
    }
  })
  
  // 再添加没有顺序的新标签
  tags.forEach((tag) => {
    if (!currentOrder.includes(tag)) {
      unordered.push(tag)
    }
  })
  unordered.sort()
  
  const allTagsOrdered = [...ordered, ...unordered]
  // 转换为带序号的对象数组
  tagList.value = allTagsOrdered.map((tag, index) => ({
    tag,
    order: index + 1,
  }))
}

// 根据序号重新排序
function reorderByNumbers() {
  // 按序号排序
  tagList.value.sort((a, b) => a.order - b.order)
  // 保存新的顺序
  saveTagOrder()
}

// 处理序号输入
function handleOrderChange(tagItem, newOrder) {
  const numOrder = parseInt(newOrder)
  const maxOrder = tagList.value.length
  
  // 验证输入
  let targetOrder = numOrder
  if (isNaN(numOrder) || numOrder < 1) {
    targetOrder = 1
  } else if (numOrder > maxOrder) {
    targetOrder = maxOrder
  }
  
  const oldOrder = tagItem.order
  tagItem.order = targetOrder
  
  // 处理冲突：交换序号
  if (oldOrder !== targetOrder) {
    const conflictItem = tagList.value.find(item => item !== tagItem && item.order === targetOrder)
    if (conflictItem) {
      conflictItem.order = oldOrder
    }
  }
  
  reorderByNumbers()
}

watch(
  () => props.modelValue,
  (open) => {
    if (open) {
      initTagList()
    }
  },
  { immediate: true }
)

watch(allTags, () => {
  if (visible.value) {
    initTagList()
  }
})

// 保存标签顺序
async function saveTagOrder() {
  try {
    const order = tagList.value.map(item => item.tag)
    await settingsStore.updateSettings({
      tagOrder: order,
    })
    ElMessage.success('标签顺序已保存')
  } catch (error) {
    console.error('保存标签顺序失败:', error)
    ElMessage.error('保存失败，请稍后再试')
  }
}

// 重置为默认顺序（按字母排序）
function resetOrder() {
  const tags = [...(allTags.value || [])]
  tags.sort()
  tagList.value = tags.map((tag, index) => ({
    tag,
    order: index + 1,
  }))
  saveTagOrder()
}
</script>

<template>
  <el-dialog v-model="visible" title="标签管理" width="500px">
    <div class="tag-manage-content">
      <div class="header-actions">
        <el-button size="small" text type="primary" @click="resetOrder">
          重置为字母顺序
        </el-button>
      </div>
      
      <div class="tag-list">
        <el-empty v-if="tagList.length === 0" description="暂无标签" />
        <div v-else class="sortable-tags">
          <div
            v-for="(item, index) in tagList"
            :key="item.tag"
            class="tag-item"
          >
            <div class="order-input-wrapper">
              <el-input-number
                v-model="item.order"
                :min="1"
                :max="tagList.length"
                :controls="false"
                size="small"
                class="order-input"
                @change="() => handleOrderChange(item, item.order)"
              />
            </div>
            <span class="tag-name">{{ item.tag }}</span>
            <span class="tag-count">{{ (linksStore.linksByTag?.get?.(item.tag)?.length) || 0 }} 个书签</span>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.tag-manage-content {
  min-height: 200px;
}

.header-actions {
  margin-bottom: 16px;
  text-align: right;
}

.tag-list {
  max-height: 400px;
  overflow-y: auto;
}

.sortable-tags {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tag-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: var(--color-bg-muted);
  border: 1px solid var(--color-border);
  border-radius: 6px;
  transition: all 0.2s;
  gap: 12px;
}

.tag-item:hover {
  background: var(--color-bg-subtle);
  border-color: var(--color-border-strong);
}

.order-input-wrapper {
  width: 80px;
  flex-shrink: 0;
}

.order-input {
  width: 100%;
}

.order-input :deep(.el-input__inner) {
  text-align: center;
  padding: 0 8px;
}

.tag-name {
  flex: 1;
  font-weight: 500;
  color: var(--color-text-primary);
}

.tag-count {
  font-size: 12px;
  color: var(--color-text-muted);
  margin-left: auto;
}
</style>

