<template>
  <view>
    <view class="my-order">
      <view class="header">
        <view class="picTxt acea-row row-between-wrapper">
          <view class="text">
            <view class="name">订单信息</view>
            <view>
              <text class="consumer-order"
                >消费订单:{{ orderDataState.orderCount || 0 }}</text
              >
              <text
                >总消费:￥{{
                  Number(orderDataState.sumPrice).toFixed(2) || 0
                }}</text
              >
            </view>
          </view>
          <view class="pictrue">
            <image src="/static/images/orderTime.png"></image>
          </view>
        </view>
      </view>
      <view class="nav acea-row row-around">
        <view
          class="item"
          :class="orderStatus == 0 ? 'on' : ''"
          @click="statusClick(0)"
        >
          <view>待付款</view>
          <view class="num">{{ orderDataState.unPaidCount || 0 }}</view>
        </view>
        <view
          class="item"
          :class="orderStatus == 1 ? 'on' : ''"
          @click="statusClick(1)"
        >
          <view>待发货</view>
          <view class="num">{{ orderDataState.unShippedCount || 0 }}</view>
        </view>
        <view
          class="item"
          :class="orderStatus == 2 ? 'on' : ''"
          @click="statusClick(2)"
        >
          <view>待收货</view>
          <view class="num">{{ orderDataState.receivedCount || 0 }}</view>
        </view>
        <!-- <view
          class="item"
          :class="orderStatus == 3 ? 'on' : ''"
          @click="statusClick(3)"
        >
          <view>待评价</view>
          <view class="num">{{ orderDataState.evaluatedCount || 0 }}</view>
        </view> -->
        <view
          class="item"
          :class="orderStatus == 4 ? 'on' : ''"
          @click="statusClick(4)"
        >
          <view>已完成</view>
          <view class="num">{{ orderDataState.completeCount || 0 }}</view>
        </view>
        <view class="item" @click="toReturnList">
          <view>退货/退款</view>
          <view class="num">{{ orderDataState.refundCount || 0 }}</view>
        </view>
      </view>
      <view class="list">
        <OrderListCard
          v-for="(item, index) in orderList"
          :key="index"
          :order="item"
          :index="index"
          @cancelOrder="cancelOrder"
          @goPay="goPay"
          @goOrderDetails="goOrderDetails"
          :mallType="0"
          @delOrder="delOrder"
        />
      </view>
      <view
        class="loadingicon acea-row row-center-wrapper"
        v-if="orderList.length > 0"
      >
        <text
          class="loading iconfont icon-jiazai"
          :hidden="loading == false"
        ></text
        >{{ loadTitle }}
      </view>
      <view v-if="orderList.length == 0">
        <emptyPage title="暂无订单~"></emptyPage>
      </view>
    </view>
    <!-- <view class='noCart' v-if="orderList.length == 0 && page > 1">
      <view class='pictrue'>
        <image src='/static/images/noOrder.png'></image>
      </view>
    </view> -->
    <payment
      @closePopup="closePayPopup"
      :payMode="payMode"
      :showPopup="showPopup"
      @payComplete="payComplete"
      @payFail="payFail"
      @onChangeFun="onChangeFun"
      :order_id="pay_order_id"
      :totalPrice="totalPrice"
    ></payment>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onShow,onLoad, onReachBottom } from "@dcloudio/uni-app";
import OrderListCard from "@/components/OrderListCard";
import { useAppStore } from "@/stores/app";
import { getOrderList, orderData, orderCancel, orderDel } from "@/api/order.js";
import payment from "@/components/payment";
import { toLogin } from "@/libs/login.js";
import emptyPage from "@/components/emptyPage.vue";
import { useToast } from "@/hooks/useToast";

const appStore = useAppStore();
const { Toast } = useToast();

// 状态
const loading = ref(false);
const loadend = ref(false);
const loadTitle = ref("加载更多");
const orderList = ref([]);
const orderDataState = ref({});
const orderStatus = ref(0);
const page = ref(1);
const limit = ref(10);
const payMode = ref([
  {
    name: "微信支付",
    icon: "icon-weixinzhifu",
    value: "weixin",
    title: "微信快捷支付",
  },
  {
    name: "余额支付",
    icon: "icon-yuezhifu",
    value: "yue",
    title: "可用余额:",
    number: 0,
  },
]);
const showPopup = ref(false);
const pay_order_id = ref("");
const totalPrice = ref("0");

// 生命周期
// onMounted(() => {
//   if (appStore.isLogin) {
//     loadend.value = false;
//     page.value = 1;
//     orderList.value = [];
//     getOrderData();
//     getOrderListFn();
//   } else {
//     toLogin();
//   }
// });

// 页面显示时

