<template>
	<view>
		<view class="header-buts flex flex-center">
			<view class="flex buts-box">
				<view class="buts" :class="{'buts-active':activeIndex===1}" @click="handleClickTab(1)">总订单</view>
				<view class="buts" :class="{'buts-active':activeIndex===2}" @click="handleClickTab(2)">日订单</view>
			</view>
		</view>

		<up-sticky bgColor="#fff" v-if="activeIndex == 1">
			<view class="container-tabs">
				<up-tabs @click="handleClassifyClickTab" :list="tabList1" lineWidth="68rpx" :activeStyle="{
					color: '#FFFFFF',
					fontWeight: 'bold',
					transform: 'scale(1.05)'
				}" :inactiveStyle="{
					color: '#FFFFFF',
					transform: 'scale(1)'
				}" :itemStyle="{height:'88rpx',width : '33%'}" 
				
				lineColor="#FFFFFF"></up-tabs>
			</view>
		</up-sticky>

		<up-sticky bgColor="#fff" v-else>
			<view class="container-tabs">
				<up-tabs :list="tabList2" lineWidth="68rpx" :activeStyle="{
					color: '#FFFFFF',
					fontWeight: 'bold',
					transform: 'scale(1.05)'
				}" :inactiveStyle="{
					color: '#FFFFFF',
					transform: 'scale(1)'
				}" :itemStyle="{height:'88rpx',padding:'0 52rpx', width : '400rpx'}" 
				@click="handleClassifyClickTab"
				lineColor="#FFFFFF"></up-tabs>
			</view>
		</up-sticky>

		<view class="container">
			<!-- 未登录提示 -->
			<view v-if="!isLogin" class="login-tip-container">
				<view class="login-tip-content">
					<up-image class="login-image" width="120rpx" height="120rpx" 
						src="https://image.hhlm1688.com/img/work/log/headImage.png" shape="circle"></up-image>
					<view class="login-tip">请先登录查看订单数据</view>
					<up-button @click="goToLogin" type="primary" text="立即登录" 
						shape="circle" color="#FFBF60" class="login-btn"></up-button>
				</view>
			</view>
			
			<!-- 已登录但加载中状态 -->
			<view v-else-if="loading" class="loading-container">
				<up-loading-icon size="36" mode="circle" color="#FFAA48"></up-loading-icon>
				<text class="loading-text">加载中...</text>
			</view>
			
			<!-- 总订单内容 -->
			<systemOrder :list="list" :current="current" v-else-if="activeIndex == 1" />
			
			<!-- 日订单内容 -->
            <view v-else>
                <view v-if="dateOrderList && dateOrderList.length > 0">
                    <timelineService 
                    v-for="(item,index) in dateOrderList"
                    :key="index"
                    :date="item.date"
                    :status="current == 0"
                    :list="item.list"
                    :current="current"
                    />
                </view>
                <view v-else class="empty-state">
                    <image src="/static/images/ydd/empty.png" mode="aspectFit" class="empty-image"></image>
                    <text class="empty-text">暂无订单数据</text>
                </view>
            </view>
		</view>

		<!-- 客服组件 -->
		<CustomerService />
	</view>
</template>

