<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="标签管理"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @refresh="handleRefresh"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
    >
      <template #toolbar-left>
        <a-button type="primary" @click="handleCreate">
          新增标签
        </a-button>
      </template>

      <!-- 序号 -->
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>

      <!-- 标签类型 -->
      <template #type="{ record }">
        <a-tag :color="getTypeColor(record.type)">
          {{ getTypeLabel(record.type) }}
        </a-tag>
      </template>

      <!-- 操作 -->
      <template #actions="{ record }">
        <a-button type="text" size="small" @click="handleEdit(record)">
          编辑
        </a-button>
        <a-button type="text" size="small" status="danger" @click="handleDelete(record)">
          删除
        </a-button>
      </template>
    </search-table>

    <!-- 标签表单对话框（新增/编辑） -->
    <category-form-dialog
      v-model:visible="formVisible"
      :category="editingCategory"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import {
  fetchCategoryList,
  deleteCategory,
  type Category,
} from '@/api/kb/category'
import CategoryFormDialog from './components/CategoryFormDialog.vue'

// 状态管理
const loading = ref(false)
const allData = ref<Category[]>([]) // 存储全量数据
const tableData = ref<Category[]>([]) // 当前页数据
const formModel = ref({
  keyword: '',
  type: '',
})

// 分页状态
const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
})

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    field: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '请输入标签名称',
  },
  {
    field: 'type',
    label: '标签类型',
    type: 'select',
    placeholder: '请选择标签类型',
    options: [
      { label: '文档标签', value: 'document' },
      { label: 'FAQ标签', value: 'faq' },
      { label: '通用标签', value: 'general' },
    ],
    allowClear: true,
  },
])

// 表格列配置
const columns = computed(() => [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 80,
    align: 'center' as const,
  },
  {
    title: '标签名称',
    dataIndex: 'name',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '标签描述',
    dataIndex: 'description',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '标签类型',
    dataIndex: 'type',
    slotName: 'type',
    width: 120,
    align: 'center' as const,
  },
  {
    title: '排序',
    dataIndex: 'sort_order',
    width: 80,
    align: 'center' as const,
  },
  {
    title: '备注信息',
    dataIndex: 'remarks',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '操作',
    slotName: 'actions',
    width: 250,
    fixed: 'right' as const,
  },
])

// 当前选中的标签
const editingCategory = ref<Category | null>(null)

// 对话框可见性
const formVisible = ref(false)

// 获取标签类型标签
const getTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    document: '文档标签',
    faq: 'FAQ标签',
    general: '通用标签',
  }
  return typeMap[type] || type
}

// 获取标签类型颜色
const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    document: 'blue',
    faq: 'green',
    general: 'orange',
  }
  return colorMap[type] || 'gray'
}

// 更新表格数据（前端分页）
const updateTableData = () => {
  const { current, pageSize } = pagination.value
  const start = (current - 1) * pageSize
  const end = start + pageSize
  tableData.value = allData.value.slice(start, end)
}

// 获取标签列表
const fetchCategories = async () => {
  loading.value = true

  try {
    const params: any = {}

    if (formModel.value.type) {
      params.type = formModel.value.type
    }

    const res: any = await fetchCategoryList(params)

    if (res.code === 0) {
      let data = res.details || []
      
      // 如果有关键词搜索，进行过滤
      if (formModel.value.keyword) {
        data = data.filter((item: Category) =>
          item.name.toLowerCase().includes(formModel.value.keyword.toLowerCase())
        )
      }
      
      // 保存全量数据并更新分页
      allData.value = data
      pagination.value.total = data.length
      // 重置到第一页
      pagination.value.current = 1
      updateTableData()
    } else {
      Message.error(res.message || '获取标签列表失败')
      allData.value = []
      tableData.value = []
      pagination.value.total = 0
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    Message.error('获取标签列表失败')
    allData.value = []
    tableData.value = []
    pagination.value.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  fetchCategories()
}

// 处理表单模型更新
const handleFormModelUpdate = (value: any) => {
  formModel.value = value
}

// 重置
const handleReset = () => {
  formModel.value = {
    keyword: '',
    type: '',
  }
  fetchCategories()
}

// 刷新
const handleRefresh = () => {
  fetchCategories()
  Message.success('数据已刷新')
}

// 分页切换
const handlePageChange = (current: number) => {
  pagination.value.current = current
  updateTableData()
}

// 每页条数切换
const handlePageSizeChange = (pageSize: number) => {
  pagination.value.current = 1
  pagination.value.pageSize = pageSize
  updateTableData()
}

// 新增标签
const handleCreate = () => {
  editingCategory.value = null
  formVisible.value = true
}

// 编辑标签
const handleEdit = (record: Category) => {
  editingCategory.value = { ...record }
  formVisible.value = true
}

// 删除标签
const handleDelete = async (record: Category) => {
  Modal.confirm({
    title: '确认删除',
    content: `确认删除标签「${record.name}」吗？`,
    onOk: async () => {
      try {
        const res: any = await deleteCategory(record.id)
        if (res.code === 0) {
          Message.success('删除成功')
          fetchCategories()
        } else {
          Message.error(res.message || '删除失败')
        }
      } catch (error) {
        console.error('删除标签失败:', error)
        Message.error('删除失败')
      }
    },
  })
}

// 表单成功回调
const handleFormSuccess = () => {
  formVisible.value = false
  fetchCategories()
}

// 初始化加载数据
onMounted(() => {
  fetchCategories()
})
</script>

<script lang="ts">
export default {
  name: 'KbCategoryManage',
}
</script>

<style scoped lang="less">
.container {
  margin-top: 20px;
}
</style>