<template>
  <div class="container">
    <SearchTable
      :form-model="searchForm"
      :form-items="filters"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      title="回收站"
      :pagination="{
        current: page,
        pageSize,
        total,
      }"
      :show-download="false"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="fetchData"
    >
      <!-- 序号列 -->
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 + (page - 1) * pageSize }}
      </template>

      <!-- 资源类型列 -->
      <template #resource_type="{ record }">
        <a-tag :color="getResourceTypeColor(record.resource_type)">
          {{ getResourceTypeText(record.resource_type) }}
        </a-tag>
      </template>

      <!-- 删除时间列 -->
      <template #deleted_time="{ record }">
        {{ formatTime(record.deleted_time) }}
      </template>

      <!-- 删除人列 -->
      <template #deleted_name="{ record }">
        {{ record.deleted_name || '-' }}
      </template>

      <!-- 操作列 -->
      <template #operation="{ record }">
        <a-space>
          <a-button type="text" size="small" @click="handleRestore(record)">
            恢复
          </a-button>
          <a-button
            type="text"
            size="small"
            status="danger"
            @click="handleDelete(record)"
          >
            彻底删除
          </a-button>
        </a-space>
      </template>
    </SearchTable>

    <!-- 恢复确认对话框 -->
    <a-modal
      v-model:visible="restoreConfirmVisible"
      title="恢复确认"
      @ok="handleConfirmRestore"
      @cancel="restoreConfirmVisible = false"
    >
      <p>
        确定要恢复「{{ recordToRestore?.resource_name }}」吗？
      </p>
      <p style="color: rgb(var(--primary-6))">恢复后资源将回到正常状态。</p>
    </a-modal>

    <!-- 彻底删除确认对话框 -->
    <a-modal
      v-model:visible="deleteConfirmVisible"
      title="彻底删除确认"
      @ok="handleConfirmDelete"
      @cancel="deleteConfirmVisible = false"
    >
      <p>
        确定要彻底删除「{{ recordToDelete?.resource_name }}」吗？
      </p>
      <p style="color: rgb(var(--danger-6))">
        警告：此操作不可恢复，删除后将无法找回！
      </p>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import SearchTable from '@/components/search-table/index.vue'
import type { FormItem } from '@/components/search-form/types'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import type { TrashRecord, FetchTrashListParams } from '@/api/kb/trash'
import {
  fetchTrashList,
  restoreTrash,
  deleteTrash,
  getResourceTypeText,
  getResourceTypeColor,
  resourceTypeOptions,
} from '@/api/kb/trash'

// 表格列配置
const columns = computed((): TableColumnData[] => [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 80,
    align: 'center',
  },
  {
    title: '标题',
    dataIndex: 'resource_name',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '分类',
    dataIndex: 'resource_type',
    slotName: 'resource_type',
    width: 120,
    align: 'center',
  },
  {
    title: '删除人',
    dataIndex: 'deleted_name',
    slotName: 'deleted_name',
    width: 120,
    align: 'center',
  },
  {
    title: '删除时间',
    dataIndex: 'deleted_time',
    slotName: 'deleted_time',
    width: 180,
    align: 'center',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    slotName: 'operation',
    width: 180,
    align: 'center',
    fixed: 'right',
  },
])

// 搜索表单配置
const filters = computed((): FormItem[] => [
  {
    label: '关键词',
    field: 'keyword',
    type: 'input',
    placeholder: '搜索标题',
    span: 6,
  },
  {
    label: '资源类型',
    field: 'resource_type',
    type: 'select',
    placeholder: '请选择资源类型',
    options: resourceTypeOptions,
    span: 6,
  },
])

// 搜索表单数据
const searchForm = reactive({
  keyword: '',
  resource_type: '',
})

// 处理表单模型更新
const handleFormModelUpdate = (newFormModel: Record<string, any>) => {
  Object.assign(searchForm, newFormModel)
}

// 表格数据
const tableData = ref<TrashRecord[]>([])
const loading = ref(false)

// 分页
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 恢复确认
const restoreConfirmVisible = ref(false)
const recordToRestore = ref<TrashRecord | null>(null)

// 删除确认
const deleteConfirmVisible = ref(false)
const recordToDelete = ref<TrashRecord | null>(null)

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const params: FetchTrashListParams = {
      page: page.value,
      page_size: pageSize.value,
      resource_type: (searchForm.resource_type || undefined) as
        | 'document'
        | 'faq'
        | undefined,
    }

    const res: any = await fetchTrashList(params)
    console.log('获取回收站列表成功:', res)
    if (res?.code === 0) {
      // 如果有关键词，在前端过滤
      let data = res.details?.data || []
      if (searchForm.keyword) {
        const keyword = searchForm.keyword.toLowerCase()
        data = data.filter(
          (item) =>
            item.resource_name?.toLowerCase().includes(keyword) ||
            item.deleted_name?.toLowerCase().includes(keyword)
        )
      }
      tableData.value = data
      total.value = res.details.total || 0
    }
  } catch (error) {
    console.error('获取回收站列表失败:', error)
    Message.error('获取回收站列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchData()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.resource_type = ''
  page.value = 1
  fetchData()
}

// 页码变化
const handlePageChange = (current: number) => {
  page.value = current
  fetchData()
}

// 格式化时间
const formatTime = (time: string | null): string => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-'
}

// 恢复资源
const handleRestore = (record: TrashRecord) => {
  recordToRestore.value = record
  restoreConfirmVisible.value = true
}

// 确认恢复
const handleConfirmRestore = async () => {
  if (!recordToRestore.value?.id) return

  try {
    loading.value = true
    const res = await restoreTrash({ id: recordToRestore.value.id })
    if (res?.code === 0) {
      Message.success('恢复成功')
      restoreConfirmVisible.value = false
      recordToRestore.value = null
      await fetchData()
    } else {
      Message.error(res?.message || '恢复失败')
    }
  } catch (error) {
    console.error('恢复失败:', error)
    Message.error('恢复失败')
  } finally {
    loading.value = false
  }
}

// 彻底删除
const handleDelete = (record: TrashRecord) => {
  recordToDelete.value = record
  deleteConfirmVisible.value = true
}

// 确认彻底删除
const handleConfirmDelete = async () => {
  if (!recordToDelete.value?.id) return

  try {
    loading.value = true
    const res = await deleteTrash({ id: recordToDelete.value.id })
    if (res?.code === 0) {
      Message.success('彻底删除成功')
      deleteConfirmVisible.value = false
      recordToDelete.value = null
      await fetchData()
    } else {
      Message.error(res?.message || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    Message.error('删除失败')
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>


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