<script setup>
	import {
		computed,
		reactive,
		ref
	} from "vue";
	import systemOrder from "./components/systemOrder.vue";
	import orderListByData from "./components/orderListByData.vue";
	import timelineService from "./components/timelineService.vue";
	import {
		onShow,
        onLoad,
	} from "@dcloudio/uni-app"
	import {
		getLoginStatus
	} from "@/utils/useMixin.js"
	import {
		getIsLogin,
		getToken
	} from "@/utils/auth";
	import {
		myList
	} from "@/api/receivingHall/index.js"
	import {
		getOrderDateList,
	} from "@/api/order/order.js"
	import {
		appletOrderDateFrequencyList,
	} from "@/api/order/frequency.js"
	import {
		useStore
	} from "vuex"
    import { getOrderServiceText, getProductNameText } from '@/utils/serviceTime.js'

    onLoad(() => {
        requestId.value = 0;
        activeIndex.value = 1;
    })

	onShow(() => {
		checkLoginStatus();
		if (isLogin.value) {
			getList();
		}
	})

	const current = ref(0)
	const activeIndex = ref(1)
	const list = ref([])
	const dateOrderList = ref([])
	const loading = ref(false) // 添加loading状态
	const requestId = ref(0) // 添加请求序列号
	const isLogin = ref(false) // 添加登录状态
	const store = useStore();

	const userInfo = computed(() => {
		return store.getters.userInfo;
	})

	const tabList1 = reactive([{
			name: '待服务',
			badge: {
				value: 0,
			}
		},
		{
			name: '进行中',
			badge: {
				value: 0,
			}
		},
		{
			name: '已完成',
			badge: {
				value: 0,
			}
		},
	])

	const tabList2 = reactive([{
			name: '待上门',
			badge: {
				value: 0,
			}
		},
		{
			name: '已完成',
			badge: {
				value: 0,
			}
		},
	])

	// 检查登录状态
	const checkLoginStatus = () => {
		if (getIsLogin() && getToken()) {
			isLogin.value = true
		} else {
			isLogin.value = false
		}
	}

	// 跳转登录页面
	const goToLogin = () => {
		uni.navigateTo({
			url: "/pages/login/index"
		})
	}

	// 检查登录状态，未登录则跳转登录
	const checkLoginAndRedirect = () => {
		if (!isLogin.value) {
			goToLogin()
			return false
		}
		return true
	}

	function getList() {
		if (!isLogin.value) return;
		
		loading.value = true; // 开始加载
		requestId.value++; // 递增请求序列号
		const currentRequestId = requestId.value; // 保存当前请求的ID

        let index = current.value;

		if (activeIndex.value == 1) {
			myList({
                orderStatus: index,
                userId: userInfo.value.userId
            })
            .then(res => {
                // 检查请求是否是最新的
                if (currentRequestId !== requestId.value) {
                    return; // 如果不是最新请求，忽略响应
                }
                
                if (res.code == 200) {
                    list.value = res.data.rows
                    
                    tabList1[index].badge.value = res.data.total
                    
                    list.value.forEach(item => {
                        item.h5OrderVO.petVOList.forEach(pet => {
                            pet.orderServiceText = getOrderServiceText(pet.id, item.h5OrderVO.orderServiceList)
                            pet.productNameText = getProductNameText(pet.id, item.h5OrderVO.orderItemList, item.h5OrderVO.orderServiceList)
                        })
                    })
                }
            })
            .finally(() => {
                // 只有最新请求才能关闭loading
                if(activeIndex.value == 1 && currentRequestId === requestId.value){
                    loading.value = false; // 结束加载
                }
            })
		}else{
            dateOrderList.value = []
			
			appletOrderDateFrequencyList({
                status: index == 0 ? '0,1' : '2',
                masterId: userInfo.value.userId
			})
            .then(res => {
                // 检查请求是否是最新的
                if (currentRequestId !== requestId.value) {
                    return; // 如果不是最新请求，忽略响应
                }
                
                if (res.code == 200) {
                    dateOrderList.value = res.data
                    // 更新标签数量显示
                    let totalOrders = 0;
                    dateOrderList.value.forEach(item => {
                        totalOrders += item.list.length || 0;
						
						item.list.forEach(n => {
							n.pets.forEach(pet => {
								pet.orderItemList.reverse()
							})
						})
						
                    });
                    tabList2[index].badge.value = totalOrders;
                }
            })
            .finally(() => {
                // 只有最新请求才能关闭loading
                if(activeIndex.value == 2 && currentRequestId === requestId.value){
                    loading.value = false; // 结束加载
                }
            })
        }
	}

    function handleClickTab(index) {
        current.value = 0;
        activeIndex.value = index;
        if (checkLoginAndRedirect()) {
			getList();
		}
    }

	const handleClassifyClickTab = (item) => {
		current.value = item.index;
		if (checkLoginAndRedirect()) {
			getList();
		}
	}
</script>

<style scoped lang="scss">
	@import "index.scss";
	
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40rpx;
		
		.loading-text {
			margin-top: 20rpx;
			color: #999;
			font-size: 28rpx;
		}
	}
	
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 80rpx 40rpx;
		
		.empty-image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 20rpx;
		}
		
		.empty-text {
			color: #999;
			font-size: 28rpx;
		}
	}
	
	.login-tip-container {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 80rpx 40rpx;
		
		.login-tip-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 60rpx;
			border-radius: 20rpx;
			
			.login-image {
				margin-bottom: 30rpx;
			}
			
			.login-tip {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 30rpx;
			}
			
			.login-btn {
				width: 240rpx;
			}
		}
	}
</style>