<template>
  <tabbar :titles="['全部', '未支付', '已支付']" :index='payStatus' @change='tabChange' />
  <u-list :list='orderList' :border='false' @scrolltolower='loadMore'>
    <u-list-item v-for='(item,index) in orderList' :key='index'>
      <order-item :item='item' @addShoppingCart='addShoppingCart' @pay='payment' />
    </u-list-item>
    <u-loadmore status='loading' />
  </u-list>
  <sku-dialog ref='skuDialogRef' :exists='temporaryStockBean' />

</template>

<script lang='ts' setup>

import { ref } from 'vue';
import { showToast } from '@/utils';
import { isPending } from '@/utils/order';
import { getOrderList } from '@/api/order';
import OrderItem from '@/pages/mine/subs/order/components/order-item.vue';
import { OrderBean } from '@/api/order/types';
import SkuDialog from '@/components/sku-dialog.vue';
import { GoodsBean, StockBean } from '@/api/goods/types';
import useShoppingCartStore from '@/store/modules/shoppingcart';

const shoppingCartStore = useShoppingCartStore();
const skuDialogRef = ref();
const temporaryStockBean = ref<StockBean>();
const orderList = ref<OrderBean[]>([]);
const currentPageNum = ref(1);
const payStatus = ref(0);

let currentInterval = 0;

onLoad((e: any) => {
  const index = Number(e.index) || 0;
  tabChange(index);
});

onUnload(() => {
  clearInterval(currentInterval);
});

const tabChange = (index: number) => {
  payStatus.value = index;
  fetchData(true);
};

const fetchData = async (refresh: boolean = true) => {
  if(!refresh) {
    currentPageNum.value += 1;
  }
  const { list } = await getOrderList({
    pageNum: currentPageNum.value,
    pageSize: 20,
    obj: { payStatus: payStatus.value }
  });
  if(refresh) {
    orderList.value = list;
  } else {
    orderList.value = orderList.value.concat(list);
  }
  handleCountdown(orderList.value.filter(item => item.payStatus == 1));
};

const handleCountdown = (items: OrderBean[]) => {
  clearInterval(currentInterval);
  let second = 30 * 60;
  currentInterval = setInterval(() => {
    items.forEach(item => {
      if(isPending(item)) {
        item.countdown = second;
        if(item.countdown <= 0) {
          item.countdown = 0;
        }
        second--;
      }
    });
  }, 1000);
};


const loadMore = () => {
  fetchData(false);
};

const addShoppingCart = (item: GoodsBean) => {
  skuDialogRef.value.show(item.goodsId, (e: GoodsBean) => {
    shoppingCartStore.save(e);
    showToast('加入购物车成功');
  });
};

const payment = (orderId: string) => {
  console.log(orderId);
};
</script>

<style lang='scss' scoped>

</style>
