<template>
  <div class="equity-product-coupons">
    <el-card>
      <template #header>
        <div class="header-title">
          <span>券码管理</span>
          <span class="product-id">权益名称：{{ equityName }}</span>
        </div>
      </template>

      <div class="toolbar">
        <el-button type="primary" @click="openImportDialog">
          <el-icon><Upload /></el-icon>导入券码
        </el-button>
      </div>

      <el-table :data="batchList" stripe style="width: 100%">
        <el-table-column prop="importCount" label="导入数量" width="100"></el-table-column>
        <el-table-column prop="actualImportCount" label="实际导入数量" width="120"></el-table-column>
        <el-table-column prop="failCount" label="导入失败数量" width="120"></el-table-column>
        <el-table-column prop="remainingCount" label="券码剩余数量" width="120"></el-table-column>
        <el-table-column prop="effectiveTime" label="生效时间" width="180"></el-table-column>
        <el-table-column prop="expireTime" label="过期时间" width="180"></el-table-column>
        <el-table-column prop="stopIssueTime" label="停止发放时间" width="180"></el-table-column>
        <el-table-column label="文件处理状态" width="120">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row.fileStatus)" size="small">{{ scope.row.fileStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="importTime" label="导入时间" width="180"></el-table-column>
        <el-table-column prop="creator" label="创建人" width="100"></el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              v-if="Number(scope.row.remainingCount) > 0"
              type="text"
              size="small"
              @click="handleRecycle(scope.row)"
            >回收</el-button>
            <el-button
              v-if="Number(scope.row.failCount) > 0"
              type="text"
              size="small"
              @click="handleExportFail(scope.row)"
            >导出失败券码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      title="编辑券码批次"
      v-model="editDialogVisible"
      width="520px"
      @closed="resetEditForm"
    >
      <el-form :model="editForm" label-width="120px" label-position="left">
        <el-form-item label="生效时间" required>
          <el-date-picker
            v-model="editForm.effectiveTime"
            type="datetime"
            placeholder="请选择生效时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="过期时间" required>
          <el-date-picker
            v-model="editForm.expireTime"
            type="datetime"
            placeholder="请选择过期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="停止发放时间" required>
          <el-date-picker
            v-model="editForm.stopIssueTime"
            type="datetime"
            placeholder="请选择停止发放时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      title="券码批次回收"
      v-model="recycleDialogVisible"
      width="640px"
      @closed="resetRecycleForm"
    >
      <div class="recycle-types">
        <div
          v-for="opt in recycleTypeOptions"
          :key="opt.value"
          :class="['recycle-type-item', { active: recycleForm.type === opt.value }]"
          @click="recycleForm.type = opt.value"
        >
          <el-radio v-model="recycleForm.type" :label="opt.value">{{ opt.label }}</el-radio>
        </div>
      </div>

      <el-form label-width="100px" label-position="left" style="margin-top: 24px;">
        <el-form-item label="回收数量" required>
          <el-input-number
            v-model="recycleForm.amount"
            :min="1"
            :max="recycleMaxAmount"
            :placeholder="`输入范围1-${recycleMaxAmount}`"
            :controls-position="''"
            style="width: 100%"
          ></el-input-number>
          <div class="recycle-tip">本批次{{ currentRecycleTypeLabel }}最多可回收数量：{{ recycleMaxAmount }}</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer-center">
          <el-button @click="recycleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRecycle">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="导入券码" v-model="importDialogVisible" width="520px" @closed="resetImportForm">
      <el-form :model="importForm" label-width="120px" label-position="left">
        <el-form-item label="券码文件" required>
          <el-upload
            action=""
            :auto-upload="false"
            :file-list="importForm.files"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :limit="1"
          >
            <el-button>
              <el-icon><Upload /></el-icon>选择文件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">支持 .xlsx / .csv，仅可上传一个文件</div>
            </template>
          </el-upload>
          <el-button type="text" @click="downloadTemplate">
            <el-icon><Download /></el-icon>模板下载
          </el-button>
        </el-form-item>
        <el-form-item label="生效时间" required>
          <el-date-picker
            v-model="importForm.effectiveTime"
            type="datetime"
            placeholder="请选择生效时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="过期时间" required>
          <el-date-picker
            v-model="importForm.expireTime"
            type="datetime"
            placeholder="请选择过期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="停止发放时间" required>
          <el-date-picker
            v-model="importForm.stopIssueTime"
            type="datetime"
            placeholder="请选择停止发放时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmImport">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

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

