<script setup lang="ts">
import { reactive, onMounted, ref } from "vue";
import { getPromotionList, removePromotion, generatePromotionQR } from "@/api/recharge-promotion";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox } from "element-plus";
import PromotionDialog from "./dialog.vue";

defineOptions({ name: "AdminRechargePromotion" });

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;
  getPromotionList(state.pageQuery)
    .then((res: any) => {
      state.tableData = res?.records || res?.list || [];
      state.pageQuery.total = res?.total || 0;
    })
    .catch(() => {
      state.tableData = [];
    })
    .finally(() => {
      state.loading = false;
    });
};

const handleSizeChange = (size: number) => {
  state.pageQuery.pageSize = size;
  loadData();
};

const handleCurrentChange = (page: number) => {
  state.pageQuery.pageNum = page;
  loadData();
};

const handleAdd = () => dialogRef.value?.open("add");

const handleEdit = (row: any) => dialogRef.value?.open("edit", row);

const handleRemove = (row: any) => {
  ElMessageBox.confirm("确定要删除该活动吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    removePromotion(row.id).then(() => {
      ElMessage.success("删除成功");
      loadData();
    }).catch(() => {
      ElMessage.error("删除失败");
    });
  }).catch(() => {});
};

const handleGenerateQR = (row: any) => {
  state.currentPromotion = row;
  state.qrDialogVisible = true;
  if (row.qrCodeUrl) {
    state.qrCodeUrl = row.qrCodeUrl;
    return;
  }
  state.qrLoading = true;
  state.qrCodeUrl = "";
  generatePromotionQR(row.id)
    .then((url: any) => {
      state.qrCodeUrl = url;
      row.qrCodeUrl = url;
    })
    .catch(() => {
      ElMessage.error("生成二维码失败");
    })
    .finally(() => {
      state.qrLoading = false;
    });
};

const formatMoney = (value: number) => {
  if (value === null || value === undefined) return "¥0.00";
  return `¥${(value / 100).toFixed(2)}`;
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <span class="card-header">专属优惠活动</span>
      </template>
      <div class="toolbar mb10">
        <el-button type="success" :icon="useRenderIcon('ri/add-line')" @click="handleAdd">
          新增活动
        </el-button>
      </div>

      <el-table
        v-loading="state.loading"
        :data="state.tableData"
        border
        stripe
        row-key="id"
      >
        <template #empty>
          <el-empty description="暂无优惠活动" />
        </template>
        <el-table-column label="活动标题" prop="title" min-width="180" show-overflow-tooltip />
        <el-table-column label="充值金额" prop="rechargeAmount" width="130">
          <template #default="{ row }">{{ formatMoney(row.rechargeAmount) }}</template>
        </el-table-column>
        <el-table-column label="赠送金额" prop="grantsAmount" width="130">
          <template #default="{ row }">{{ formatMoney(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 type="primary" link size="small" @click="handleGenerateQR(row)">二维码</el-button>
            <el-button type="warning" link size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link size="small" @click="handleRemove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="state.pageQuery.pageNum"
          v-model:page-size="state.pageQuery.pageSize"
          :total="state.pageQuery.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 二维码弹窗 -->
    <el-dialog v-model="state.qrDialogVisible" title="活动二维码" width="400px" center>
      <div style="text-align: center">
        <el-image v-if="state.qrCodeUrl && !state.qrLoading" :src="state.qrCodeUrl" style="max-width: 280px; max-height: 280px" 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)">重新生成</el-button>
      </template>
    </el-dialog>

    <PromotionDialog ref="dialogRef" @refresh="loadData" />
  </div>
</template>

<style scoped lang="scss">
.card-header { font-size: 16px; font-weight: 600; }

.page-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
