<template>
	<view class="list-filter">
		<scroll-view scroll-x>
			<view class="list-filter-tabs">
				<!-- 一级tabs：添加点击事件和动态active类 -->
				<view v-for="(item, index) in firstTabs" :key="index" class="list-filter-tabs-item"
					:class="{ active: activeFirstId === item.id }" @click="handleFirstTabClick(item)">
					{{ item.title }}
				</view>
			</view>
		</scroll-view>
		<view class="list-filter-tabs2">
			<!-- 二级tabs-数据项：添加点击事件和动态active类 -->
			<view v-for="(item, index) in secondTabs" :key="index" class="list-filter-tabs2-item"
				:class="{ active: activeSecondId === item.id }" @click="handleSecondTabClick(item.id, item.title)">
				{{ item.title }}
			</view>
		</view>
		<CommonList ref="groupRef" :isLogin="isLogin" :apiUrl="apiUrl" :listScrollHeight="`calc(100vh - ${426}rpx)`"
			@load-success="loadSuccess">
			<template #listData="{ list }">
				<view v-for="item in popList">
					<!-- <orderCardManHours v-if="activeFirstId == 4 && order.first_class_title" :dataItem="order"
						@cancel="cancelOrder($event, order)" @accept="confirmOrder($event, order)"
						@start="startOrder($event, order)" @done="endOrder($event, order)"
						@goOrderDetail="goOrderDetail"></orderCardManHours>
					<orderCardList v-else :dataItem="order" :typeId="1" @cancel="cancelOrder($event, order)"
						@accept="confirmOrder($event, order)" @start="startOrder($event, order)"
						@done="endOrder($event, order)" @goOrderDetail="goOrderDetail" /> -->

					<OrderCard v-if="activeFirstId != 3" :haveButton="haveButton" :showState="false" :dataItem="item"
						:typeId="activeFirstId" @cancel="cancelOrder($event, item)" @start="startOrder($event, item)"
						@done="endOrder($event, item)" @goOrderDetail="goOrderDetail" />
					<WorkHourOrderCard v-else :showState="false" :dataItem="item" :typeId="activeFirstId"
						@cancel="cancelOrder($event, item)" @accept="confirmOrder($event, item)"
						@start="startOrder($event, item)" @done="endOrder($event, item)" @goOrderDetail="goOrderDetail">
					</WorkHourOrderCard>
				</view>
			</template>

			<!-- 空数据状态 -->
			<template #empty>
				<view class="noDataBox">

					<noData tipText="暂无服务订单哟～" v-if="isLogin"></noData>
					<noLogin v-else></noLogin>
				</view>
			</template>
		</CommonList>
		<serviceCodeInput :show="showInput" @close="showInput = false" @confirm="onConfirm" />
	</view>
</template>

