<template>
  <div class="panel">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="危险操作审批"
      search-button-text="查询"
      reset-button-text="重置"
      :show-download="false"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
      @refresh="fetchList"
    >
      <template #status="{ record }">
        <a-tag :color="statusColor(record.status)">{{ statusLabel(record.status) }}</a-tag>
      </template>
      <template #operations="{ record }">
        <a-space>
          <a-button type="text" size="small" @click="openDetail(record)">详情</a-button>
          <a-button
            v-permission="['*', 'admin', 'system:audit:approve']"
            type="text"
            size="small"
            :disabled="record.status !== 'pending'"
            @click="handleReview(record, 'approve')"
          >
            通过
          </a-button>
          <a-button
            v-permission="['*', 'admin', 'system:audit:approve']"
            type="text"
            status="danger"
            size="small"
            :disabled="record.status !== 'pending'"
            @click="handleReview(record, 'reject')"
          >
            驳回
          </a-button>
        </a-space>
      </template>
    </search-table>

    <a-drawer
      v-model:visible="detailVisible"
      width="720px"
      :title="detailRow ? `审批详情 #${detailRow.id}` : '审批详情'"
      :footer="false"
      unmount-on-close
    >
      <a-descriptions v-if="detailRow" :column="1" bordered>
        <a-descriptions-item label="审批单号">{{ detailRow.request_id || '-' }}</a-descriptions-item>
        <a-descriptions-item label="服务">{{ detailRow.source_service || '-' }}</a-descriptions-item>
        <a-descriptions-item label="动作">{{ detailRow.action || '-' }}</a-descriptions-item>
        <a-descriptions-item label="对象">{{ detailRow.object_type }} / {{ detailRow.object_id }}</a-descriptions-item>
        <a-descriptions-item label="申请人">{{ detailRow.requester_name || detailRow.requester_id || '-' }}</a-descriptions-item>
        <a-descriptions-item label="原因">{{ detailRow.reason || '-' }}</a-descriptions-item>
        <a-descriptions-item label="状态">{{ statusLabel(detailRow.status) }}</a-descriptions-item>
        <a-descriptions-item label="审核人">{{ detailRow.reviewer_name || detailRow.reviewer_id || '-' }}</a-descriptions-item>
        <a-descriptions-item label="审核意见">{{ detailRow.review_comment || '-' }}</a-descriptions-item>
        <a-descriptions-item label="变更前"><pre class="pre-block">{{ detailRow.before_json || '-' }}</pre></a-descriptions-item>
        <a-descriptions-item label="变更后"><pre class="pre-block">{{ detailRow.after_json || '-' }}</pre></a-descriptions-item>
      </a-descriptions>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import { approveDangerousApproval, fetchDangerousApprovals, rejectDangerousApproval, unwrapLogsPayload, type DangerousApproval } from '@/api/ops/logs'
import { useUserStore } from '@/store'

const userStore = useUserStore()
const loading = ref(false)
const tableData = ref<DangerousApproval[]>([])
const detailVisible = ref(false)
const detailRow = ref<DangerousApproval | null>(null)
const formModel = ref({
  source_service: '',
  status: 'pending',
  requester_id: '',
  object_type: '',
})
const pagination = reactive({ current: 1, pageSize: 50, total: 0 })

const formItems = computed<FormItem[]>(() => [
  { field: 'source_service', label: '服务', type: 'input', placeholder: 'alert / dc-control', span: 6 },
  {
    field: 'status',
    label: '状态',
    type: 'select',
    placeholder: '全部',
    span: 6,
    options: [
      { label: '全部', value: '' },
      { label: '待审批', value: 'pending' },
      { label: '已通过', value: 'approved' },
      { label: '已驳回', value: 'rejected' },
    ],
  },
  { field: 'requester_id', label: '申请人ID', type: 'input', placeholder: '输入申请人', span: 6 },
  { field: 'object_type', label: '对象类型', type: 'input', placeholder: '输入对象类型', span: 6 },
])