onShow(() => {
  console.log('onShow')
  if (appStore.isLogin) {
    loadend.value = false;
    page.value = 1;
    orderList.value = [];
    getOrderData();
    getOrderListFn();
  } else {
    toLogin();
  }
});
onLoad((options)=>{
  if (appStore.isLogin) {
    if(options.status  && options.status!= 5){
      statusClick(options.status)
    }else if(options.status  && options.status == 5){
      toReturnList()
    }
  } else {
    toLogin();
  }
})

// 下拉加载
onReachBottom(() => {
  getOrderListFn();
});

function onChangeFun(state) {
  let action = state.action || null;
  let value = state.value !== undefined ? state.value : null;
  if (action && typeof [action] === "function") {
    [action](value);
  }
}
function getOrderData() {
  orderData().then((res) => {
    orderDataState.value = res.data;
  });
}
function cancelOrder(index, order_id) {
  if (!order_id) return Toast({ title: "缺少订单号无法取消订单" });
  uni.showLoading({ title: "正在删除中" });
  orderCancel(order_id)
    .then((res) => {
      uni.hideLoading();
      Toast({ title: "删除成功", icon: "success" }, () => {
        orderList.value.splice(index, 1);
        orderDataState.value.unpaid_count--;
        getOrderData();
      });
    })
    .catch((err) => {
      Toast({ title: err });
    });
}

function goPay(pay_price, order_id) {
  appStore.USERINFO().then((res) => {
    if (res.nowMoney) {
      showPopup.value = true;
      pay_order_id.value = order_id;
      totalPrice.value = pay_price;
    }
  });
}
const closePayPopup = () => {
  console.log("payClose");
  showPopup.value = false;
};
function payComplete() {
  console.log("payComplete");
  loadend.value = false;
  page.value = 1;
  orderList.value = [];
  showPopup.value = false;
  getOrderData();
  getOrderListFn();
}
function payFail() {
  showPopup.value = false;
}
function goOrderDetails(order_id) {
  if (!order_id) return Toast({ title: "缺少订单号无法查看订单详情" });
  uni.navigateTo({ url: "/pages/order_details/index?order_id=" + order_id });
}

function toReturnList() {
  uni.navigateTo({ url: "/pages/users/user_return_list/index" });
}
function statusClick(status) {
  if (status === orderStatus.value) return;
  orderStatus.value = status;
  loadend.value = false;
  page.value = 1;
  orderList.value = [];
  getOrderListFn();
}
function getOrderListFn() {
  if (loadend.value || loading.value) return;
  loading.value = true;
  loadTitle.value = "加载更多";
  getOrderList({
    type: orderStatus.value,
    page: page.value,
    limit: limit.value,
    mallType: 0,
  })
    .then((res) => {
      let list = res.data.list || [];
      let isLoadend = list.length < limit.value;
      // orderList.value = uni.$util.SplitArray(list, orderList.value)
      orderList.value = [...list, ...orderList.value];
      loadend.value = isLoadend;
      loading.value = false;
      loadTitle.value = isLoadend ? "我也是有底线的" : "加载更多";
      page.value += 1;
    })
    .catch(() => {
      loading.value = false;
      loadTitle.value = "加载更多";
    });
}
function delOrder(order_id, index) {
  orderDel(order_id)
    .then((res) => {
      orderList.value.splice(index, 1);
      orderDataState.value.unpaid_count--;
      getOrderData();
      Toast({ title: "删除成功", icon: "success" });
    })
    .catch((err) => {
      Toast({ title: err });
    });
}
</script>

<style scoped lang="scss">
.my-order {
  .header {
    height: 250rpx;
    padding: 0 30rpx;
    background-color: $header-color;

    .picTxt {
      height: 190rpx;

      .text {
        color: #000;
        font-size: 26rpx;
        font-family: "Guildford Pro";

        .name {
          font-size: 34rpx;
          font-weight: bold;
          color: #000;
          margin-bottom: 20rpx;
        }

        .consumer-order {
          margin-right: 30rpx;
        }
      }

      .pictrue {
        width: 122rpx;
        height: 109rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .nav {
    background-color: #fff;
    width: 690rpx;
    height: 140rpx;
    border-radius: 14rpx;
    margin: -60rpx auto 0 auto;

    .item {
      text-align: center;
      font-size: 26rpx;
      color: #282828;
      padding: 26rpx 0;

      &.on {
        font-weight: bold;
        border-bottom: 5rpx solid $border-color;
      }

      .num {
        margin-top: 18rpx;
      }
    }
  }

  .list {
    width: 690rpx;
    margin: 14rpx auto 0 auto;
  }
}

.noCart {
  margin-top: 171rpx;
  padding-top: 0.1rpx;

  .pictrue {
    width: 414rpx;
    height: 336rpx;
    margin: 78rpx auto 56rpx auto;

    image {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
