<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 v-if="isDelete" class="searchRow flex-row justify-between">
          <div class="l-flex-RC c-text-15 c-text-color c-text-b">
            {{ $t("advertManage.advertRule.selected") }}
            {{ selectTotals }}
            {{ $t("advertManage.advertRule.individual") }}
          </div>
        </div>
        <div v-else 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>
          </div>
        </div>
        <div class="tabButtomBox flex-row">
          <div class="tabBox flex-row">
            <span :class="{ active: isUse === '0' }" @click="setIsUse('0')" style="cursor: pointer;">{{
              $t('discountCode.notUsed') }}</span>
            <span :class="{ active: isUse === '1' }" @click="setIsUse('1')" style="cursor: pointer;">{{
              $t('discountCode.used') }}</span>
          </div>
          <div v-if="isDelete" class="buttomBox flex-row">
            <div @click="cancelClk" class="buttonItem" style="color: #9696b1;">
              {{ $t("discountCode.cancel") }}
            </div>
            <div @click="allClk" class="buttonItem" style="color: #2c87c8">
              {{ $t("discountCode.selectAll") }}
            </div>
            <div @click="noticeClk" class="buttonItem" style="color: #df5e4c">
              {{ $t("discountCode.confirmDel") }}
            </div>
          </div>
          <div v-else class="buttomBox flex-row">
            <div class="buttonItem" @click="payCode()" style="color: #2c87c8">{{ $t('discountCode.apply') }}</div>
            <div class="buttonItem" @click="isDelete = true">{{ $t('discountCode.delete') }}</div>
            <div class="buttonItem" @click="exportClick()" style="color: #45be2d">{{ $t('discountCode.export') }}</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">
                  {{ item.type == '1' ? $t('discountCode.deduction') : $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="user.type < 2">
                <span class="itemTitle">
                  {{ $t('discountCode.affiliatedMerchants') }}:&nbsp;
                </span>
                {{ item.userName }}
              </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' && isDelete == false">
              {{ $t('discountCode.notUsed') }}
            </div>
            <div class="tipBox isUseTip" v-if="item.isUse === '1' && isDelete == false">
              {{ $t('discountCode.used') }}
            </div>
            <div v-if="isDelete" class="checkedBox">
              <van-checkbox checked-color="#2c87c8" v-model="item.checked"></van-checkbox>
            </div>
          </div>
        </div>
      </van-list>
    </div>
    <codeSearch ref="searchRef" @search="search($event)"></codeSearch>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs, ref, computed } from "vue";
import sHeader from "@/components/SimpleHeader";
import { getdiscountCodeList, discountCodeExport, deleteCode } from "@/service/discountCode";
import { showFailToast, showToast, showConfirmDialog } 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";
import { useI18n } from "vue-i18n";


export default {
  setup() {
    const { t } = useI18n();
    const router = useRouter();
    const searchRef = ref(null);
    const user = getLoginUser();
    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 () => {
      //加载样式
      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") {
        // 加入删除选中状态
        if (data.data.records.length > 0) {
          data.data.records.forEach((item) => {
            item.checked = false;
          });
        }
        // 列表值叠加
        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;
    });

    // 是否删除状态
    const isDelete = ref(false); // 选中
    const selectTotals = computed(() => {
      let nums = 0;
      if (discountCodeList.value.length > 0) {
        discountCodeList.value.forEach((item) => {
          if (item.checked) {
            nums++;
          }
        });
      }
      return nums;
    });
    const cancelClk = () => {
      // 把选中状态去掉
      if (discountCodeList.value.length > 0) {
        discountCodeList.value.forEach((item) => {
          if (item.checked) {
            item.checked = false;
          }
        });
      }
      isDelete.value = false;
    };
    // 点击全选
    const allClk = () => {
      if (discountCodeList.value.length > 0) {
        discountCodeList.value.forEach((item) => {
          item.checked = true;
        });
      }
    };
    // 点击确认删除
    const noticeClk = () => {
      if (selectTotals.value < 1) {
        showToast(t("advertManage.delTips"));
        return;
      }
      showConfirmDialog({
        title: t('advertManage.delPopTitle'),
        message: t('advertManage.delPopContent'),
      })
        .then(() => {
          const ids = [];
          discountCodeList.value.forEach((item) => {
            if (item.checked) {
              ids.push(item.id);
            }
          });
          deleteCode(ids).then((res) => {
            console.log(res);
            if (res.data.code === '00000') {
              isDelete.value = false;
              showToast(t('discountCode.deletionSucceeded'));
              setTimeout(() => {
                discountCodeList.value = [];
                getList();
              }, 1500);
            }
          }).catch(() => {
            isDelete.value = false;
            showToast('ERROR');
          });
        })
        .catch(() => {
          // showToast('ERROR');
        })
    };

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

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