const columns = computed<TableColumnData[]>(() => [
  { title: 'ID', dataIndex: 'id', width: 80 },
  { title: '申请时间', dataIndex: 'created_at', width: 180, ellipsis: true, tooltip: true },
  { title: '服务', dataIndex: 'source_service', width: 120 },
  { title: '动作', dataIndex: 'action', width: 180, ellipsis: true, tooltip: true },
  { title: '对象类型', dataIndex: 'object_type', width: 150, ellipsis: true, tooltip: true },
  { title: '对象ID', dataIndex: 'object_id', width: 150, ellipsis: true, tooltip: true },
  { title: '申请人', dataIndex: 'requester_name', width: 130, ellipsis: true, tooltip: true },
  { title: '状态', dataIndex: 'status', slotName: 'status', width: 100 },
  { title: '审核人', dataIndex: 'reviewer_name', width: 120, ellipsis: true, tooltip: true },
  { title: '操作', dataIndex: 'operations', slotName: 'operations', width: 190, fixed: 'right' },
])

function statusLabel(status: string) {
  if (status === 'pending') return '待审批'
  if (status === 'approved') return '已通过'
  if (status === 'rejected') return '已驳回'
  return status || '-'
}

function statusColor(status: string) {
  if (status === 'pending') return 'orange'
  if (status === 'approved') return 'green'
  if (status === 'rejected') return 'red'
  return 'gray'
}

function currentReviewer() {
  const info = userStore.userInfo || {}
  return {
    reviewer_id: String(info.user_id || info.id || info.identity || 'current-user'),
    reviewer_name: String(info.name || info.account || ''),
  }
}

function handleFormModelUpdate(v: Record<string, unknown>) {
  formModel.value = v as typeof formModel.value
}

async function fetchList() {
  loading.value = true
  try {
    const res: any = await fetchDangerousApprovals({
      page: pagination.current,
      page_size: pagination.pageSize,
      source_service: formModel.value.source_service || undefined,
      status: formModel.value.status || undefined,
      requester_id: formModel.value.requester_id || undefined,
      object_type: formModel.value.object_type || undefined,
    })
    const payload = unwrapLogsPayload(res) ?? {}
    tableData.value = payload.items ?? []
    pagination.total = payload.total ?? 0
  } catch (e: any) {
    Message.error(e?.message || '审批列表加载失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  pagination.current = 1
  fetchList()
}

function handleReset() {
  formModel.value = { source_service: '', status: 'pending', requester_id: '', object_type: '' }
  pagination.current = 1
  fetchList()
}

function handlePageChange(page: number) {
  pagination.current = page
  fetchList()
}

function handlePageSizeChange(size: number) {
  pagination.pageSize = size
  pagination.current = 1
  fetchList()
}

function openDetail(row: DangerousApproval) {
  detailRow.value = row
  detailVisible.value = true
}

function handleReview(row: DangerousApproval, action: 'approve' | 'reject') {
  const isApprove = action === 'approve'
  Modal.confirm({
    title: isApprove ? '通过审批' : '驳回审批',
    content: `${isApprove ? '通过' : '驳回'}危险操作审批 #${row.id}？`,
    onOk: async () => {
      try {
        const payload = {
          ...currentReviewer(),
          review_comment: isApprove ? 'approved' : 'rejected',
        }
        const res: any = isApprove ? await approveDangerousApproval(row.id, payload) : await rejectDangerousApproval(row.id, payload)
        if (typeof res.code === 'number' && res.code !== 0) {
          Message.error(res.message || res.msg || '审批操作失败')
          return
        }
        Message.success('审批已更新')
        fetchList()
      } catch (e: any) {
        Message.error(e?.message || '审批操作失败')
      }
    },
  })
}

fetchList()
</script>

<style scoped lang="less">
.panel {
  padding: 16px;
}

.pre-block {
  margin: 0;
  max-height: 240px;
  overflow: auto;
  white-space: pre-wrap;
  word-break: break-word;
  font-size: 12px;
  line-height: 1.5;
}
</style>
