<style scoped lang="scss">
.qr-image {
  max-width: 280px;
  max-height: 280px;
  display: block;
  margin: 0 auto;
}
</style>
<template>
  <div class="system-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="page-search mb10" style="display: flex; align-items: center; gap: 10px;">
        <el-button v-auth="'promotion.add'" size="default" plain type="success" @click="handleAdd">
          <SvgIcon name="ele-Plus"/>
          新增活动
        </el-button>
      </div>

      <el-table
          border
          stripe
          :data="state.tableData"
          v-loading="state.loading"
          row-key="id">
        <template #empty>
          <el-empty description="暂无优惠活动"></el-empty>
        </template>
        <el-table-column label="活动标题" prop="title" min-width="180" :show-overflow-tooltip="true"/>
        <el-table-column label="充值金额" prop="rechargeAmount" width="130">
          <template #default="{ row }">
            {{ u.fmt.fmtMoney(row.rechargeAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="赠送金额" prop="grantsAmount" width="130">
          <template #default="{ row }">
            {{ u.fmt.fmtMoney(row.grantsAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="目标用户" width="120">
          <template #default="{ row }">
            <el-tag :type="row.targetMode === 1 ? 'success' : 'warning'" size="small">
              {{ row.targetMode === 1 ? '所有人' : '指定用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="有效期" width="340">
          <template #default="{ row }">
            {{ row.startTime }} ~ {{ row.endTime }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" align="center" fixed="right">
          <template #default="{ row }">
            <el-button v-auth="'promotion.list'" type="primary" size="small" text @click="handleGenerateQR(row)">二维码</el-button>
            <el-button v-auth="'promotion.modify'" type="warning" size="small" text @click="handleEdit(row)">编辑</el-button>
            <el-button v-auth="'promotion.remove'" type="danger" size="small" text @click="handleRemove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <ext-page class="page-pager mt10" v-model:value="state.pageQuery" @change="loadData"/>
    </el-card>

    <el-dialog v-model="state.qrDialogVisible" title="活动二维码" width="400px" center>
      <div style="text-align: center;">
        <el-image v-if="state.qrCodeUrl" :src="state.qrCodeUrl" class="qr-image" fit="contain"/>
        <span v-if="state.qrLoading" style="color: #999;">正在生成二维码...</span>
      </div>
      <template #footer>
        <el-button @click="state.qrDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleGenerateQR(state.currentPromotion, true)">重新生成</el-button>
      </template>
    </el-dialog>
  </div>

  <Dialog ref="dialogRef" @refresh="loadData"/>
</template>

<script setup lang="ts" name="AdminRechargePromotion">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { $get, $body } from "/@/utils/request";
import u from '/@/utils/u'
import { Msg } from "/@/utils/message";

const Dialog = defineAsyncComponent(() => import("./dialog.vue"));

const dialogRef = ref();

const state = reactive({
  loading: false,
  tableData: [] as any[],
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  },
  qrDialogVisible: false,
  qrCodeUrl: '',
  qrLoading: false,
  currentPromotion: null as any,
});

onMounted(() => {
  loadData();
});

const loadData = () => {
  state.loading = true;
  $get('/rechargePromotion/list', state.pageQuery).then((res: any) => {
    state.tableData = res.records || [];
    state.pageQuery.total = res.total || 0;
    state.loading = false;
  }).catch(() => {
    state.loading = false;
  });
};

const handleAdd = () => {
  dialogRef.value.open('add', null);
};

const handleEdit = (row: any) => {
  dialogRef.value.open('edit', row);
};

const handleRemove = (row: any) => {
  Msg.confirm('此操作将永久删除该活动，是否继续?').then(() => {
    $get(`/rechargePromotion/remove/${row.id}`).then(() => {
      Msg.message("删除成功", 'success');
      loadData();
    }).catch(() => {
      Msg.message("删除失败", 'error');
    });
  });
};

const handleGenerateQR = (row: any, force: boolean = false) => {
  state.currentPromotion = row;
  state.qrDialogVisible = true;
  if (row.qrCodeUrl && !force) {
    state.qrCodeUrl = row.qrCodeUrl;
    return;
  }
  state.qrLoading = true;
  state.qrCodeUrl = '';
  $get(`/rechargePromotion/generateQR/${row.id}`).then((url: any) => {
    state.qrCodeUrl = url;
    state.qrLoading = false;
    row.qrCodeUrl = url;
  }).catch(() => {
    state.qrLoading = false;
    Msg.message("生成二维码失败", 'error');
  });
};
</script>
