<script setup lang="tsx">
import { onMounted, inject, ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { AxiosInstance } from 'axios'
import { type DataTableColumn, type DataTableRowKey, useMessage, useDialog } from 'naive-ui'
import ImportDomainDialog from '../components/ImportDomainDialog.vue'
import AddDomainDialog from '../components/AddDomainDialog.vue'
import EditDomainDialog from '../components/EditDomainDialog.vue'
import { convertTimestampToDate } from '@/utils/common'

const axios = inject('axios') as AxiosInstance
const message = useMessage()
const dialog = useDialog()
const route = useRoute()
const router = useRouter()

// 筛选条件
const filterForm = ref({
  domain: '',
  status: null as number | null,
})

// 状态选项
const statusOptions = [
  { label: '全部', value: null },
  { label: 'READY', value: 1 },
  { label: 'QUEUE', value: 2 },
  { label: 'CRAWLING', value: 3 },
  { label: 'PAUSE', value: 999 },
]

const showImportDialog = ref(false)
const showAddDialog = ref(false)
const showEditDialog = ref(false)

// 当前正在编辑的域名 ID 列表（单个或批量）
const editingDomainIds = ref<DataTableRowKey[] | null>(null)

// 选中行的 Key
const checkedRowKeys = ref<DataTableRowKey[]>([])

// 分页相关状态
const pagination = ref({
  page: 1,
  pageSize: 50,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 200, 500, 1000],
  onChange: (page: number) => {
    pagination.value.page = page
    updateUrlParams()
    getDomainList()
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.value.pageSize = pageSize
    pagination.value.page = 1
    updateUrlParams()
    getDomainList()
  },
})

// 更新URL参数
const updateUrlParams = () => {
  router.push({
    query: {
      page: pagination.value.page,
      size: pagination.value.pageSize,
      domain: filterForm.value.domain || undefined,
      status: filterForm.value.status || undefined,
    },
  })
}

// 初始化分页参数
const initPagination = () => {
  const page = Number(route.query.page) || 1
  const size = Number(route.query.size) || 50
  const domain = route.query.domain as string || ''
  const status = route.query.status ? Number(route.query.status) : null
  
  pagination.value.page = page
  pagination.value.pageSize = size
  filterForm.value.domain = domain
  filterForm.value.status = status
}

const columns: Array<DataTableColumn> = [
  {
    type: 'selection',
  },
  {
    title: '#',
    key: 'id',
  },
  {
    title: '域名',
    key: 'domain',
  },
  {
    title: '状态',
    key: 'status',
    render: (row) => {
      let statusText = ''
      let statusType = ''

      switch (row.status) {
        case 1:
          statusText = 'READY'
          statusType = 'success'
          break
        case 2:
          statusText = 'QUENE'
          statusType = 'warning'
          break
        case 3:
          statusText = 'CRAWLING'
          statusType = 'info'
          break
        case 999:
          statusText = 'PAUSE'
          statusType = 'error'
          break
        default:
          statusText = 'UNKNOWN'
          statusType = 'error'
      }

      return <n-tag type={statusType}>{statusText}</n-tag>
    },
  },
  {
    title: '采集间隔 (分钟)',
    key: 'crawl_interval',
    render: (row) => (
      <n-tooltip>
        {{
          trigger: () => <span>{row.crawl_interval}</span>,
          default: () => `约 ${(row.crawl_interval as number) / 60 / 24} 天`,
        }}
      </n-tooltip>
    ),
  },
  {
    title: '最近采集时间',
    key: 'latest_crawl_time',
    render: (row) => convertTimestampToDate(row.latest_crawl_time as number),
  },
  {
    title: '操作',
    key: 'action',
    render: (row) => (
      <div class="flex gap-2">
        <n-button size="small" type="primary" onClick={() => handleEdit(row)}>
          编辑
        </n-button>
        <n-button size="small" type="info" onClick={() => handleSingleCrawl(row)}>
          立即采集
        </n-button>
        <n-button size="small" type="error" onClick={() => handleDelete(row)}>
          删除
        </n-button>
      </div>
    ),
  },
]

