<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 #category="{ record }">
        <a-tag :color="getResourceTypeColor(record.type)">
          {{ getResourceTypeText(record.type) }}
        </a-tag>
      </template>

      <!-- 作者列 -->
      <template #author="{ record }">
        {{ record.resource?.author_name || '-' }}
      </template>

      <!-- 申请时间列 -->
      <template #created_at="{ record }">
        {{ formatTime(record.resource?.created_at) }}
      </template>

      <!-- 描述列 -->
      <template #description="{ record }">
        <a-tooltip :content="record.resource?.description || record.resource?.question || '-'">
          <span class="description-text">
            {{ record.resource?.description || record.resource?.question || '-' }}
          </span>
        </a-tooltip>
      </template>

      <!-- 操作列 -->
      <template #operation="{ record }">
        <a-space>
          <a-button type="text" size="small" @click="handleView(record)">
            查看
          </a-button>
          <a-button type="text" size="small" status="success" @click="handleApprove(record)">
            审核通过
          </a-button>
          <a-button type="text" size="small" status="danger" @click="handleReject(record)">
            拒绝
          </a-button>
        </a-space>
      </template>
    </SearchTable>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:visible="detailVisible"
      title="详情"
      :width="720"
      :footer="false"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="类型">
          <a-tag :color="getResourceTypeColor(currentRecord?.type || '')">
            {{ getResourceTypeText(currentRecord?.type || '') }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="编号">
          {{ getResourceNo(currentRecord) }}
        </a-descriptions-item>
        <a-descriptions-item label="标题" :span="2">
          {{ getResourceTitle(currentRecord) }}
        </a-descriptions-item>
        <a-descriptions-item label="作者">
          {{ currentRecord?.resource?.author_name || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">
          {{ formatTime(currentRecord?.resource?.created_at) }}
        </a-descriptions-item>
        <a-descriptions-item label="分类">
          {{ currentRecord?.resource?.sub_category || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(currentRecord?.resource?.status)">
            {{ getStatusText(currentRecord?.resource?.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="描述" :span="2">
          {{ getResourceDescription(currentRecord) }}
        </a-descriptions-item>
        <a-descriptions-item label="关键词" :span="2">
          {{ currentRecord?.resource?.keywords || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="标签" :span="2">
          <a-space wrap>
            <a-tag v-for="tag in parseTags(currentRecord?.resource?.tags)" :key="tag">
              {{ tag }}
            </a-tag>
          </a-space>
        </a-descriptions-item>
        <a-descriptions-item v-if="currentRecord?.type === 'faq'" label="答案" :span="2">
          <div class="content-preview">{{ getFaqAnswer(currentRecord) }}</div>
        </a-descriptions-item>
        <a-descriptions-item v-if="currentRecord?.type === 'document'" label="内容" :span="2">
          <div class="content-preview">{{ getDocumentContent(currentRecord) }}</div>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>

    <!-- 拒绝原因对话框 -->
    <a-modal
      v-model:visible="rejectVisible"
      title="拒绝原因"
      :ok-loading="rejectLoading"
      @ok="handleConfirmReject"
      @cancel="handleCancelReject"
    >
      <a-form :model="rejectForm" layout="vertical">
        <a-form-item label="拒绝原因" required>
          <a-textarea
            v-model="rejectForm.reason"
            placeholder="请输入拒绝原因"
            :max-length="500"
            :auto-size="{ minRows: 3, maxRows: 6 }"
            show-word-limit
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message, Modal } 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 { ReviewListItem, FetchReviewListParams } from '@/api/kb/review'
import {
  fetchReviewList,
  approveReview,
  rejectReview,
  getResourceTypeText,
  getResourceTypeColor,
  resourceTypeOptions,
} from '@/api/kb/review'

// 表格列配置
const columns = computed((): TableColumnData[] => [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 80,
    align: 'center',
  },
  {
    title: '分类',
    dataIndex: 'category',
    slotName: 'category',
    width: 100,
    align: 'center',
  },
  {
    title: '作者',
    dataIndex: 'author',
    slotName: 'author',
    width: 120,
    align: 'center',
  },
  {
    title: '申请时间',
    dataIndex: 'created_at',
    slotName: 'created_at',
    width: 180,
    align: 'center',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
  },
  {
    title: '描述',
    dataIndex: 'description',
    slotName: 'description',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    slotName: 'operation',
    width: 280,
    align: 'center',
    fixed: 'right',
  },
])

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

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

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

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

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

// 详情弹窗
const detailVisible = ref(false)
const currentRecord = ref<ReviewListItem | null>(null)

// 拒绝对话框
const rejectVisible = ref(false)
const rejectLoading = ref(false)
const recordToReject = ref<ReviewListItem | null>(null)
const rejectForm = reactive({
  reason: '',
})

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

    const res: any = await fetchReviewList(params)

    if (res?.code === 0) {
      tableData.value = res.details?.data || []
      total.value = res.details?.total || 0
    } else {
      Message.error(res?.message || '获取审核列表失败')
    }
  } catch (error) {
    console.error('获取审核列表失败:', error)
    Message.error('获取审核列表失败')
  } finally {
    loading.value = false
  }
}

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

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

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

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

// 获取状态文本
const getStatusText = (status: string | undefined): string => {
  const statusMap: Record<string, string> = {
    draft: '草稿',
    published: '待审核',
    reviewed: '已审核',
    rejected: '已拒绝',
  }
  return statusMap[status || ''] || status || '-'
}

// 获取状态颜色
const getStatusColor = (status: string | undefined): string => {
  const colorMap: Record<string, string> = {
    draft: 'gray',
    published: 'orange',
    reviewed: 'green',
    rejected: 'red',
  }
  return colorMap[status || ''] || 'gray'
}

// 解析标签
const parseTags = (tags: string | null | undefined): string[] => {
  if (!tags) return []
  try {
    return JSON.parse(tags)
  } catch {
    return tags.split(',').filter(Boolean)
  }
}

// 获取资源编号
const getResourceNo = (record: ReviewListItem | null): string => {
  if (!record?.resource) return '-'
  const resource = record.resource as any
  return resource.doc_no || resource.faq_no || '-'
}

// 获取资源标题
const getResourceTitle = (record: ReviewListItem | null): string => {
  if (!record?.resource) return '-'
  const resource = record.resource as any
  return resource.title || resource.question || '-'
}

// 获取资源描述
const getResourceDescription = (record: ReviewListItem | null): string => {
  if (!record?.resource) return '-'
  const resource = record.resource as any
  return resource.description || '-'
}

// 获取FAQ答案
const getFaqAnswer = (record: ReviewListItem | null): string => {
  if (!record?.resource) return '-'
  const resource = record.resource as any
  return resource.answer || '-'
}

// 获取文档内容
const getDocumentContent = (record: ReviewListItem | null): string => {
  if (!record?.resource) return '-'
  const resource = record.resource as any
  return resource.content || '-'
}

// 查看详情
const handleView = (record: ReviewListItem) => {
  currentRecord.value = record
  detailVisible.value = true
}

// 审核通过
const handleApprove = (record: ReviewListItem) => {
  const resourceTitle = getResourceTitle(record)
  const resourceTypeText = getResourceTypeText(record.type)
  
  Modal.confirm({
    title: '确认审核通过',
    content: `确定要通过该${resourceTypeText}的审核吗？\n标题：${resourceTitle}`,
    okText: '确认通过',
    cancelText: '取消',
    onOk: async () => {
      try {
        loading.value = true
        const res: any = await approveReview({
          resource_type: record.type,
          id: record.resource.id,
        })
        if (res?.code === 0) {
          Message.success('审核通过')
          await fetchData()
        } else {
          Message.error(res?.message || '审核失败')
        }
      } catch (error) {
        console.error('审核失败:', error)
        Message.error('审核失败')
      } finally {
        loading.value = false
      }
    },
  })
}

// 拒绝
const handleReject = (record: ReviewListItem) => {
  recordToReject.value = record
  rejectForm.reason = ''
  rejectVisible.value = true
}

// 确认拒绝
const handleConfirmReject = async () => {
  if (!recordToReject.value) return

  if (!rejectForm.reason.trim()) {
    Message.warning('请输入拒绝原因')
    return
  }

  try {
    rejectLoading.value = true
    const res: any = await rejectReview({
      resource_type: recordToReject.value.type,
      id: recordToReject.value.resource.id,
      reason: rejectForm.reason,
    })
    if (res?.code === 0) {
      Message.success('已拒绝')
      rejectVisible.value = false
      recordToReject.value = null
      rejectForm.reason = ''
      await fetchData()
    } else {
      Message.error(res?.message || '拒绝失败')
    }
  } catch (error) {
    console.error('拒绝失败:', error)
    Message.error('拒绝失败')
  } finally {
    rejectLoading.value = false
  }
}

// 取消拒绝
const handleCancelReject = () => {
  rejectVisible.value = false
  recordToReject.value = null
  rejectForm.reason = ''
}

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

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

.description-text {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.content-preview {
  max-height: 200px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>