<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, NDropdown } from 'naive-ui'
import { convertTimestampToDate } from '@/utils/common'

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

// 搜索条件
const searchForm = ref({
  domain: '',
  surl: '',
  is_report_by_one: 2,
  is_report_by_site: 2,
  is_report_by_wap: 2,
  has_evidence: 2,
})

// 选项数据
const options = [
  { label: '全部', value: 2 },
  { label: '是', value: 1 },
  { label: '否', value: 0 },
]

// 分页相关状态
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()
    getUrlList()
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.value.pageSize = pageSize
    pagination.value.page = 1
    updateUrlParams()
    getUrlList()
  },
})

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

// 初始化分页参数
const initPagination = () => {
  const page = Number(route.query.page) || 1
  const size = Number(route.query.size) || 50
  pagination.value.page = page
  pagination.value.pageSize = size
}

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

// 举报选项
const reportOptions = [
  {
    label: '全部渠道',
    key: 'all',
  },
  {
    label: 'PC渠道',
    key: 'pc',
  },
  {
    label: 'SITE渠道',
    key: 'site',
  },
  {
    label: 'WAP渠道',
    key: 'wap',
  },
]

const columns: Array<DataTableColumn> = [
  {
    type: 'selection',
  },
  {
    title: '#',
    key: 'id',
    minWidth: 60,
  },
  {
    title: '域名',
    key: 'domain',
    minWidth: 200,
  },
  {
    title: 'SURL',
    key: 'surl',
    minWidth: 100,
  },
  {
    title: 'Q',
    key: 'q',
    minWidth: 100,
  },
  {
    title: 'Token',
    key: 'token',
    minWidth: 100,
  },
  {
    title: '已通过PC举报',
    key: 'is_report_by_one',
    render: (row) => (
      <n-tag type={row.is_report_by_one ? 'success' : 'default'}>
        {row.is_report_by_one ? '是' : '否'}
      </n-tag>
    ),
  },
  {
    title: '已通过site举报',
    key: 'is_report_by_site',
    render: (row) => (
      <n-tag type={row.is_report_by_site ? 'success' : 'default'}>
        {row.is_report_by_site ? '是' : '否'}
      </n-tag>
    ),
  },
  {
    title: '已通过WAP举报',
    key: 'is_report_by_wap',
    render: (row) => (
      <n-tag type={row.is_report_by_wap ? 'success' : 'default'}>
        {row.is_report_by_wap ? '是' : '否'}
      </n-tag>
    ),
  },
  {
    title: '已收集证据',
    key: 'has_evidence',
    render: (row) => (
      <n-tag type={row.has_evidence ? 'success' : 'default'}>
        {row.has_evidence ? '是' : '否'}
      </n-tag>
    ),
  },
  {
    title: '操作',
    key: 'action',
    render: (row) => {
      return (
        <div class="flex gap-2">
          <n-dropdown
            trigger="click"
            options={reportOptions}
            onSelect={(key: string) => handleSingleReport(row, key)}
          >
            <n-button size="small" type="primary">举报</n-button>
          </n-dropdown>
          <n-button
            size="small"
            type="info"
            onClick={() => handleSingleCollectEvidence(row)}
          >
            收集证据
          </n-button>
        </div>
      )
    },
  },
]

const urls = ref([])

// 获取URL列表
const getUrlList = async () => {
  try {
    const response = (
      await axios.get('/api/urls/v1/list', {
        params: {
          ...searchForm.value,
          page: pagination.value.page,
          size: pagination.value.pageSize,
        },
      })
    ).data

    if (response.code !== 20000) {
      message.error(`获取URL列表失败：${response.message}`)
      return
    }

    urls.value = response.data.data
    console.log('response.data.total:', response.data.total)
    pagination.value.itemCount = response.data.total
  } catch (error) {
    console.error('获取URL列表失败', error)
    message.error(`获取URL列表失败：${error}`)
  }
}

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

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    domain: '',
    surl: '',
    is_report_by_one: 2,
    is_report_by_site: 2,
    is_report_by_wap: 2,
    has_evidence: 2,
  }
  handleSearch()
}