const domains = ref([])

// 是否有选中的行
const hasSelectedRows = computed(() => checkedRowKeys.value.length > 0)

// 处理选中行变化
const handleCheck = (rowKeys: DataTableRowKey[]) => {
  checkedRowKeys.value = rowKeys
}

/** 批量删除域名 */
const handleBatchDelete = () => {
  if (!hasSelectedRows.value) {
    message.warning('请至少选择一个域名')
    return
  }
  const removeSurl = ref(false)
  dialog.warning({
    title: '确认批量删除',
    content: () => (
      <div>
        <div class="mb-2">确定要删除选中的 {checkedRowKeys.value.length} 个域名吗？</div>
        <n-checkbox v-model:checked={removeSurl.value}>同时删除所有关联的 SURL</n-checkbox>
      </div>
    ),
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        const response = (
          await axios.post('/api/domain/v1/delete', {
            domain_ids: checkedRowKeys.value,
            remove_surl: removeSurl.value,
          })
        ).data
        if (response.code !== 20000) {
          message.error(`批量删除域名失败，错误：${response.message}`)
          return
        }
        message.success('批量删除成功')
        checkedRowKeys.value = [] // 清空选择
        getDomainList()
      } catch (error) {
        console.error('批量删除域名失败', error)
        message.error(`批量删除域名失败，错误：${error}`)
      }
    },
  })
}

/** 批量修改采集间隔 */
const handleBatchEdit = () => {
  if (!hasSelectedRows.value) {
    message.warning('请至少选择一个域名')
    return
  }
  editingDomainIds.value = [...checkedRowKeys.value] // 设置要编辑的 ID 为当前选中的 ID
  showEditDialog.value = true
}

/** 批量立即采集 */
const handleBatchCrawl = async () => {
  if (!hasSelectedRows.value) {
    message.warning('请至少选择一个域名')
    return
  }
  try {
    // TODO: 确认后端是否有 /api/domain/v1/crawl 接口
    const response = (
      await axios.post('/api/domain/v1/crawl', {
        domain_ids: checkedRowKeys.value,
      })
    ).data

    if (response.code !== 20000) {
      message.error(`批量触发采集失败：${response.message}`)
      return
    }

    message.success('批量触发采集成功，已加入队列')
    checkedRowKeys.value = [] // 清空选择
    getDomainList() // 刷新列表查看状态变化
  } catch (error) {
    console.error('批量触发采集失败', error)
    message.error(`批量触发采集失败：${error}`)
  }
}

/** 单个立即采集 */
const handleSingleCrawl = async (row: any) => {
  try {
    // 调用与批量采集相同的接口，但只传单个 ID
    const response = (
      await axios.post('/api/domain/v1/crawl', {
        domain_ids: [row.id],
      })
    ).data

    if (response.code !== 20000) {
      message.error(`触发采集失败：${response.message}`)
      return
    }

    message.success(`域名 ${row.domain} 已加入采集队列`)
    getDomainList() // 刷新列表查看状态变化
  } catch (error) {
    console.error('触发采集失败', error)
    message.error(`触发采集失败：${error}`)
  }
}

/** 删除域名 */
const handleDelete = async (row: any) => {
  const removeSurl = ref(false)

  dialog.warning({
    title: '确认删除',
    content: () => (
      <div>
        <div class="mb-2">确定要删除域名 {row.domain} 吗？</div>
        <n-checkbox v-model:checked={removeSurl.value}>同时删除所有关联的 SURL</n-checkbox>
      </div>
    ),
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        const response = (
          await axios.post('/api/domain/v1/delete', {
            domain_ids: [row.id],
            remove_surl: removeSurl.value,
          })
        ).data
        if (response.code !== 20000) {
          message.error(`删除域名失败，错误：${response.message}`)
          return
        }
        message.success('删除成功')
        // 如果删除的是选中的行，也从 checkedRowKeys 中移除
        const index = checkedRowKeys.value.findIndex((key) => key === row.id)
        if (index > -1) {
          checkedRowKeys.value.splice(index, 1)
        }
        getDomainList()
      } catch (error) {
        console.error('删除域名失败', error)
        message.error(`删除域名失败，错误：${error}`)
      }
    },
  })
}

