<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="兑换码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入兑换码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="未使用" :value="0" />
          <el-option label="已使用" :value="1" />
          <el-option label="已过期" :value="2" />
          <el-option label="已禁用" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openGenerateForm"
          v-hasPermi="['muye:redeem-code:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 批量生成
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['muye:redeem-code:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="checkedIds.length === 0"
          @click="handleDeleteBatch"
          v-hasPermi="['muye:redeem-code:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column label="兑换码" align="center" prop="code" width="180" />
      <el-table-column label="积分面额" align="center" prop="points" width="100">
        <template #default="scope">
          <el-tag type="warning">{{ scope.row.points }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="码类型" align="center" prop="codeType" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.REDEEM_CODE_TYPE" :value="scope.row.codeType" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="success">未使用</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="info">已使用</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="danger">已过期</el-tag>
          <el-tag v-else type="warning">已禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="批次号" align="center" prop="batchNo" width="160" />
      <el-table-column label="使用者ID" align="center" prop="userId" width="100" />
      <el-table-column label="使用次数" align="center" width="100">
        <template #default="scope">
          {{ scope.row.usedCount }} / {{ scope.row.maxUseCount }}
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" prop="expireTime" width="180" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="操作" align="center" fixed="right" width="120">
        <template #default="scope">
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['muye:redeem-code:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 批量生成表单 -->
  <RedeemCodeGenerateForm ref="generateFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as RedeemCodeApi from '@/api/muye/redeemcode'
import RedeemCodeGenerateForm from './RedeemCodeGenerateForm.vue'

defineOptions({ name: 'RedeemCode' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const list = ref([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  status: undefined,
  batchNo: undefined,
  createTime: []
})
const queryFormRef = ref()
const exportLoading = ref(false)
const checkedIds = ref<number[]>([])

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await RedeemCodeApi.getRedeemCodePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 选择改变 */
const handleSelectionChange = (selection: any[]) => {
  checkedIds.value = selection.map((item) => item.id)
}

/** 打开批量生成表单 */
const generateFormRef = ref()
const openGenerateForm = () => {
  generateFormRef.value.open()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await RedeemCodeApi.deleteRedeemCode(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 批量删除按钮操作 */
const handleDeleteBatch = async () => {
  try {
    await message.delConfirm()
    await RedeemCodeApi.deleteRedeemCodeList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await RedeemCodeApi.exportRedeemCode(queryParams)
    download.excel(data, '兑换码列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