// 处理举报
const handleReport = async (ids: number[], option: string) => {
  // 检查是否有证据
  const selectedUrls = urls.value.filter((url: any) => ids.includes(url.id))
  const hasNoEvidence = selectedUrls.some((url: any) => !url.has_evidence)

  if (hasNoEvidence) {
    message.warning('请先收集证据后再进行举报')
    return
  }

  try {
    const response = (await axios.post('/api/urls/v1/report', {
      ids,
      report_by_one: option === 'all' || option === 'pc',
      report_by_site: option === 'all' || option === 'site',
      report_by_wap: option === 'all' || option === 'wap',
    })).data

    if (response.code !== 20000) {
      message.error(`举报失败：${response.message}`)
      return
    }

    message.success('操作成功，已修改SURL状态，等待引擎调度')
    getUrlList()
  } catch (error) {
    console.error('举报失败', error)
    message.error(`举报失败：${error}`)
  }
}

// 处理收集证据
const handleCollectEvidence = async (ids: number[]) => {
  try {
    const response = (await axios.post('/api/urls/v1/evidence', {
      ids,
    })).data

    if (response.code !== 20000) {
      message.error(`收集证据失败：${response.message}`)
      return
    }

    message.success('操作成功，已修改SURL状态，等待引擎调度')
    getUrlList()
  } catch (error) {
    console.error('收集证据失败', error)
    message.error(`收集证据失败：${error}`)
  }
}

// 处理单个URL的举报
const handleSingleReport = (row: any, option: string) => {
  handleReport([row.id], option)
}

// 处理单个URL的收集证据
const handleSingleCollectEvidence = (row: any) => {
  handleCollectEvidence([row.id])
}

// 处理批量举报
const handleBatchReport = (option: string) => {
  if (checkedRowKeys.value.length === 0) {
    message.warning('请至少选择一个URL')
    return
  }
  handleReport(checkedRowKeys.value as number[], option)
}

// 处理批量收集证据
const handleBatchCollectEvidence = () => {
  if (checkedRowKeys.value.length === 0) {
    message.warning('请至少选择一个URL')
    return
  }
  handleCollectEvidence(checkedRowKeys.value as number[])
}

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

onMounted(() => {
  initPagination()
  getUrlList()
})
</script>

<template>
  <div class="p-4">
    <h1 class="text-2xl mb-4">URL管理</h1>

    <!-- 搜索表单 -->
    <n-card class="mb-4">
      <n-form :model="searchForm" label-placement="left" label-width="auto" require-mark-placement="right-hanging">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="8" label="域名">
            <n-input v-model:value="searchForm.domain" placeholder="请输入域名" @keyup.enter="handleSearch" />
          </n-form-item-gi>
          <n-form-item-gi :span="8" label="SURL">
            <n-input v-model:value="searchForm.surl" placeholder="请输入SURL" @keyup.enter="handleSearch" />
          </n-form-item-gi>
          <n-form-item-gi :span="8" label="是否已通过PC举报">
            <n-select v-model:value="searchForm.is_report_by_one" :options="options" placeholder="请选择" />
          </n-form-item-gi>
          <n-form-item-gi :span="8" label="是否已通过site举报">
            <n-select v-model:value="searchForm.is_report_by_site" :options="options" placeholder="请选择" />
          </n-form-item-gi>
          <n-form-item-gi :span="8" label="是否已通过WAP举报">
            <n-select v-model:value="searchForm.is_report_by_wap" :options="options" placeholder="请选择" />
          </n-form-item-gi>
          <n-form-item-gi :span="8" label="是否已收集证据">
            <n-select v-model:value="searchForm.has_evidence" :options="options" placeholder="请选择" />
          </n-form-item-gi>
        </n-grid>
        <div class="flex justify-end gap-2 mt-4">
          <n-button @click="handleReset">重置</n-button>
          <n-button type="primary" @click="handleSearch">搜索</n-button>
        </div>
      </n-form>
    </n-card>

    <!-- 数据表格 -->
    <n-card>
      <div class="mb-4" v-if="hasSelectedRows">
        <n-space>
          <n-dropdown trigger="click" :options="reportOptions" @select="handleBatchReport">
            <n-button type="primary">批量举报 ({{ checkedRowKeys.length }})</n-button>
          </n-dropdown>
          <n-button type="info" @click="handleBatchCollectEvidence">
            批量收集证据 ({{ checkedRowKeys.length }})
          </n-button>
        </n-space>
      </div>

      <n-data-table :columns="columns" :data="urls" :bordered="false" :row-key="(row: any) => row.id"
        :checked-row-keys="checkedRowKeys" @update:checked-row-keys="checkedRowKeys = $event" />

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

<style scoped></style>
