<template>
  <div class="community-manage">
    <a-card title="社群申请审核">
      <template #extra>
        <a-radio-group v-model:value="statusFilter" button-style="solid" @change="loadData">
          <a-radio-button value="">全部</a-radio-button>
          <a-radio-button value="pending">待审核</a-radio-button>
          <a-radio-button value="approved">已通过</a-radio-button>
          <a-radio-button value="rejected">已拒绝</a-radio-button>
        </a-radio-group>
      </template>

      <a-table
        :columns="columns"
        :data-source="list"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="statusColor(record.status)">{{ statusLabel(record.status) }}</a-tag>
          </template>
          <template v-if="column.key === 'createdAt'">
            {{ formatTime(record.createdAt) }}
          </template>
          <template v-if="column.key === 'reviewedAt'">
            {{ record.reviewedAt ? formatTime(record.reviewedAt) : '-' }}
          </template>
          <template v-if="column.key === 'action'">
            <template v-if="record.status === 'pending'">
              <a-button type="primary" size="small" @click="showApproveModal(record)">通过并发券</a-button>
              <a-button danger size="small" style="margin-left: 8px" @click="handleReject(record)">拒绝</a-button>
            </template>
            <span v-else>{{ record.adminRemark || '-' }}</span>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:open="approveVisible"
      title="审核通过 - 选择优惠券模板"
      @ok="handleApprove"
      :confirm-loading="approving"
      ok-text="确认发券"
      cancel-text="取消"
    >
      <a-form layout="vertical">
        <a-form-item label="优惠券模板" required>
          <a-select v-model:value="approveForm.templateId" placeholder="请选择要下发的优惠券模板" :loading="templatesLoading">
            <a-select-option v-for="t in templates" :key="t.id" :value="t.id">
              {{ t.name }} ({{ t.type === 'discount' ? t.discountRate + '折' : '满' + t.thresholdAmount + '减' + t.discountAmount }})
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="备注">
          <a-input v-model:value="approveForm.remark" placeholder="可选备注" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { adminApi } from '@/service/apiService'

const loading = ref(false)
const list = ref([])
const statusFilter = ref('pending')
const pagination = reactive({ current: 1, pageSize: 10, total: 0 })

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '用户ID', dataIndex: 'userId', key: 'userId', width: 100 },
  { title: '状态', key: 'status', width: 100 },
  { title: '申请时间', key: 'createdAt', width: 180 },
  { title: '审核时间', key: 'reviewedAt', width: 180 },
  { title: '操作/备注', key: 'action' }
]

const statusColor = (s) => ({ pending: 'orange', approved: 'green', rejected: 'red' }[s] || 'default')
const statusLabel = (s) => ({ pending: '待审核', approved: '已通过', rejected: '已拒绝' }[s] || s)
const formatTime = (t) => t ? new Date(t).toLocaleString('zh-CN') : '-'

const loadData = async () => {
  loading.value = true
  try {
    const res = await adminApi.getCommunityRequests({
      status: statusFilter.value || undefined,
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    })
    const page = res.data
    list.value = page.records || []
    pagination.total = page.total || 0
  } catch (e) {
    message.error('加载失败')
  } finally {
    loading.value = false
  }
}

const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadData()
}

// 优惠券模板
const templates = ref([])
const templatesLoading = ref(false)
const loadTemplates = async () => {
  templatesLoading.value = true
  try {
    const res = await adminApi.getCouponTemplates({ pageNum: 1, pageSize: 100 })
    templates.value = (res.data?.records || []).filter(t => t.status === 'active')
  } catch { /* ignore */ } finally {
    templatesLoading.value = false
  }
}

// 审核通过
const approveVisible = ref(false)
const approving = ref(false)
const currentRecord = ref(null)
const approveForm = reactive({ templateId: null, remark: '' })

const showApproveModal = (record) => {
  currentRecord.value = record
  approveForm.templateId = null
  approveForm.remark = ''
  approveVisible.value = true
  if (templates.value.length === 0) loadTemplates()
}

const handleApprove = async () => {
  if (!approveForm.templateId) {
    message.warning('请选择优惠券模板')
    return
  }
  approving.value = true
  try {
    await adminApi.approveCommunityRequest(currentRecord.value.id, approveForm.templateId, approveForm.remark)
    message.success('审核通过，优惠券已下发')
    approveVisible.value = false
    loadData()
  } catch (e) {
    message.error(e.response?.data?.message || '操作失败')
  } finally {
    approving.value = false
  }
}

// 拒绝
const handleReject = (record) => {
  Modal.confirm({
    title: '确认拒绝',
    content: `确定拒绝用户 ${record.userId} 的社群申请？`,
    okText: '拒绝',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await adminApi.rejectCommunityRequest(record.id, '不符合条件')
        message.success('已拒绝')
        loadData()
      } catch (e) {
        message.error(e.response?.data?.message || '操作失败')
      }
    }
  })
}

onMounted(() => {
  loadData()
  loadTemplates()
})
</script>

<style scoped>
.community-manage {
  max-width: 1200px;
}
</style>
