<template>
  <tabbar :titles="['全部', '进行中', '已结束']" @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 { 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 { showToast } from '@/utils';
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);

onLoad((e) => {
  fetchData();
});

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);
  }
};

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>
