<template>
  <div>
    <el-dialog title="充值兑换码" top="5vh" width="800px" v-model="visible" @closed="closedHandle">
      <el-form label-width="80px" label-position="right">
        <el-form-item label="名称">
          {{ form.name }}
        </el-form-item>
        <el-form-item label="活动日期">
          {{ form.startTime }} ~ {{ form.endTime }}
        </el-form-item>
        <el-form-item label="金额">
          {{ form.amount }}
        </el-form-item>
        <el-form-item label="总数">
          {{ form.total }}
        </el-form-item>
        <el-form-item label="库存">
          {{ form.stock }}
        </el-form-item>
        <el-form-item v-if="shopInfo.isHeadShop == 1 || shopInfo.shopType == 'only'">
          <el-button type="primary" @click="addRef.show({ ...form })">编辑</el-button>
        </el-form-item>
      </el-form>
      <div class="row mt14">
        <el-form :model="queryForm" inline>
          <el-form-item>
            <el-select v-model="queryForm.status" style="width: 200px;" placeholder="请选择状态" @change="getTableData">
              <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="queryForm.code" placeholder="请输入兑换码" style="width: 200px;" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchHandle">搜索</el-button>
            <el-button type="primary" plain @click="exportHandle">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="row mt14">
        <el-table :data="tableData.list" border stripe v-loading="tableData.loading" height="300px">
          <el-table-column label="兑换码" prop="code">
            <template #default="scope">
              <div class="center" @click="copyHandle(scope.row.code)">
                <el-text>{{ scope.row.code }}</el-text>
                <el-link type="primary">复制</el-link>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="100">
            <template #default="scope">
              <el-tag disable-transitions :type="statusList.find(item => item.value === scope.row.status).type">
                {{statusList.find(item => item.value === scope.row.status).label}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="兑换时间" prop="redemptionTime" />
          <el-table-column label="兑换用户" prop="nickName">
            <template #default="scope">
              <div class="column">
                <span>{{ scope.row.nickName }}</span>
                <span>{{ scope.row.phone }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="row mt14">
        <el-pagination v-model:current-page="tableData.page" v-model:page-size="tableData.size"
          :page-sizes="[10, 30, 50, 100]" background layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-dialog>
    <add ref="addRef" @success="rechargeRedemptionDetailAjax" />
  </div>
</template>

<script setup>
import { ref } from "vue";
import add from "./add.vue";
import { rechargeRedemptionCodeList, rechargeRedemptionDetail, rechargeRedemptionExport } from "@/api/coupon/index.js";
import { downloadFile } from "@/utils/index";
import useClipboard from "vue-clipboard3";
const { toClipboard } = useClipboard();

const emit = defineEmits(['update']);
const addRef = ref(null);
const visible = ref(false);
const shopInfo = ref(JSON.parse(localStorage.getItem("userInfo")));

const form = ref({
  id: '',
  name: '',
  startTime: '',
  endTime: '',
  amount: '',
  total: 0,
  stock: 0,
});

const resetForm = () => {
  form.value = {
    id: '',
    name: '',
    startTime: '',
    endTime: '',
    amount: '',
    total: 0,
    stock: 0,
  };
};

// 复制
async function copyHandle(text) {
  try {
    await toClipboard(text);
    ElNotification({
      title: "成功",
      message: `复制成功`,
      type: "success",
    });
    console.log("Copied to clipboard");
  } catch (e) {
    console.error(e);
  }
}

// 关闭
function closedHandle() {
  resetForm();
  tableData.list = [];
  tableData.page = 1;
  tableData.size = 10;
  tableData.total = 0;
  queryForm.value = {
    status: "",
    code: '',
  };
  emit('update')
}

const statusList = ref([
  { label: "全部", value: "" },
  { label: "已兑换", value: 1, type: 'info' },
  { label: "未兑换", value: 0, type: 'success' },
]);

const queryForm = ref({
  status: "",
  code: '', // 兑换码
});

const tableData = reactive({
  list: [],
  loading: false,
  page: 1,
  size: 10,
  total: 0,
});

// 分页大小发生变化
function handleSizeChange(e) {
  tableData.size = e;
  getTableData();
}

// 分页发生变化
function handleCurrentChange(e) {
  tableData.page = e;
  getTableData();
}

function searchHandle() {
  tableData.page = 1;
  getTableData();
}

const redemptionId = ref('')
async function getTableData(id) {
  // 获取表格数据
  try {
    tableData.loading = true
    const res = await rechargeRedemptionCodeList({
      redemptionId: redemptionId.value,
      ...queryForm.value,
      page: tableData.page,
      size: tableData.size,
    })
    tableData.totalAmount = res.totalAmount
    tableData.list = res.records
    tableData.total = +res.totalRow
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    tableData.loading = false
  }, 500);
}

// 导出配置
const exportLoading = ref(false)
async function exportHandle() {
  try {
    exportLoading.value = true
    const file = await rechargeRedemptionExport({
      redemptionId: redemptionId.value,
      ...queryForm.value,
    });
    downloadFile(file, "数据", "xlsx");
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    exportLoading.value = false
  }, 500);
}

// 获取配置详情
async function rechargeRedemptionDetailAjax() {
  try {
    const res = await rechargeRedemptionDetail({ id: redemptionId.value });
    form.value = {
      id: res.id || '',
      name: res.name || '',
      startTime: res.startTime || '',
      endTime: res.endTime || '',
      amount: res.amount || '',
      total: res.total || 0,
      stock: res.stock || 0,
    };
  } catch (error) {
    console.log(error);
  }
}

function show(obj) {
  visible.value = true;
  redemptionId.value = obj.id
  getTableData()
  rechargeRedemptionDetailAjax()
}

defineExpose({
  show,
});
</script>

<style scoped lang="scss">
.row {
  &.mt14 {
    margin-top: 14px;
  }
}

.center {
  display: flex;
  align-items: center;
  gap: 10px;
}

.column {
  display: flex;
  flex-direction: column;
}
</style>