<script>
	import OrderCard from "./orderCard2.vue";
	import WorkHourOrderCard from "./workOrderCard.vue";
	import CommonList from "@/components/common/CommonList.vue";
	import noLogin from "@/components/noData/noLogin.vue";
	import request from "@/utils/request";
	import serviceCodeInput from "@/components/service-code-input/service-code-input.vue";
	export default {
		name: "filters",
		props: {
			title: {
				type: String,
				default: "",
			},
			userInfo: {
				type: Object,
				default: () => ({}),
			},
			isLogin: {
				type: Boolean,
				default: false,
			},
			// 自营状态 0未加入 1加入 2停用
			selfState: {
				type: Number,
				default: 0,
			},
		},
		components: {
			CommonList,
			noLogin,
			serviceCodeInput,
			OrderCard,
			WorkHourOrderCard,
		},
		data() {
			return {
				popList:[],
				haveButton: true,
				statusBarHeight: 0,
				tabs: [{
						title: "到店订单",
						id: 1
					},
					{
						title: "自营到店订单",
						id: 2,
						isNeedLogin: true,
						isRuzHu: true,
						isSelfOrder: true
					},
					{
						title: "工位订单",
						id: 3,
						isNeedLogin: true,
						id_type: 1
					},
					{
						title: "上门订单",
						id: 4,
						isNeedLogin: true,
						id_type: 1
					},
					{
						title: "自营上门订单",
						id: 5,
						isNeedLogin: true,
						id_type: 1
					},
				], // 1级类目
				activeFirstId: 1, // 记录选中的1级tab id
				activeSecondId: 3, // 记录选中的2级tab id（null表示"全部"）
				numInfo: {
					djd: 0,
					dfw: 0,
					dwc: 0,
					nocompletednum: 0,
					noconfirmnum: 0,
					noservernum: 0,
				},
				sjId: undefined,
				idType: undefined,
				showInput: false,
				orderInfo: {},
				urls: {
					1: {
						weChatRefund: "/sj/yhwechatrefund",
						aliRefund: "/sj/yhalirefund",
						startOrder: "/sj/startserver",
						endOrder: "/sj/endserver",
						ordernum: "/sj/ordernum",
						list: "/sj/sjgetyhorder",
					},
					2: {
						weChatRefund: "/sj/orderSelf/weChatRefund",
						aliRefund: "/sj/orderSelf/aliRefund",
						startOrder: "/sj/orderSelf/start",
						endOrder: "/sj/orderSelf/end",
						ordernum: "/sj/orderSelf/orderNum",
						list: "/sj/orderSelf/list",
					},
					3: {
						weChatRefund: "/sj/workSeatOrder/weChatRefund",
						aliRefund: "/sj/workSeatOrder/aliRefund",
						startOrder: "/sj/workSeatOrder/start",
						sureOrder:"/sj/workSeatOrder/sure",
						endOrder: "/sj/workSeatOrder/end",
						ordernum: "/sj/workSeatOrder/orderNum",
						list: "/sj/workSeatOrder/list",
					},
					4: {
						ordernum: "/sj/sjonsiteordernum",
						list: "/sj/sjonsiteorder",
					},
					5: {
						ordernum: "/sj/sjonsiteordernumself",
						list: "/sj/sjonsiteorderself",
					}
				},
			};
		},
		computed: {
			apiUrl() {
				if(!this.urls[this.activeFirstId]){
					return ""
				} 
				const urls = this.urls[this.activeFirstId];
				return urls.list;
			},
			getNumUrl() {
				const urls = this.urls[this.activeFirstId];
				return urls.ordernum;
			},
			// 计算是否显示自营订单tab
			showSelfOrderTab() {
				// 只有当self_state为1或2时才显示自营订单tab
				return this.selfState == 1 || this.selfState == 2;
			},
			firstTabs() {
				return this.tabs
					.filter((tab) => !tab.isNeedLogin || this.isLogin)
					.filter((tab) => {
						if (tab.id_type) {
							return this.idType == tab.id_type;
						}
						return true;
					})
					.filter((tab) => !tab.isRuzHu || this.idType != 0)
					// 自营订单tab显示条件
					.filter((tab) => {
						if (tab.isSelfOrder) {
							return this.showSelfOrderTab;
						}
						return true;
					});
			},
			secondTabs() {
				if (this.activeFirstId == 1 || this.activeFirstId == 2) {
					return [{
							title: `待开始(${this.numInfo.noservernum})`,
							id: 3
						},
						{
							title: `待完成(${this.numInfo.nocompletednum})`,
							id: 4
						},
					];
				} else if (this.activeFirstId == 4 || this.activeFirstId == 5) {
					return [{
							title: `待接单(${this.numInfo.noconfirmnum})`,
							id: 2
						},
						{
							title: `待开始(${this.numInfo.noservernum})`,
							id: 3
						},
						{
							title: `待完成(${this.numInfo.nocompletednum})`,
							id: 4
						},
					];
				} else {
					return [{
							title: `待接单(${this.numInfo.djd})`,
							id: 2
						},
						{
							title: `待服务(${this.numInfo.dfw})`,
							id: 3
						},
						{
							title: `待完成(${this.numInfo.dwc})`,
							id: 4
						},
					];
				}

			},
		},
		mounted() {
			this.statusBarHeight = this.getRpxStatusBarHeight();
			if (this.isLogin) {
				this.activeFirstId = 1;
				this.activeSecondId = 3; // 默认选中"待接单"
				this.searchList();
			} else {
				this.activeFirstId = null;
				this.activeSecondId = null; // 默认选中"待接单"
			}
		},
		watch: {
			isLogin(newVal) {
				if (newVal) {
					this.activeFirstId = 1;
					this.activeSecondId = 2; // 默认选中"待接单"
					this.searchList();
				}
			},
		},
		methods: {
			searchList() {
				if (this.syrId && this.idType) {
					this.$refs.groupRef.manualRefresh({
						sjid: this.sjId,
						state: this.activeSecondId || undefined,

					});
				} else {
					request.post("/sj/user/getUser").then((result) => {
						this.sjId = result.data.id;
						this.idType = result.data.id_type;
						this.$refs.groupRef.manualRefresh({
							sjid: this.sjId,
							state: this.activeSecondId,
						});
					});
				}
			},
			loadSuccess(res) {
				
				this.popList = res.list
				request
					.post(this.getNumUrl, {
						sjid: this.sjId,
					})
					.then((result) => {
						for (let key in result.data) {
							this.numInfo[key] = result.data[key];
						}

					});
			},
			// 一级tab点击事件
			handleFirstTabClick(item) {
				this.popList = []
				if (!this.isLogin) return;
				// 避免重复点击
				if (this.activeFirstId === item.id) return;
				// 更新1级选中状态
				this.activeFirstId = item.id;

				this.haveButton = true
				if (this.activeFirstId == 4 || this.activeFirstId == 5) {
					this.haveButton = false
				}

				// 重置2级选中状态（默认选中"全部"）
				if (this.activeFirstId == 1 || this.activeFirstId == 2) {
					this.activeSecondId = 3;
				} else {
					this.activeSecondId = 2;
				}

				// 传递给父组件（1级选中数据）
				this.$emit("tabChange", {
					firstId: this.activeFirstId,
					secondId: this.activeSecondId,
				});
				this.$nextTick(() => {
					this.searchList();
				});
			},
			// 二级tab点击事件
			handleSecondTabClick(id, title) {
				this.popList = []
				if (!this.isLogin) return;
				if (this.activeSecondId === id) return;
				// 更新2级选中状态
				this.activeSecondId = id;
				// 传递给父组件（2级选中数据）
				this.$emit("tabChange", {
					firstId: this.activeFirstId,
					secondId: this.activeSecondId,
				});
				this.$nextTick(() => {
					this.searchList();
				});
			},
			cancelOrder(e, order) {
				uni.showModal({
					title: "取消订单",
					content: "确定要取消该订单吗？（订单取消后，支付金额将原路退回）",
					success: (res) => {
						if (res.confirm) {
							// TODO: 取消订单
							let data = {
								orderNo: order.number,
								amount: order.pay_money,
								syrid: this.syrId,
							};
							let url = "";
							if (order.pay_kind == 1) {
								url = "";
							} else if (order.pay_kind == 2) {
								url = this.urls[this.activeFirstId].weChatRefund;
							} else if (order.pay_kind == 3) {
								url = this.urls[this.activeFirstId].aliRefund;
							}
							console.log(data, url);
							if (this.clickType) {
								return;
							}
							this.clickType = true;
							request
								.post(url, data)
								.then((res) => {
									if (res.state == 1 || res.code == 200 || res.code == 1) {
										uni.showToast({
											title: "取消成功！",
											icon: "none",
										});
										this.searchList();
									} else {
										uni.showToast({
											title: res.msg,
											icon: "none",
										});
									}
								})
								.catch((err) => {
									console.log(err);
								})
								.finally(() => {
									this.clickType = false;
								});
						}
					},
				});
			},
			// 确认接单
			confirmOrder(e, order) {
				if (this.clickType) {
					return;
				}
				this.clickType = true;
				console.log(111,this.activeFirstId,this.urls)
				request
					.post(this.urls[this.activeFirstId].sureOrder, {
						id: order.id,
						syrid: this.syrId,
						order_kind: this.idType == 2 ? 3 : 1,
					})
					.then((res) => {
						if (res.state != 1 || res.code != 200) {
							uni.showToast({
								title: "开始服务",
								icon: "none",
							});
						} else {
							uni.showToast({
								title: "已接单",
								icon: "none",
							});
						}
						this.searchList();
					})
					.finally(() => {
						this.clickType = false;
					});
			},
			// 开始服务
			startOrder(e, order) {
				if (order.team_buy_order_state == 1) {
					uni.showToast({
						title: "订单当前处于拼团中，服务将在拼团完成后才开启~",
						icon: "none",
					});
					return
				}
				this.showInput = true;
				this.orderInfo = order;
			},
			// 输入完成
			onConfirm(code) {
				this.showInput = false;
				if (this.clickType) {
					return;
				}
				this.clickType = true;
				console.log(this.orderInfo, "this.urls[this.activeFirstId].startOrder");
				request
					.post(this.urls[this.activeFirstId].startOrder, {
						id: this.orderInfo.id,
						server_code: code,
						sjid: this.sjId,
					})
					.then((res) => {
						console.log(res);
						if (res.state == 1 || res.code == 200) {
							uni.showToast({
								title: "开始服务",
								icon: "none",
							});
							this.searchList();
						} else {
							uni.showToast({
								title: res.msg,
								icon: "none",
							});
						}
						this.orderInfo = {};
					})
					.finally(() => {
						this.clickType = false;
					});
			},
			// 完成服务
			endOrder(e, order) {
				// app阻止事件冒泡
				// #ifdef APP-PLUS
				// e.preventDefault();
				// e.stopPropagation();
				// #endif
				if (this.clickType) {
					return;
				}
				this.clickType = true;
				request
					.post(this.urls[this.activeFirstId].endOrder, {
						id: order.id,
						sjid: this.sjId,
					})
					.then((res) => {
						if (res.state == 1 || res.code == 200) {
							uni.showToast({
								title: res.msg,
								icon: "none",
							});
							this.searchList();
						} else {
							uni.showToast({
								title: res.msg,
								icon: "none",
							});
						}
					})
					.finally(() => {
						this.clickType = false;
					});
			},
			goOrderDetail(order) {
				if (this.idType == 1) {
					if (this.activeFirstId == 1) {
						uni.navigateTo({
							url:  `/pages/shop/userorder-detail?order_id=${order.id}&order_kind=${order.order_kind}&haveButton=${this.haveButton}`,
						});
					}
					if (this.activeFirstId == 2) {
						uni.navigateTo({
							url: `/pages/shop/userorder-detail?order_id=${order.id}&serviceType=2&haveButton=${this.haveButton}`,
						});
					}
					if (this.activeFirstId == 3) {
						uni.navigateTo({
							url: `/pages/shop/SellerDetail?order_id=${order.id}&haveButton=${this.haveButton}`,
						});
					}
					if (this.activeFirstId == 4) {
						uni.navigateTo({
							url: `/pages/shop/userorder-detail?order_id=${order.id}&order_kind=${order.order_kind}&haveButton=${this.haveButton}`,
						});
					}
					if (this.activeFirstId == 5) {
						uni.navigateTo({
							url: `/pages/shop/userorder-detail?order_id=${order.id}&order_kind=${order.order_kind}&serviceType=2&haveButton=${this.haveButton}`,
						});
					}
				}
			},
		},
	};
