<template>
  <!-- 优惠码 -->
  <div class="discountCodePage flex-col">
    <s-header :name="$t('discountCode.discountCode')" :noback="false"></s-header>
    <div class="discountCodeBox flex-col">
      <van-list v-model:loading="loading" v-model:error="error" :error-text="$t('public.requestFailed')"
        :finished="finished" :finished-text="$t('public.noMore')" offset="300" :immediate-check="false" @load="onLoad">
        <div class="searchRow flex-row justify-between">
          <div class="flex-col">
            <div class="flex-row justify-between bd3">
              <div class="flex-col outer4"></div>
              <span class="flex-col txt2">{{ $t('discountCode.total') }}<span class="discountNumber">{{ discountCodeTotal
              }}</span>{{ $t('discountCode.discountCodesInTotal') }}</span>
            </div>
          </div>
          <div class="flex-col">
            <div class="main5 flex-row justify-between" @click="searchClick">
              <img class="label2" src="../../assets/device/searchIcon.png" />
              <div class="TextGroup2 flex-col">
                <span class="txt3">{{ $t('discountCode.search') }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="tabButtomBox flex-row">
          <div class="tabBox flex-row">
            <span :class="{ active: isUse === '0' }" @click="setIsUse('0')">{{ $t('discountCode.notUsed') }}</span>
            <span :class="{ active: isUse === '1' }" @click="setIsUse('1')">{{ $t('discountCode.used') }}</span>
          </div>
          <div class="buttomBox flex-row">
            <div class="buttonItem" @click="exportClick()">{{ $t('discountCode.export') }}&gt;</div>
            <div class="buttonItem" @click="payCode()">{{ $t('discountCode.apply') }}&gt;</div>
          </div>
        </div>
        <div class="intervalRow"></div>
        <div class="listBox">
          <div v-for="(item, index) in discountCodeList" :key="index" class="listItem" @click="disCountCodeClick(item)">
            <div class="itemBox">
              <div class="itemRow"><span class="itemTitle">{{ $t('discountCode.discountCode') }}:&nbsp;</span>{{ item.code
              }}<span class="itemTitle discount">{{ $t('discountCode.discount') }}:&nbsp;</span>{{ item.discount }}
              </div>
              <div class="itemRow"><span class="itemTitle">{{ $t('discountCode.creationTime') }}:&nbsp;</span>{{
                showDateTime(item.createDate) }}</div>
              <div class="itemRow" v-if="item.isUse !== '0'"><span class="itemTitle">{{ $t('discountCode.usageTime') }}:&nbsp;</span>{{
                showDateTime(item.useDate) }}</div>
              <div class="itemRow"><span class="itemTitle">{{ $t('discountCode.termOfValidity') }}:&nbsp;</span>{{
                showDate(item.lastUseDate) }} <span v-if="item.isUse === '0' && isExpired(item.lastUseDate)">{{ $t('discountCode.expired') }}</span></div>
              <div class="itemRow" v-if="item.isUse !== '0'"><span class="itemTitle">{{ $t('discountCode.usingTheMachine') }}:&nbsp;</span>{{
                item.useBy }}</div>
            </div>
            <div class="tipBox" v-if="item.isUse === '0'">{{ $t('discountCode.notUsed') }}</div>
            <div class="tipBox isUseTip" v-if="item.isUse === '1'">{{ $t('discountCode.used') }}</div>
          </div>
        </div>
      </van-list>
    </div>
    <codeSearch ref="searchRef" @search="search($event)"></codeSearch>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import { getdiscountCodeList, discountCodeExport } from "@/service/discountCode";
import { showFailToast } from "vant";
import { getLoginUser, $M_ExportFile, styleUrl } from "@/common/js/utils";
import codeSearch from './codeSearch.vue';
import dateUtil from "@/utils/dateUtil";
import { useRouter } from "vue-router";

export default {
  setup() {
    const router = useRouter();
    const searchRef = ref(null);
    const loading = ref(false); // 加载状态
    const error = ref(false); // 错误状态
    const finished = ref(false); // 结束翻页状态
    const discountCodeList = ref([]); // 列表集合
    const discountCodeTotal = ref(0); // 列表总数
    let searchParams = reactive({
      adminId: "", // 用户账户id
      current: 1, // 页数
      size: 20, // 页大小
      isUse: '0', // 是否使用,0:未使用；1：已使用
      // type: null // 优惠码类型 0或null:折扣优惠码；1：抵扣价优惠码
    });
    // 初始化页面获取列表
    onMounted(async () => {
      //加载样式
      styleUrl('discountCode');
      // 初始化列表及页码
      const user = getLoginUser();
      if (user) {
        searchParams.adminId = user.id;
        searchGetList();
      }
    });
    // 搜索弹窗触发搜索
    const search = (data) => {
      searchParams = Object.assign(searchParams, data);
      searchGetList();
    };
    // 查询列表
    const searchGetList = () => {
      discountCodeList.value = [];
      searchParams.current = 1;
      getList();
    }
    // 滚动加载
    const onLoad = () => { if (!finished.value) { searchParams.current = searchParams.current + 1; getList(); } };
    // 获取设备列表数据
    const getList = async () => {
      const { data } = await getdiscountCodeList(Object.assign({}, searchParams));
      if (data.code === "00000") {
        // 列表值叠加
        discountCodeList.value = discountCodeList.value.concat(data.data.records);
        discountCodeTotal.value = data.data.total;
        if (discountCodeList.value.length === data.data.total) { finished.value = true; }
        loading.value = false;
      } else { showFailToast(data.message); }
    };
    // 搜索点击
    const searchClick = () => { searchRef.value.showSearch(); };
    // 切换tab
    const setIsUse = (data) => { searchParams.isUse = data; searchGetList(); }
    // 点击优惠码
    const disCountCodeClick = (data) => { console.log('disCountCodeClick', data); }
    // 时间格式化
    const showDate = (date) => { return date ? dateUtil.formateDate(new Date(date), "yyyy-MM-dd") : ''; }
    const showDateTime = (date) => { return date ? dateUtil.formateDate(new Date(date), "yyyy-MM-dd hh:mm:ss") : ''; }
    // 优惠码导出
    const exportClick = async () => {
      searchParams.size = 1000;
      const { headers, data } = await discountCodeExport(Object.assign({}, searchParams));
      $M_ExportFile(data, headers);
    }
    const payCode = () => { router.push({ path: '/payCode' }); };

    const isExpired = ref((lastUseDate) => {
      const currentDate = new Date();
      const lastUseDateTime = new Date(lastUseDate);
      return currentDate > lastUseDateTime;
    });

    return {
      searchRef,
      loading,
      error,
      finished,
      discountCodeList,
      discountCodeTotal,
      ...toRefs(searchParams),
      onLoad,
      searchClick,
      search,
      setIsUse,
      disCountCodeClick,
      showDate,
      showDateTime,
      exportClick,
      payCode,
      isExpired,
    };
  },
  components: { sHeader, codeSearch },
};
</script>

<style lang="less" scoped>
@import "../../common/style/common.less";
</style>
