<route lang="json5" type="page">
{
  style: {
    navigationStyle: "custom",
    navigationBarTitleText: "我的订单",
    navigationBarBackgroundColor: "#FFF",
  },
}
</route>

<template>
  <wd-tabs color="#333" inactiveColor="#888" @click="handleClick">
    <block v-for="item in tabs" :key="item.state">
      <wd-tab :title="item.tabName" :name="item.state">
        <scroll-view scroll-y class="page-wrapper" @scrolltolower="queryNext">
          <!-- <view class="order-wrapper flex flex-col flex-items-center" v-if="Array.isArray(list[item.state]) && list[item.state].length > 0"> -->
          <!-- <view v-for="(ele,index) in list[item.state]" :key="`${ele.id}-${item.state}`">
                            <OrderItem :detail="ele" @pay-event="pay" @detail-event="viewDetail" @pwd-event="viewPwd"/>
                        </view> -->
          <view
            class="order-wrapper flex flex-col flex-items-center"
            v-if="Array.isArray(list) && list.length > 0"
          >
            <view v-for="(ele, index) in list" :key="`${ele.id}-${item.state}`">
              <OrderItem
                :detail="ele"
                @pay-event="pay"
                @detail-event="viewDetail"
                @pwd-event="viewPwd"
                @del-event="removeOrder"
                @refund-event="refund"
              />
            </view>
            <view class="no-more" v-if="isLastPage">没有更多了~</view>
          </view>
          <view class="no-data" v-else>
            <image
              src="/static/ycnc/bg-nodata.png"
              mode="scaleToFill"
              class="no-img"
            />
            <text class="no-text">暂无订单，快去下单吧~</text>
          </view>
        </scroll-view>
      </wd-tab>
    </block>
  </wd-tabs>
  <wd-message-box />
</template>

<script setup>
import { useMessage } from "wot-design-uni";
import OrderItem from "./components/order-item";
import {
  getOrderList,
  deleteOrder,
  refundOrder,
  queryOrderDetail,
} from "../../api/ycnc";
import { onMounted, ref, unref, reactive, computed } from "vue";
import { tabs } from "./config";
import { deepClone, getQueryString } from "../../utils/utils";
const message = useMessage();
const pageSize = 10;
const activeName = ref(0);
const total = ref(0);
const page = ref(1);
const list = ref([]);
const replace = ref(false);

//获取订单列表
const queryOrderList = () => {
  const activeTab = unref(activeName);
  const params = {
    page: unref(page),
    pageSize: pageSize,
    backUrl: uni.getStorageSync("backUrl"),
    ...(activeTab !== 0 && { state: activeTab }),
  };
  getOrderList({ params })
    .then((res) => {
      const { count, data } = res;
      total.value = count;
      if (replace.value) {
        const prevPage = page.value - 1;
        const prevList = list.value.slice(0, prevPage * pageSize);
        list.value = [...prevList, ...data];
      } else {
        list.value = [...list.value, ...data];
      }
      replace.value = false;
    })
    .catch((err) => {
      total.value = 0;
      list.value = [];
    });
};

function handleClick({ index, name }) {
  page.value = 1;
  total.value = 0;
  list.value = [];
  activeName.value = name;
  // name代表状态值
  queryOrderList();
}

async function pay(orderData) {
  console.log(orderData);
  const { order_no, notify_url, price, brand, sign, plain_text, id, pay_url } =
    orderData;
  window.location.replace(pay_url);
}

function viewDetail(orderData) {
  const { id, order_no } = orderData;
  uni.navigateTo({
    url: `/pages/ycnc/orderDetail?order_id=${id}&order_no=${order_no}`,
  });
}

function viewPwd(orderData) {
  const { voucher_link } = orderData;
  if (voucher_link) {
    console.log("跳转外部链接--->", voucher_link);
    window.location.href = voucher_link;
  } else {
    console.error(`${voucher_link}无有效值`);
  }
}

function removeOrder(orderData) {
  message
    .confirm({
      msg: "删除订单后无法恢复，确认继续吗？",
      title: "提示",
    })
    .then(() => {
      const { id } = orderData;
      const params = { order_id: id };
      deleteOrder({ params })
        .then((res) => {
          replace.value = true;
          queryOrderList();
        })
        .catch((err) => {
          console.log(err);
        });
    })
    .catch(() => {
      console.log("点击了取消按钮");
    });
}

function refund(orderData) {
  const { id } = orderData;
  if (!id) {
    uni.showToast({
      icon: "none",
      title: "无有效的订单id",
    });
    return;
  }
  const params = { order_id: id };
  refundOrder({ params })
    .then((res) => {
      uni.showToast({
        icon: "success",
        title: "退款成功",
      });
      replace.value = true;
      queryOrderList();
    })
    .catch((err) => {
      console.log(err);
    });
}

onMounted(() => {
  queryOrderList();
});

const isLastPage = computed(() => {
  return unref(page) === Math.ceil(unref(total) / pageSize);
});

function queryNext() {
  if (unref(isLastPage)) {
    console.error("已经是最后一页");
    return false;
  }
  page.value = page.value + 1;
  queryOrderList();
}
</script>

<style lang="scss" scoped>
.page-wrapper {
  width: 100%;
  // height: 100%;
  height: calc(100vh - 42rpx);
  overflow-y: auto;
  background: #fafbfd;
  box-sizing: border-box;
  padding-bottom: 30rpx;
}
.order-wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;
}
.no-more {
  font-weight: normal;
  font-size: 18rpx;
  color: #999999;
  height: 146rpx;
  padding: 28rpx 0;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  box-sizing: border-box;
}
.no-data {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  .no-img {
    width: 446rpx;
    height: 446rpx;
  }
  .no-text {
    font-weight: normal;
    font-size: 24rpx;
    color: #999999;
  }
}
/* 修改标签页下划线颜色*/
// :deep(.wd-button.is-primary){
//     background: #EA0000;
// }
:deep(.wd-tabs__line) {
  background: #ea0000;
}
:deep(.wd-tabs) {
  display: flex;
  flex-direction: column;
  height: 100%;
}
:deep(.wd-tab__body) {
  height: calc(100vh - 42rpx);
}
:deep(.wd-tabs__container) {
  flex: 1;
}
</style>