</script>

<style scoped lang="less">
	.list-filter {
		background: #ffffff;
		border-radius: 20rpx 20rpx 0rpx 0rpx;

		.list-filter-tabs {
			display: flex;
			gap: 50rpx;
			padding-left: 30rpx;
			padding-top: 30rpx;
			// 给一级tabs容器添加底部内边距，避免横条被遮挡
			padding-bottom: 12rpx;

			.list-filter-tabs-item {
				// 关键：设置为inline-block，让宽度跟随文字，横条宽度与文字一致
				display: inline-block;
				// 相对定位，用于横条的绝对定位参考
				position: relative;

				font-weight: 500;
				font-size: 30rpx;
				color: #333333;
				line-height: 42rpx;
				text-align: left;
				font-style: normal;
				white-space: nowrap;

				// 点击反馈
				&:active {
					opacity: 0.8;
				}

				// 选中状态样式
				&.active {
					color: #e8101e; // 选中文字颜色
					font-weight: 600; // 选中时加粗（可选，根据图片效果）

					// 横条效果：通过伪元素实现
					&::after {
						content: "";
						// 绝对定位在元素底部
						position: absolute;
						width: 34rpx;
						left: 50%;
						transform: translateX(-50%);
						bottom: -6rpx; // 距离文字底部的距离（可调整）
						height: 6rpx; // 横条高度
						background: linear-gradient(306deg,
								#e8101e 0%,
								#e8101e 100%); // 横条颜色（与文字颜色一致）
						border-radius: 3rpx; // 横条圆角（可选，更柔和）
					}
				}
			}
		}

		.list-filter-tabs2 {
			display: flex;
			flex-wrap: wrap;
			gap: 40rpx;
			padding: 24rpx 20rpx;

			.list-filter-tabs2-item {
				width: 168rpx;
				height: 56rpx;
				background: #f0f0f0;
				border-radius: 6rpx;
				font-weight: 400;
				font-size: 26rpx;
				color: #666666;
				text-align: center;
				font-style: normal;
				display: flex;
				align-items: center;
				justify-content: center;
				white-space: nowrap;

				// 点击反馈
				&:active {
					opacity: 0.8;
				}

				// 选中状态样式
				&.active {
					color: #e8101e; // 选中颜色
					background: rgba(252, 67, 124, 0.1); // 可选：选中时背景色变化
					font-weight: 600; // 可选：选中时加粗
				}
			}
		}
	}

	.noDataBox {
		background-color: #ffffff;
		height: 100%;
		margin: 0rpx;
		border-radius: 20rpx;
		//   padding-bottom: 314rpx;
	}

	.common-list {
		background: #f5f5f5;
		padding-bottom: 0;

	}

	::v-deep .list-scroll {
		margin-top: 0 !important;
		padding: 20rpx;
		box-sizing: border-box;
	}
	
	.order-card{
		margin: 0rpx 0rpx 20rpx 0rpx;
	}
</style>