<template>
  <div class="activity-management">
    <el-card class="activity-list-card">
      <template #header>
        <div class="search-section">
          <el-form :model="searchForm" class="search-grid" label-width="86px">
            <el-form-item label="活动 ID" class="search-cell">
              <el-input v-model="searchForm.id" clearable placeholder="精确查询活动编号" />
            </el-form-item>
            <el-form-item label="活动名称" class="search-cell">
              <el-input v-model="searchForm.name" clearable placeholder="对内标题/对客名称" />
            </el-form-item>
            <el-form-item label="活动类型" class="search-cell">
              <el-select v-model="searchForm.category" clearable placeholder="全部">
                <el-option label="普通活动" value="普通活动" />
                <el-option label="卓越迎新礼" value="卓越迎新礼" />
                <el-option label="层层礼" value="层层礼" />
                <el-option label="MGM" value="MGM" />
                <el-option label="信用卡活动" value="信用卡活动" />
              </el-select>
            </el-form-item>
            <el-form-item label="发布状态" class="search-cell">
              <el-select v-model="searchForm.status" clearable placeholder="全部">
                <el-option label="草稿" value="draft" />
                <el-option label="待审核" value="pending" />
                <el-option label="审核通过" value="approved" />
                <el-option label="已发布" value="published" />
                <el-option label="已下线" value="offline" />
                <el-option label="已结束" value="ended" />
              </el-select>
            </el-form-item>
            <el-form-item label="活动状态" class="search-cell">
              <el-select v-model="searchForm.activityStatus" clearable placeholder="全部">
                <el-option label="未开始" value="未开始" />
                <el-option label="进行中" value="进行中" />
                <el-option label="已结束" value="已结束" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建人" class="search-cell">
              <el-input v-model="searchForm.creator" clearable placeholder="创建人" />
            </el-form-item>
          </el-form>
          <div class="action-row">
            <el-button type="primary" @click="handleCreate"><el-icon><Plus /></el-icon>新建活动</el-button>
            <div class="search-actions">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </div>
        </div>
      </template>

      <el-table :data="pagedTableData" stripe border style="width: 100%">
        <el-table-column label="操作" width="400" fixed="left" align="left">
          <template #default="{ row }">
            <div class="list-actions">
              <el-button v-if="['draft', 'rejected', 'approved'].includes(row.status)" type="text" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="text" size="small" @click="handleView(row)">查看</el-button>
              <el-button type="text" size="small" @click="preview(row)">预览</el-button>
              <el-button v-if="row.status === 'draft'" type="text" size="small" @click="submitAudit(row)">提交审核</el-button>
              <el-button v-if="row.status === 'pending'" type="text" size="small" @click="handleAudit(row)">{{ row.auditAction === 'offline' ? '审核下线' : '审核' }}</el-button>
              <el-button v-if="row.status === 'approved'" type="text" size="small" @click="publish(row)">发布</el-button>
              <el-button v-if="row.status === 'published'" type="text" size="small" class="offline-button" @click="requestOffline(row)">申请下线</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="活动 ID" width="130" align="center" />
        <el-table-column prop="internalTitle" label="活动标题（对内）" min-width="170" show-overflow-tooltip />
        <el-table-column prop="name" label="活动名称（对客）" min-width="170" show-overflow-tooltip />
        <el-table-column prop="category" label="活动类型" width="120" align="center" />
        <el-table-column label="活动时间" width="210" align="center"><template #default="{ row }">{{ rangeText(row.activityTime) }}</template></el-table-column>
        <el-table-column label="报名时间" width="210" align="center"><template #default="{ row }">{{ rangeText(row.signupTime) }}</template></el-table-column>
        <el-table-column label="展示状态" width="110" align="center">
          <template #default="{ row }">
            <el-tag :type="row.showOnHome || row.showOnAll ? 'success' : 'info'">{{ row.showOnHome || row.showOnAll ? '对客展示' : '不展示' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发布状态" width="110" align="center"><template #default="{ row }"><el-tag :type="statusType(row.status)">{{ statusText(row.status) }}</el-tag></template></el-table-column>
        <el-table-column label="活动状态" width="100" align="center"><template #default="{ row }"><el-tag :type="activityStatusType(row)">{{ activityStatusText(row) }}</el-tag></template></el-table-column>
        <el-table-column prop="auditStatus" label="审核状态" width="110" align="center" />
        <el-table-column prop="creator" label="创建人" width="110" align="center" />
        <el-table-column prop="auditor" label="审核人" width="110" align="center" />
        <el-table-column prop="createdAt" label="创建时间" width="170" align="center" />
        <el-table-column prop="updatedAt" label="更新时间" width="170" align="center" />
      </el-table>
      <div class="pagination-section">
        <span class="total">Total {{ tableData.length }}</span>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          layout="prev, pager, next, sizes, jumper"
          :page-sizes="[10, 20, 50]"
          :total="tableData.length"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import activityStore from '@/store/activityStore'

export default {
  name: 'ActivityManagement',
  data() {
    return {
      searchForm: { id: '', name: '', category: '', status: '', activityStatus: '', creator: '' },
      tableData: [],
      currentPage: 1,
      pageSize: 10
    }
  },
  computed: {
    pagedTableData() {
      const start = (this.currentPage - 1) * this.pageSize
      return this.tableData.slice(start, start + this.pageSize)
    }
  },
  created() { this.handleSearch() },
  activated() { this.handleSearch() },
  methods: {
    handleSearch() {
      this.tableData = activityStore.queryActivities(this.searchForm).filter((item) => {
        if (this.searchForm.creator && !String(item.creator || '').includes(this.searchForm.creator)) return false
        if (this.searchForm.activityStatus && this.activityStatusText(item) !== this.searchForm.activityStatus) return false
        return true
      })
      this.currentPage = 1
    },
    handleReset() {
      this.searchForm = { id: '', name: '', category: '', status: '', activityStatus: '', creator: '' }
      this.handleSearch()
    },
    handleCreate() { this.$router.push('/customization/hsbc/activities/add') },
    handleEdit(row) { this.$router.push(`/customization/hsbc/activities/edit/${row.id}`) },
    handleView(row) { this.$router.push(`/customization/hsbc/activities/view/${row.id}`) },
    handleAudit(row) { this.$router.push(`/customization/hsbc/activities/audit/${row.id}`) },
    preview(row) { ElMessage.success(`已生成移动端预览：${row.name}`) },
    submitAudit(row) {
      const error = this.validateRequired(row)
      if (error) return ElMessage.warning(error)
      row.status = 'pending'
      row.auditStatus = '待审核'
      row.auditAction = ''
      ElMessage.success('已提交审核')
      this.handleSearch()
    },
    async publish(row) {
      await ElMessageBox.confirm(`确定发布活动「${row.name}」吗？`, '发布活动', { type: 'warning' })
      activityStore.publishActivity(row.id)
      this.handleSearch()
    },
    async requestOffline(row) {
      await ElMessageBox.confirm(`提交后将进入下线审核流程，审核通过后活动才会下线。确定申请下线「${row.name}」吗？`, '申请下线', { type: 'warning' })
      row.status = 'pending'
      row.auditStatus = '下线待审核'
      row.auditAction = 'offline'
      this.handleSearch()
    },
    validateRequired(row) {
      if (!row.name) return '活动名称（对客）必填'
      if (!row.internalTitle) return '活动标题（对内）必填'
      if (!row.activityTime || row.activityTime.length !== 2) return '活动时间必填'
      if (row.needSignup && (!row.signupTime || row.signupTime.length !== 2)) return '报名时间必填'
      if (row.rewardEnabled && !row.grantPlanId) return '需要权益发放时必须选择发放计划'
      if (row.mutexEnabled && !row.mutexGroup) return '参与互斥时必须选择互斥组'
      return ''
    },
    rangeText(range) { return range && range.length === 2 ? `${range[0]} 至 ${range[1]}` : '-' },
    activityStatusText(row) {
      const range = row.activityTime
      if (!Array.isArray(range) || range.length !== 2 || !range[0] || !range[1]) return '-'
      const today = new Date().toISOString().slice(0, 10)
      if (today < range[0]) return '未开始'
      if (today > range[1]) return '已结束'
      return '进行中'
    },
    activityStatusType(row) {
      return { '未开始': 'info', '进行中': 'success', '已结束': 'warning' }[this.activityStatusText(row)] || 'info'
    },
    statusText(status) {
      return { draft: '草稿', pending: '待审核', approved: '审核通过', published: '已发布', offline: '已下线', ended: '已结束', rejected: '已驳回' }[status] || status
    },
    statusType(status) {
      return { draft: 'info', pending: 'warning', approved: 'success', published: 'success', offline: 'danger', ended: 'info', rejected: 'danger' }[status] || ''
    }
  }
}
</script>

<style scoped>
.activity-management { padding:0; }
.activity-list-card { border-radius:4px; }
.search-section { display:flex; flex-direction:column; }
.search-grid {
  display:grid;
  grid-template-columns:repeat(4, minmax(0, 1fr));
  column-gap:24px;
  row-gap:20px;
  margin-bottom:4px;
}
.search-grid .search-cell { margin:0; }
.search-grid .search-cell :deep(.el-form-item__content) { width:100%; }
.search-grid .search-cell :deep(.el-input),
.search-grid .search-cell :deep(.el-select) { width:100%; }
.action-row { display:flex; align-items:center; justify-content:space-between; margin-top:20px; }
.search-actions { display:flex; align-items:center; gap:12px; }
.activity-management :deep(.el-input:not(.el-textarea)) { --el-input-height:32px; }
.activity-management :deep(.el-input:not(.el-textarea) .el-input__wrapper),
.activity-management :deep(.el-select__wrapper) { min-height:32px; height:32px; }
.activity-management :deep(.el-input:not(.el-textarea) .el-input__inner) { height:30px; line-height:30px; }
.activity-management :deep(.el-table th.el-table__cell) { background:#fafafa; }
.activity-management :deep(.el-table .el-table__cell) { padding:10px 0; }
.pagination-section { display:flex; justify-content:flex-end; align-items:center; gap:20px; margin-top:20px; }
.pagination-section .total { color:#606266; font-size:13px; }
.list-actions { display:inline-flex; align-items:center; justify-content:flex-start; gap:10px; width:100%; white-space:nowrap; }
.list-actions :deep(.el-button) { margin-left:0; padding:0; }
.offline-button { color:#f56c6c; }
@media (max-width: 1100px) {
  .search-grid { grid-template-columns:repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 600px) {
  .search-grid { grid-template-columns:1fr; }
}
</style>
