<template>
  <!-- 优惠码 -->
  <div class="discountCodePage flex-col">
    <s-header :name="'优惠码'" :noback="false"></s-header>
    <div class="discountCodeBox flex-col">
      <van-list
        v-model:loading="loading"
        v-model:error="error"
        error-text="请求失败，点击重新加载"
        :finished="finished"
        finished-text="没有更多了"
        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"
                >共<span class="discountNumber">{{ discountCodeTotal }}</span
                >个优惠码</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">搜索</span>
              </div>
            </div>
          </div>
        </div>
        <div class="tabButtomBox flex-row">
          <div class="tabBox flex-row">
            <span :class="{ active: isUse === '0' }" @click="setIsUse('0')" >未使用</span>
            <span :class="{ active: isUse === '1' }" @click="setIsUse('1')">已使用</span>
          </div>
          <div class="buttomBox flex-row">
            <div class="buttonItem" @click="exportClick()" >导出&gt;</div>
            <div class="buttonItem" @click="payCode()">申请&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">优惠码:&nbsp;</span>{{item.code}}<span class="itemTitle discount">折扣:&nbsp;</span>{{item.discount}}</div>
              <div class="itemRow"><span class="itemTitle">创建时间:&nbsp;</span>{{showDateTime(item.createDate)}}</div>
              <div class="itemRow"><span class="itemTitle">使用时间:&nbsp;</span>{{showDateTime(item.useDate)}}</div>
              <div class="itemRow"><span class="itemTitle">有效期:&nbsp;</span>{{showDate(item.lastUseDate)}}</div>
              <div class="itemRow"><span class="itemTitle">使用机器:&nbsp;</span>{{item.useBy}}</div>
            </div>
            <div class="tipBox" v-if="item.isUse === '0'">未使用</div>
            <div class="tipBox isUseTip" v-if="item.isUse === '1'">已使用</div>
          </div>
        </div>
      </van-list>
    </div>
    <nav-bar></nav-bar>
    <codeSearch ref="searchRef" @search="search($event)"></codeSearch>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs, ref } from "vue";
import navBar from "@/components/NavBar";
import sHeader from "@/components/SimpleHeader";
import { getdiscountCodeList, discountCodeExport } from "@/service/discountCode";
import { Toast } from "vant";
import { getLoginUser } 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', // 是否使用
      // type: null // 优惠码类型 0或null:折扣优惠码；1：抵扣价优惠码
    });
    // 初始化页面获取列表
    onMounted(async () => {
      // 初始化列表及页码
      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 { Toast.fail(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 () => {
      const { headers, data } = await discountCodeExport( Object.assign({}, searchParams) );
      const blob = new Blob([data])
      const downloadElement = document.createElement('a');
      const href = window.URL.createObjectURL(blob); //创建下载的链接
      downloadElement.href = href;
      downloadElement.download = decodeURIComponent(headers['content-disposition'].split('filename=')[1]); //下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); //点击下载
      document.body.removeChild(downloadElement); //下载完成移除元素
      window.URL.revokeObjectURL(href); //释放掉blob对象
    }
    const payCode = () => { router.push({ path: '/payCode' }); };
    return {
      searchRef,
      loading,
      error,
      finished,
      discountCodeList,
      discountCodeTotal,
      ...toRefs(searchParams),
      onLoad,
      searchClick,
      search,
      setIsUse,
      disCountCodeClick,
      showDate,
      showDateTime,
      exportClick,
      payCode
    };
  },
  components: { sHeader, navBar, codeSearch },
};
</script>

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