<template>
  <div class="cash-discount-grant">
    <el-card>
      <template #header>
        <div class="search-section">
        <el-form :model="searchForm" label-width="100px">
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="客户号:">
                <el-input v-model="searchForm.customerId" placeholder="请输入客户号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="立减金类型:">
                <el-select v-model="searchForm.discountType" placeholder="请选择立减金类型" clearable style="width: 100%;">
                  <el-option v-for="item in discountTypeOptions" :key="item" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发放时间:">
                <el-date-picker
                  v-model="searchForm.grantDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%;"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="是否领取:">
                <el-select v-model="searchForm.claimed" placeholder="请选择" clearable style="width: 100%;">
                  <el-option label="是" value="是"></el-option>
                  <el-option label="否" value="否"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否使用:">
                <el-select v-model="searchForm.used" placeholder="请选择" clearable style="width: 100%;">
                  <el-option label="是" value="是"></el-option>
                  <el-option label="否" value="否"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" class="action-col">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
              <el-button type="success" @click="handleExport"><el-icon><Download /></el-icon>导出</el-button>
            </el-col>
          </el-row>
        </el-form>
        </div>
      </template>

      <el-table :data="pagedData" stripe border style="width: 100%;" v-loading="loading">
        <el-table-column prop="grantTime" label="发放时间" width="170"></el-table-column>
        <el-table-column prop="customerId" label="客户号" width="160"></el-table-column>
        <el-table-column prop="discountType" label="立减金类型" width="130"></el-table-column>
        <el-table-column prop="binRestriction" label="是否有bin卡限制" width="140">
          <template #default="scope">
            <el-tag :type="scope.row.binRestriction === '是' ? 'warning' : 'info'" size="small">{{ scope.row.binRestriction }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="grantAmount" label="发放金额" width="110">
          <template #default="scope">
            <span>¥{{ scope.row.grantAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="grantReason" label="发放事由" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column prop="claimed" label="是否领取" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.claimed === '是' ? 'success' : 'danger'" size="small">{{ scope.row.claimed }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="claimTime" label="领取时间" width="160"></el-table-column>
        <el-table-column prop="validPeriod" label="使用有效期" width="220"></el-table-column>
        <el-table-column prop="used" label="是否使用" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.used === '是' ? 'success' : 'danger'" size="small">{{ scope.row.used }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="useTime" label="使用时间" width="160"></el-table-column>
      </el-table>

      <el-pagination
        style="margin-top: 20px; text-align: right;"
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="filteredData.length"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'

const DISCOUNT_TYPES = ['借记卡', '信用卡']
const GRANT_REASONS = ['新开户礼遇', '月度消费达标奖励', '生日专属福利', '双十一营销活动', '服务补偿', '升级Premier礼遇', '推荐好友奖励', '季度活跃奖励']

function pad(n) { return String(n).padStart(2, '0') }

function randomDateTime(baseDate, offsetDays) {
  const d = new Date(baseDate)
  d.setDate(d.getDate() - Math.floor(Math.random() * offsetDays))
  d.setHours(Math.floor(Math.random() * 14 + 8), Math.floor(Math.random() * 60), Math.floor(Math.random() * 60))
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

function generateMockData() {
  const list = []
  const base = new Date(2026, 4, 15)
  const amounts = [10, 20, 30, 50, 88, 100, 128, 200]

  for (let i = 1; i <= 65; i++) {
    const grantTime = randomDateTime(base, 90)
    const grantDate = grantTime.slice(0, 10)
    const validEnd = new Date(grantDate)
    validEnd.setDate(validEnd.getDate() + 30 + Math.floor(Math.random() * 60))
    const validEndStr = `${validEnd.getFullYear()}-${pad(validEnd.getMonth() + 1)}-${pad(validEnd.getDate())}`

    const claimed = Math.random() > 0.25 ? '是' : '否'
    const used = claimed === '是' && Math.random() > 0.35 ? '是' : '否'

    list.push({
      id: i,
      customerId: 'CUST' + String(100000 + Math.floor(Math.random() * 900000)),
      discountType: DISCOUNT_TYPES[Math.floor(Math.random() * DISCOUNT_TYPES.length)],
      binRestriction: Math.random() > 0.5 ? '是' : '否',
      grantTime: grantTime,
      grantDate: grantDate,
      grantAmount: amounts[Math.floor(Math.random() * amounts.length)],
      grantReason: GRANT_REASONS[Math.floor(Math.random() * GRANT_REASONS.length)],
      validPeriod: claimed === '是' ? `${grantDate} 至 ${validEndStr}` : '-',
      claimed: claimed,
      claimTime: claimed === '是' ? randomDateTime(base, 60) : '-',
      used: used,
      useTime: used === '是' ? randomDateTime(base, 30) : '-'
    })
  }
  list.sort((a, b) => b.grantTime.localeCompare(a.grantTime))
  return list
}

export default {
  name: 'CashDiscountGrant',
  data() {
    return {
      searchForm: {
        customerId: '',
        discountType: '',
        grantDateRange: [],
        claimed: '',
        used: ''
      },
      loading: false,
      currentPage: 1,
      pageSize: 10,
      tableData: generateMockData(),
      discountTypeOptions: DISCOUNT_TYPES
    }
  },
  computed: {
    filteredData() {
      let list = this.tableData
      const customerId = this.searchForm.customerId.trim()
      if (customerId) {
        list = list.filter(item => item.customerId.includes(customerId))
      }
      if (this.searchForm.discountType) {
        list = list.filter(item => item.discountType === this.searchForm.discountType)
      }
      if (this.searchForm.grantDateRange && this.searchForm.grantDateRange.length === 2) {
        const [start, end] = this.searchForm.grantDateRange
        list = list.filter(item => item.grantDate >= start && item.grantDate <= end)
      }
      if (this.searchForm.claimed) {
        list = list.filter(item => item.claimed === this.searchForm.claimed)
      }
      if (this.searchForm.used) {
        list = list.filter(item => item.used === this.searchForm.used)
      }
      return list
    },
    pagedData() {
      const start = (this.currentPage - 1) * this.pageSize
      return this.filteredData.slice(start, start + this.pageSize)
    }
  },
  methods: {
    handleSearch() {
      this.currentPage = 1
    },
    handleReset() {
      this.searchForm = {
        customerId: '',
        discountType: '',
        grantDateRange: [],
        claimed: '',
        used: ''
      }
      this.currentPage = 1
    },
    handlePageChange(page) {
      this.currentPage = page
    },
    handleExport() {
      ElMessage.success('导出任务已提交，请稍后在下载中心查看')
    }
  }
}
</script>

<style scoped>
.search-section {
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.action-col {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