/** 获取域名列表 */
const getDomainList = async () => {
  try {
    const response = (
      await axios.get('/api/domain/v1/list', {
        params: {
          page: pagination.value.page,
          size: pagination.value.pageSize,
          domain: filterForm.value.domain || undefined,
          status: filterForm.value.status || undefined,
        },
      })
    ).data
    if (response.code !== 20000) {
      message.error(`获取域名列表失败，错误：${response.message}`)
      return
    }

    domains.value = response.data.rows
    pagination.value.itemCount = response.data.total
  } catch (error) {
    console.error('获取域名列表失败', error)
    message.error(`获取域名列表失败，错误：${error}`)
  }
}

const handleImportSuccess = () => {
  getDomainList()
}

const handleAddSuccess = () => {
  getDomainList()
}

/** 编辑域名 */
const handleEdit = (row: any) => {
  editingDomainIds.value = [row.id] // 设置要编辑的 ID 为当前行的 ID
  showEditDialog.value = true
}

const handleEditSuccess = () => {
  getDomainList()
  const editedCount = editingDomainIds.value?.length || 0
  editingDomainIds.value = null // 清空正在编辑的 ID
  // 如果是批量编辑，成功后清空表格的选择
  if (editedCount > 1) {
    checkedRowKeys.value = []
  }
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    domain: '',
    status: null,
  }
  pagination.value.page = 1
  updateUrlParams()
  getDomainList()
}

// 应用筛选
const applyFilter = () => {
  pagination.value.page = 1
  updateUrlParams()
  getDomainList()
}

onMounted(async () => {
  initPagination()
  await getDomainList()
})
</script>

<template>
  <div class="text-2xl pb-4">域名管理</div>
  <div class="flex gap-2 mb-4">
    <n-button type="primary" @click="showImportDialog = true">通过文件导入</n-button>
    <n-button type="primary" @click="showAddDialog = true">手动添加</n-button>
    <n-button type="error" @click="handleBatchDelete" :disabled="!hasSelectedRows">批量删除</n-button>
    <n-button type="warning" @click="handleBatchEdit" :disabled="!hasSelectedRows">修改间隔</n-button>
    <n-button type="info" @click="handleBatchCrawl" :disabled="!hasSelectedRows">立即采集</n-button>
  </div>

  <!-- 筛选表单 -->
  <n-form inline :model="filterForm" class="mb-4 p-4 bg-gray-50 rounded-lg">
    <n-form-item label="域名" path="domain">
      <n-input v-model:value="filterForm.domain" placeholder="请输入域名" clearable @keydown.enter="applyFilter" />
    </n-form-item>
    <n-form-item label="状态" path="status">
      <n-select v-model:value="filterForm.status" :options="statusOptions" placeholder="请选择状态" style="width: 200px" />
    </n-form-item>
    <n-form-item>
      <n-button type="primary" @click="applyFilter">筛选</n-button>
      <n-button class="ml-2" @click="resetFilter">重置</n-button>
    </n-form-item>
  </n-form>

  <n-data-table :columns="columns" :data="domains" :row-key="(row: any) => row.id" :checked-row-keys="checkedRowKeys"
    @update:checked-row-keys="handleCheck" size="small" />

  <div class="flex justify-center mt-4">
    <n-pagination v-model:page="pagination.page" :page-size="pagination.pageSize" :item-count="pagination.itemCount"
      :show-size-picker="pagination.showSizePicker" :page-sizes="pagination.pageSizes"
      @update:page-size="pagination.onUpdatePageSize" @update:page="pagination.onChange" />
  </div>

  <ImportDomainDialog v-model:show="showImportDialog" @success="handleImportSuccess" />
  <AddDomainDialog v-model:show="showAddDialog" @success="handleAddSuccess" />
  <EditDomainDialog v-model:show="showEditDialog" :domain-ids="editingDomainIds" @success="handleEditSuccess"
    @close="editingDomainIds = null" />
</template>
