<template>
	<view>
		<view class="my-order">
			<view class="nav">
				<up-tabs :scrollable="false" lineColor="#F8C008" :activeStyle="{color:'#F8C008',fontSize:'28rpx'}"
					:inactiveStyle="{color:'#333333',fontSize:'28rpx'}" :list="list" @click="statusClick"
					:current="oldOrderStatus"></up-tabs>
			</view>
			<view class="list" v-if="orderList.length">
				<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 class="empty" v-if="orderList.length == 0">
				<uni-empty-view />
			</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 {
    onLoad,
		onShow,
		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 oldOrderStatus = 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");

	const list = ref([{
			name: '待付款',
			orderStatus: 0,
      value: 0
		},
		{
			name: '待发货',
			orderStatus: 1,
      value: 1
		},
		{
			name: '待收货',
			orderStatus: 2,
      value: 2
		},
    {
      name: '退款/换货',
      orderStatus: -3,
      value: 3
    },
		{
			name: '已完成',
			orderStatus: 4,
      value: 4
		},

	]) //头部导航

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

	// 页面显示时
	onShow(() => {
		if (appStore.isLogin) {
			loadend.value = false;
			page.value = 1;
			orderList.value = [];
			getOrderData();
			getOrderListFn();
		} else {
			toLogin();
		}
	});
  onLoad((options) => {
    if (options.status) {
      const statusValue = parseInt(options.status);

      // 验证状态是否有效
      const validStatuses = [0, 1, 2, 4, -3];
      if (validStatuses.includes(statusValue)) {
        // 设置状态
        orderStatus.value = statusValue;
        // 找到对应的索引
        const index = list.value.findIndex(item => item.orderStatus === statusValue);
        if (index !== -1) {
          oldOrderStatus.value = index;  // 设置索引值
        }

        console.log("设置订单状态为:", statusValue, "索引为:", index);
      } else {
        console.warn("无效的状态参数:", statusValue);
      }
    }
  })
	// 下拉加载
	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"
		});
	}

	const changeStatus = (item) => {
		// oldOrderStatus.value = item.index;
	}

	function statusClick(item) {
    console.log(item)
		if (item.orderStatus === orderStatus.value) return;
		
		orderStatus.value = item.orderStatus;
		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>
	page {
		background: #F9F7F0;
	}
</style>
<style scoped lang="scss">
	.empty {
		height: calc(100vh - 44px);
		/* #ifdef H5 */
		height: calc(100vh - 88px);
		/* #endif */
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.my-order {

		.nav {
			background: #FFFFFF;

			// height: 140rpx;
			background-color: #fff;

			.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: 16rpx 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>