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

      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="待导入券码列表" name="pending"></el-tab-pane>
        <el-tab-pane label="已导入券码列表" name="imported"></el-tab-pane>
      </el-tabs>

      <!-- 待导入券码列表 -->
      <template v-if="activeTab === 'pending'">
        <div class="search-section">
          <el-form :model="pendingSearch" label-width="80px" inline>
            <el-form-item label="批次ID:">
              <el-input v-model="pendingSearch.batchId" placeholder="精准匹配" style="width: 220px" />
            </el-form-item>
            <div class="button-group" style="margin-left: 20px;">
              <el-button type="primary" @click="loadData">查询</el-button>
              <el-button @click="resetPending">重置</el-button>
            </div>
          </el-form>
        </div>

        <el-table :data="pagedData" stripe style="width: 100%">
          <el-table-column prop="batchId" label="批次ID" width="170"></el-table-column>
          <el-table-column label="权益编号" width="120">
            <template #default="scope">{{ scope.row.productId || '-' }}</template>
          </el-table-column>
          <el-table-column label="权益名称" min-width="160" show-overflow-tooltip>
            <template #default="scope">{{ scope.row.equityName || '-' }}</template>
          </el-table-column>
          <el-table-column prop="importCount" label="导入数量" width="110"></el-table-column>
          <el-table-column prop="creator" label="创建人" width="110"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
          <el-table-column label="审核状态" width="110">
            <template #default="scope">
              <el-tag :type="auditStatusTag(scope.row.auditStatus)" size="small">{{ auditStatusLabel(scope.row.auditStatus) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" fixed="right">
            <template #default="scope">
              <template v-if="scope.row.auditStatus === 'rejected'">
                <el-button type="text" size="small" @click="openEdit(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
              </template>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 已导入券码列表 -->
      <template v-else>
        <div class="search-section">
          <el-form :model="importedSearch" label-width="80px" inline>
            <el-form-item label="权益编号:">
              <el-input v-model="importedSearch.productId" placeholder="精准匹配" style="width: 200px" />
            </el-form-item>
            <el-form-item label="批次ID:">
              <el-input v-model="importedSearch.batchId" placeholder="精准匹配" style="width: 200px" />
            </el-form-item>
            <div class="button-group" style="margin-left: 20px;">
              <el-button type="primary" @click="loadData">查询</el-button>
              <el-button @click="resetImported">重置</el-button>
            </div>
          </el-form>
        </div>

        <el-table :data="pagedData" stripe style="width: 100%">
          <el-table-column prop="batchId" label="批次ID" width="170"></el-table-column>
          <el-table-column prop="productId" label="权益编号" width="120"></el-table-column>
          <el-table-column prop="equityName" label="权益商品名称" min-width="160" show-overflow-tooltip></el-table-column>
          <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 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="280" fixed="right">
            <template #default="scope">
              <el-button
                v-if="Number(scope.row.remainingCount) > 0"
                type="text"
                size="small"
                @click="handleRecycle(scope.row)"
              >回收</el-button>
              <el-button
                type="text"
                size="small"
                @click="openRecycleRecordDialog(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>
      </template>

      <div class="pagination-section">
        <span>Total {{ total }}</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="total"
        />
      </div>
    </el-card>

    <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>
          <span v-if="recycleForm.type === 'expired'">{{ recycleMaxAmount }}</span>
          <template v-else>
            <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>
          </template>
        </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="权益商品">
          <el-select
            v-model="importForm.productId"
            filterable
            clearable
            placeholder="可输入权益名称/编号搜索（非必填）"
            style="width: 100%"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.productId"
              :label="`${item.equityName}（${item.productId}）`"
              :value="item.productId"
            ></el-option>
          </el-select>
        </el-form-item>
        <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">
                <div>*只支持模板格式，请先下载模板再导入</div>
                <div>*不能导入相同的券码</div>
                <div>*最多支持50000条，若超过请分次导入</div>
              </div>
              <el-button type="text" @click="downloadTemplate">
                <el-icon><Download /></el-icon>模板下载
              </el-button>
            </template>
          </el-upload>
        </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>

    <el-dialog title="编辑待导入券码" v-model="editDialogVisible" width="520px" @closed="resetEditForm">
      <el-form :model="editForm" label-width="120px" label-position="left">
        <el-form-item label="批次ID">{{ editForm.batchId }}</el-form-item>
        <el-form-item label="权益商品">
          <el-select
            v-model="editForm.productId"
            filterable
            clearable
            placeholder="可输入权益名称/编号搜索（非必填）"
            style="width: 100%"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.productId"
              :label="`${item.equityName}（${item.productId}）`"
              :value="item.productId"
            ></el-option>
          </el-select>
        </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="recycleRecordDialogVisible" width="900px">
      <el-table :data="recycleRecords" stripe style="width: 100%">
        <el-table-column prop="recycleTime" label="回收时间" width="180"></el-table-column>
        <el-table-column prop="type" label="类型" width="150"></el-table-column>
        <el-table-column prop="operator" label="操作人" width="120"></el-table-column>
        <el-table-column prop="amount" label="回收数量" width="120"></el-table-column>
        <el-table-column label="操作" min-width="140">
          <template #default="scope">
            <el-button type="text" size="small" @click="downloadRecycleCoupons(scope.row)">下载回收券码</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="recycleRecordDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

export default {
  name: 'CouponBatchList',
  data() {
    return {
      activeTab: 'pending',
      pendingSearch: { batchId: '' },
      importedSearch: { productId: '', batchId: '' },
      pendingData: [],
      importedData: [],
      currentPage: 1,
      pageSize: 10,
      importDialogVisible: false,
      editDialogVisible: false,
      recycleDialogVisible: false,
      recycleRecordDialogVisible: false,
      recycleRow: null,
      recordRow: null,
      recycleForm: {
        type: 'unissued',
        amount: undefined
      },
      recycleTypeOptions: [
        { label: '未发放券码回收', value: 'unissued' },
        { label: '已过期券码回收', value: 'expired' }
      ],
      importForm: {
        productId: '',
        files: []
      },
      editForm: {
        batchId: '',
        productId: ''
      },
      productOptions: []
    }
  },
  created() {
    this.loadData()
    this.loadProductOptions()
  },
  activated() {
    this.loadData()
  },
  computed: {
    currentData() {
      return this.activeTab === 'pending' ? this.pendingData : this.importedData
    },
    total() {
      return this.currentData.length
    },
    pagedData() {
      const start = (this.currentPage - 1) * this.pageSize
      return this.currentData.slice(start, start + this.pageSize)
    },
    currentRecycleTypeLabel() {
      const opt = this.recycleTypeOptions.find(o => o.value === this.recycleForm.type)
      if (!opt) return ''
      return opt.label.replace('回收', '')
    },
    recycleRecords() {
      return (this.recordRow && this.recordRow.recycleRecords) || []
    },
    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
        }
        default: return 0
      }
    }
  },
  methods: {
    loadData() {
      this.currentPage = 1
      if (this.activeTab === 'pending') {
        this.loadPending()
      } else {
        this.loadImported()
      }
    },
    loadPending() {
      const params = new URLSearchParams()
      if (this.pendingSearch.batchId) params.append('batchId', this.pendingSearch.batchId)
      request.get('/api/coupon/pending-list?' + params.toString()).then(res => {
        this.pendingData = res.data || []
      }).catch(() => {})
    },
    loadImported() {
      const params = new URLSearchParams()
      if (this.importedSearch.productId) params.append('productId', this.importedSearch.productId)
      if (this.importedSearch.batchId) params.append('batchId', this.importedSearch.batchId)
      request.get('/api/coupon/batch-list?' + params.toString()).then(res => {
        this.importedData = res.data || []
      }).catch(() => {})
    },
    handleTabChange() {
      this.loadData()
    },
    loadProductOptions() {
      request.get('/api/equity/list').then(res => {
        this.productOptions = res.data || []
      }).catch(() => {})
    },
    resetPending() {
      this.pendingSearch = { batchId: '' }
      this.loadData()
    },
    resetImported() {
      this.importedSearch = { productId: '', batchId: '' }
      this.loadData()
    },
    auditStatusLabel(s) {
      return { pending: '待审核', approved: '审核通过', rejected: '审核拒绝' }[s] || s
    },
    auditStatusTag(s) {
      return { pending: 'warning', approved: 'success', rejected: 'danger' }[s] || ''
    },
    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 = { productId: '', files: [] }
    },
    confirmImport() {
      if (!this.importForm.files.length) {
        ElMessage.warning('请选择券码文件')
        return
      }
      request.post('/api/coupon/import', { productId: this.importForm.productId }).then(() => {
        ElMessage.success('已提交，等待券码审核')
        this.importDialogVisible = false
        this.activeTab = 'pending'
        this.loadData()
      }).catch(() => {})
    },
    openEdit(row) {
      this.editForm = { batchId: row.batchId, productId: row.productId || '' }
      this.editDialogVisible = true
    },
    resetEditForm() {
      this.editForm = { batchId: '', productId: '' }
    },
    confirmEdit() {
      request.post('/api/coupon/pending-edit', {
        batchId: this.editForm.batchId,
        productId: this.editForm.productId
      }).then(() => {
        ElMessage.success('已重新提交审核')
        this.editDialogVisible = false
        this.loadData()
      }).catch(() => {})
    },
    handleDelete(row) {
      ElMessageBox.confirm(`确定删除批次 ${row.batchId} 吗？`, '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.post('/api/coupon/pending-delete', { batchId: row.batchId }).then(() => {
          ElMessage.success('已删除')
          this.loadData()
        }).catch(() => {})
      }).catch(() => {})
    },
    handleRecycle(row) {
      this.recycleRow = row
      this.recycleForm = { type: 'unissued', amount: undefined }
      this.recycleDialogVisible = true
    },
    handleExportFail(row) {
      ElMessage.success(`已开始导出失败券码（${row.failCount} 条）`)
    },
    openRecycleRecordDialog(row) {
      this.recordRow = row
      this.recycleRecordDialogVisible = true
    },
    downloadRecycleCoupons() {
      ElMessage.success('已开始下载回收券码')
    },
    resetRecycleForm() {
      this.recycleRow = null
      this.recycleForm = { type: 'unissued', amount: undefined }
    },
    confirmRecycle() {
      const max = this.recycleMaxAmount
      // 已过期券码回收：数量为文本展示，直接按可回收数量全部回收
      const amount = this.recycleForm.type === 'expired' ? max : Number(this.recycleForm.amount)
      if (!amount || amount < 1) {
        ElMessage.warning(this.recycleForm.type === 'expired' ? '当前批次没有可回收的已过期券码' : '请输入回收数量')
        return
      }
      if (amount > max) {
        ElMessage.error(`回收数量不能超过 ${max}`)
        return
      }
      request.post('/api/coupon/recycle', {
        batchId: this.recycleRow.batchId,
        type: this.recycleForm.type,
        amount
      }).then(() => {
        ElMessage.success('回收成功')
        this.recycleDialogVisible = false
        this.loadData()
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.coupon-batch-list {
  padding: 0;
}

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

.search-section {
  margin-bottom: 8px;
}

.button-group {
  display: flex;
  gap: 5px;
}

.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;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
}
</style>