export default {
  name: 'EquityProductCoupons',
  data() {
    return {
      importDialogVisible: false,
      editDialogVisible: false,
      editingRow: null,
      editForm: {
        effectiveTime: '',
        expireTime: '',
        stopIssueTime: ''
      },
      recycleDialogVisible: false,
      recycleRow: null,
      recycleForm: {
        type: 'unissued',
        amount: undefined
      },
      recycleTypeOptions: [
        { label: '未发放券码回收', value: 'unissued' },
        { label: '已过期券码回收', value: 'expired' },
        { label: '导错码券码回收', value: 'wrong' }
      ],
      importForm: {
        files: [],
        effectiveTime: '',
        expireTime: '',
        stopIssueTime: ''
      },
      batchList: [
        {
          importCount: 1000,
          actualImportCount: 998,
          failCount: 2,
          remainingCount: 720,
          effectiveTime: '2026-04-16 00:00:00',
          expireTime: '2026-12-31 23:59:59',
          stopIssueTime: '2026-11-30 23:59:59',
          fileStatus: '处理成功',
          importTime: '2026-04-15 10:32:18',
          creator: '张三'
        },
        {
          importCount: 500,
          actualImportCount: 500,
          failCount: 0,
          remainingCount: 320,
          effectiveTime: '2026-04-21 00:00:00',
          expireTime: '2026-09-30 23:59:59',
          stopIssueTime: '2026-08-31 23:59:59',
          fileStatus: '处理成功',
          importTime: '2026-04-20 14:15:42',
          creator: '李四'
        },
        {
          importCount: 800,
          actualImportCount: 0,
          failCount: 0,
          remainingCount: 0,
          effectiveTime: '2026-05-08 00:00:00',
          expireTime: '2026-12-31 23:59:59',
          stopIssueTime: '2026-11-30 23:59:59',
          fileStatus: '处理中',
          importTime: '2026-05-07 09:08:11',
          creator: '王五'
        },
        {
          importCount: 200,
          actualImportCount: 0,
          failCount: 200,
          remainingCount: 0,
          effectiveTime: '2026-05-02 00:00:00',
          expireTime: '2026-10-31 23:59:59',
          stopIssueTime: '2026-09-30 23:59:59',
          fileStatus: '处理失败',
          importTime: '2026-05-01 16:45:30',
          creator: '赵六'
        }
      ]
    }
  },
  computed: {
    productId() {
      return this.$route.params.id || ''
    },
    equityName() {
      const map = {
        'Q100001': '权益A',
        'Q100002': '权益B',
        'Q100003': '权益C',
        'Q100004': '权益D',
        'Q100005': '权益E'
      }
      return map[this.productId] || this.productId
    },
    currentRecycleTypeLabel() {
      const opt = this.recycleTypeOptions.find(o => o.value === this.recycleForm.type)
      if (!opt) return ''
      return opt.label.replace('回收', '')
    },
    recycleMaxAmount() {
      const row = this.recycleRow
      if (!row) return 0
      switch (this.recycleForm.type) {
        case 'unissued': return Number(row.remainingCount) || 0
        case 'expired': {
          const ts = row.expireTime ? new Date(row.expireTime).getTime() : 0
          return ts && ts < Date.now() ? Number(row.remainingCount) || 0 : 0
        }
        case 'wrong': return Number(row.failCount) || 0
        default: return 0
      }
    }
  },
  methods: {
    statusTagType(status) {
      switch (status) {
        case '处理成功': return 'success'
        case '处理中': return 'warning'
        case '处理失败': return 'danger'
        default: return 'info'
      }
    },
    openImportDialog() {
      this.importDialogVisible = true
    },
    downloadTemplate() {
      ElMessage.success('模板已开始下载')
    },
    handleFileChange(file) {
      this.importForm.files = [file]
    },
    handleFileRemove() {
      this.importForm.files = []
    },
    resetImportForm() {
      this.importForm = {
        files: [],
        effectiveTime: '',
        expireTime: '',
        stopIssueTime: ''
      }
    },
    confirmImport() {
      if (!this.importForm.files.length) {
        ElMessage.warning('请选择券码文件')
        return
      }
      if (!this.importForm.effectiveTime) {
        ElMessage.warning('请选择生效时间')
        return
      }
      if (!this.importForm.expireTime) {
        ElMessage.warning('请选择过期时间')
        return
      }
      if (!this.importForm.stopIssueTime) {
        ElMessage.warning('请选择停止发放时间')
        return
      }
      this.batchList.unshift({
        importCount: 0,
        actualImportCount: 0,
        failCount: 0,
        remainingCount: 0,
        effectiveTime: this.importForm.effectiveTime,
        expireTime: this.importForm.expireTime,
        stopIssueTime: this.importForm.stopIssueTime,
        fileStatus: '处理中',
        importTime: this.formatNow(),
        creator: '当前用户'
      })
      ElMessage.success('券码已提交，正在处理中')
      this.importDialogVisible = false
    },
    formatNow() {
      const d = new Date()
      const pad = n => String(n).padStart(2, '0')
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
    },
    handleEdit(row) {
      this.editingRow = row
      this.editForm = {
        effectiveTime: row.effectiveTime || '',
        expireTime: row.expireTime || '',
        stopIssueTime: row.stopIssueTime || ''
      }
      this.editDialogVisible = true
    },
    resetEditForm() {
      this.editingRow = null
      this.editForm = { effectiveTime: '', expireTime: '', stopIssueTime: '' }
    },
    confirmEdit() {
      if (!this.editForm.effectiveTime) {
        ElMessage.warning('请选择生效时间')
        return
      }
      if (!this.editForm.expireTime) {
        ElMessage.warning('请选择过期时间')
        return
      }
      if (!this.editForm.stopIssueTime) {
        ElMessage.warning('请选择停止发放时间')
        return
      }
      if (this.editingRow) {
        this.editingRow.effectiveTime = this.editForm.effectiveTime
        this.editingRow.expireTime = this.editForm.expireTime
        this.editingRow.stopIssueTime = this.editForm.stopIssueTime
        ElMessage.success('保存成功')
      }
      this.editDialogVisible = false
    },
    handleRecycle(row) {
      this.recycleRow = row
      this.recycleForm = { type: 'unissued', amount: undefined }
      this.recycleDialogVisible = true
    },
    handleExportFail(row) {
      ElMessage.success(`已开始导出失败券码（${row.failCount} 条）`)
    },
    resetRecycleForm() {
      this.recycleRow = null
      this.recycleForm = { type: 'unissued', amount: undefined }
    },
    confirmRecycle() {
      const max = this.recycleMaxAmount
      const amount = Number(this.recycleForm.amount)
      if (!amount || amount < 1) {
        ElMessage.warning('请输入回收数量')
        return
      }
      if (amount > max) {
        ElMessage.error(`回收数量不能超过 ${max}`)
        return
      }
      if (this.recycleRow && this.recycleForm.type === 'unissued') {
        this.recycleRow.remainingCount = Math.max(0, Number(this.recycleRow.remainingCount) - amount)
      }
      ElMessage.success('回收成功')
      this.recycleDialogVisible = false
    }
  }
}
</script>

<style scoped>
.equity-product-coupons {
  padding: 20px;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 16px;
}

.product-id {
  font-size: 14px;
  font-weight: normal;
  color: #909399;
  margin-left: 16px;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
}

.toolbar-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-left: auto;
}

.recycle-types {
  display: flex;
  gap: 16px;
  justify-content: space-between;
}

.recycle-type-item {
  flex: 1;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.recycle-type-item.active {
  border-color: #409eff;
  background: #ecf5ff;
}

.recycle-type-item >>> .el-radio__label {
  font-size: 14px;
  color: #303133;
}

.recycle-tip {
  margin-top: 8px;
  font-size: 13px;
  color: #909399;
}

.dialog-footer-center {
  display: flex;
  justify-content: center;
  gap: 24px;
}
</style>
