<!-- 券兑换码 -->
<template>
  <div class="gyq_container">
    <div class="gyq_content" v-if="shopInfo.isHeadShop == 1 || isUse">
      <header-card name="券兑换码" intro="可添加多券组合兑换" icon="qdhm"
        :showSwitch="shopInfo.isHeadShop == 1 || shopInfo.shopType == 'only'" v-model:isOpen="queryForm.isEnable" />
      <div class="row mt14">
        <el-form inline>
          <el-form-item>
            <el-select v-model="queryForm.status" @change="getTableData" style="width: 200px;" placeholder="请选择状态">
              <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="shopInfo.isHeadShop == 1 || shopInfo.shopType == 'only'">
            <el-button type="primary" @click="addRef.show()">添加</el-button>
            <el-button type="primary" plain @click="useShopsRef.show()">适用门店</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="row">
        <el-table :data="tableData.list" border stripe v-loading="tableData.loading">
          <el-table-column label="ID" prop="id" width="80" />
          <el-table-column label="名称" prop="name" />
          <el-table-column label="优惠券（张）" prop="couponInfoList" width="250">
            <template #default="scope">
              <div class="column">
                <div v-for="item in scope.row.couponInfoList" :key="item.id">
                  <el-tag effect="dark" round disable-transitions :type="getRandomStatus()">
                    {{ item.title }} x{{ item.num }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="库存" prop="stock" />
          <el-table-column label="总数" prop="total" />
          <el-table-column label="有效期" width="320">
            <template #default="scope">
              <div>{{ scope.row.startTime }} ~ {{ scope.row.endTime }}</div>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="operateTime">
            <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="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="addRef.show(scope.row)"
                v-if="shopInfo.isHeadShop == 1 || shopInfo.shopType == 'only'">编辑</el-button>
              <el-button link type="primary" @click="recordRef.show(scope.row)">查看</el-button>
            </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>
    </div>
    <div class="gyq_content" v-else>
      门店未参与券兑换码活动或主店未开启活动，如需开启参与请联系主店
    </div>
    <useShops ref="useShopsRef" />
    <add ref="addRef" @success="getTableData" />
    <record ref="recordRef" @update="getTableData" />
  </div>
</template>

<script setup>
import HeaderCard from "../components/headerCard.vue";
import useShops from "./components/useShops.vue";
import add from "./components/add.vue";
import record from "./components/record.vue";
import { ref, reactive, onMounted } from "vue";
import { couponRedemptionEnable, couponRedemptionList, couponRedemptionEnableStatus } from "@/api/coupon/index.js";

const shopInfo = ref(JSON.parse(localStorage.getItem("userInfo")));
const useShopsRef = ref(null);
const addRef = ref(null);
const recordRef = ref(null);

const statusList = ref([
  { label: "全部", value: "" },
  { label: "有效", value: 0, type: 'success' },
  { label: "无效", value: 1, type: 'info' },
]);

function getRandomStatus() {
  const statusList = ['primary', 'success', 'warning', 'danger'];
  // 生成0到数组长度之间的随机整数索引
  const randomIndex = Math.floor(Math.random() * statusList.length);
  // 返回随机索引对应的元素
  return statusList[randomIndex];
}

const queryForm = ref({
  status: "",
  isEnable: 0,
});

watch(
  () => queryForm.value.isEnable,
  (newVal) => {
    if (!tableData.loading) {
      updateStatus();
    }
  }
);

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

// 更新状态
async function updateStatus() {
  try {
    await couponRedemptionEnable({
      isEnable: queryForm.value.isEnable,
    });
  } catch (error) {
    console.log(error);
  }
}

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

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

// 配置信息获取 列表
async function getTableData() {
  try {
    tableData.loading = true;
    const res = await couponRedemptionList({
      status: queryForm.value.status,
      page: tableData.page,
      size: tableData.size,
    });
    tableData.list = res.records;
    tableData.total = res.totalRow;
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    tableData.loading = false;
  }, 500);
}

// 开关状态
const isUse = ref(false)
async function rechargeRedemptionEnableStatusAjax() {
  try {
    const res = await couponRedemptionEnableStatus();
    queryForm.value.isEnable = res.isEnable;


    if (res.isEnable == 1) {
      if (shopInfo.value.shopType == 'only') {
        isUse.value = true
      } else {
        if (res.useType == 'all') {
          isUse.value = true
        } else {
          let currentShopId = shopInfo.value.shopId;
          res.shopIdList.some((item) => {
            if (item == currentShopId) {
              isUse.value = true;
              return true;
            }
          });
        }
      }
    } else {
      isUse.value = false;
    }
  } catch (error) {
    console.log(error);
  }
}

onMounted(() => {
  getTableData();
  rechargeRedemptionEnableStatusAjax()
});
</script>

<style scoped lang="scss">
.gyq_container {
  padding: 14px;

  .gyq_content {
    padding: 14px;
    background-color: #fff;
    border-radius: 8px;
  }
}

.row {
  &.mt14 {
    margin-top: 14px;
  }
}

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