<template>
  <div class="equity-grant-campaign">
    <el-card>
      <template #header>
        <div class="search-section">
        <div class="search-row">
          <el-form :model="searchForm" label-width="100px" inline>
            <el-form-item label="发放计划名称:">
              <el-input v-model="searchForm.name" placeholder="关键字" clearable style="width:220px" />
            </el-form-item>
            <el-form-item label="发放计划时间:">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width:360px"
              />
            </el-form-item>
            <el-form-item label="状态:">
              <el-select v-model="searchForm.status" placeholder="全部" clearable style="width:140px">
                <el-option label="未开始" value="未开始" />
                <el-option label="进行中" value="进行中" />
                <el-option label="已结束" value="已结束" />
              </el-select>
            </el-form-item>
            <div class="button-group">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </el-form>
        </div>
        <div class="action-row">
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>新建发放计划
          </el-button>
        </div>
        </div>
      </template>

      <el-table :data="filteredData" stripe border style="width:100%">
        <el-table-column label="操作" width="280" fixed="left">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button
              v-if="statusLabel(scope.row) !== '进行中'"
              type="text"
              size="small"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              size="small"
              @click="handleCopy(scope.row)"
            >复制</el-button>
            <el-button
              v-if="statusLabel(scope.row) === '进行中'"
              type="text"
              size="small"
              style="color:#E6A23C"
              @click="handleEnd(scope.row)"
            >结束</el-button>
            <el-button
              v-if="statusLabel(scope.row) !== '进行中'"
              type="text"
              size="small"
              style="color:#F56C6C"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="发放计划 ID" width="160" align="center" />
        <el-table-column prop="name" label="发放计划名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="startTime" label="开始时间" width="170" align="center" />
        <el-table-column prop="endTime" label="结束时间" width="170" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="statusTag(scope.row)" size="small">{{ statusLabel(scope.row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="获取方式" width="110" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.grantMode === 'direct' ? 'warning' : 'success'" size="small">
              {{ scope.row.grantMode === 'direct' ? '直接发放' : '用户领取' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="权益数量" width="150" align="center">
          <template #default="scope">
            {{ grantSummary(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="权益有效期" min-width="200" align="center">
          <template #default="scope">
            {{ validitySummary(scope.row.validity) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170" align="center" />
      </el-table>
    </el-card>
  </div>
</template>

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

const grantCycleLabelMap = { total: '整个周期', monthly: '每月', quarterly: '每季度', yearly: '每年' }

export default {
  name: 'EquityGrantCampaign',
  data() {
    return {
      searchForm: { name: '', dateRange: [], status: '' },
      tableData: []
    }
  },
  computed: {
    filteredData() {
      if (!this.searchForm.status) return this.tableData
      return this.tableData.filter(r => this.statusLabel(r) === this.searchForm.status)
    }
  },
  created() {
    this.fetchList()
  },
  activated() {
    this.fetchList()
  },
  watch: {
    $route(to) {
      if (to.path === '/customization/hsbc/equity-grant-campaign') {
        this.fetchList()
      }
    }
  },
  methods: {
    async fetchList() {
      const params = { name: this.searchForm.name }
      if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
        params.startDate = this.searchForm.dateRange[0]
        params.endDate = this.searchForm.dateRange[1]
      }
      const res = await request.get('/api/equity-grant-campaign/list', { params })
      this.tableData = res.data || []
    },
    handleSearch() { this.fetchList() },
    handleReset() {
      this.searchForm = { name: '', dateRange: [], status: '' }
      this.fetchList()
    },
    handleCreate() {
      this.$router.push('/customization/hsbc/equity-grant-campaign/add')
    },
    handleEdit(row) {
      this.$router.push(`/customization/hsbc/equity-grant-campaign/edit/${row.id}`)
    },
    handleCopy(row) {
      this.$router.push(`/customization/hsbc/equity-grant-campaign/copy/${row.id}`)
    },
    handleView(row) {
      this.$router.push(`/customization/hsbc/equity-grant-campaign/view/${row.id}`)
    },
    async handleEnd(row) {
      await ElMessageBox.confirm(
        `确定结束发放计划「${row.name}」吗？结束后将立即生效，且不再继续发放权益。`,
        '结束发放计划',
        { type: 'warning', confirmButtonText: '确认结束', cancelButtonText: '取消' }
      )
      await request.post('/api/equity-grant-campaign/end', { id: row.id })
      ElMessage.success('已结束')
      this.fetchList()
    },
    async handleDelete(row) {
      await ElMessageBox.confirm('您确定要删除此条发放计划吗？删除后将无法恢复。', '确认删除', {
        type: 'warning',
        confirmButtonText: '确认删除',
        cancelButtonText: '取消'
      })
      await request.post('/api/equity-grant-campaign/delete', { id: row.id })
      ElMessage.success('删除成功')
      this.fetchList()
    },
    validitySummary(v) {
      if (!v) return '-'
      if (v.type === 'fixed') {
        if (!v.fixedRange || v.fixedRange.length !== 2) return '固定日期'
        return `${v.fixedRange[0]} 至 ${v.fixedRange[1]}`
      }
      if (v.type === 'relative') {
        return `自发放起 ${v.relativeDays || 0} 天内有效`
      }
      return '-'
    },
    grantSummary(row) {
      if (!row) return '-'
      const cycle = grantCycleLabelMap[row.grantCycle] || '整个周期'
      return `${cycle} ${row.grantQuantity || 0} 个`
    },
    statusLabel(row) {
      const now = Date.now()
      const s = new Date(row.startTime).getTime()
      const e = new Date(row.endTime).getTime()
      if (now < s) return '未开始'
      if (now > e) return '已结束'
      return '进行中'
    },
    statusTag(row) {
      const l = this.statusLabel(row)
      return { 未开始: 'info', 进行中: 'success', 已结束: '' }[l] || ''
    }
  }
}
</script>

<style scoped>
.search-section .search-row { margin-bottom: 0; }
.search-section .action-row { margin-top: 15px; }
.button-group { display: inline-block; margin-left: 20px; }
</style>
