<template>
	<view>
		<uni-nav-bar fixed="true" statusBar="true" title="工作台" right-icon="scan"
			@clickRight="HandlScanCode"></uni-nav-bar>
		<!-- 顶部横向导航 -->
		<view class="top-nav-wrapper" v-if="moduleNavList.length > 0">
			<scroll-view class="top-nav" scroll-x enable-flex :scroll-into-view="scrollIntoViewId" scroll-with-animation
				@scroll="handleNavScroll">
				<view class="nav-tab" v-for="(item, index) in moduleNavList" :key="index" :id="'nav-' + item.id"
					:class="{ active: currentNavIndex === index }" @click="goToModule(item, index)">
					{{ item.name }}
				</view>
			</scroll-view>
		</view>
		<view class="content-wrapper">
			<view v-if="internalManagementList.length > 0" :id="'module-xietong'" :data-index="0">
				<CellTip title="协同办公"></CellTip>
				<view class="nav">
					<view class="nav-content">
						<view class="nav-item" v-for="(item, index) in internalManagementList"
							@click="toNav(item.path)">
							<span :class="'iconfont ' + item.icon"></span>
							<i class="badge" v-if="item.badge">{{ item.badge }}</i>
							<label>{{ item.name }}</label>
						</view>
					</view>
				</view>
			</view>
			<view v-if="productionList.length > 0" :id="'module-shengchan'" :data-index="1">
				<CellTip title="生产管理"></CellTip>
				<view class="nav">
					<view class="nav-content">
						<view class="nav-item" v-for="item in productionList" :key="item.link_url"
							@click="toNav(item.path)">
							<span :class="'iconfont ' + item.icon"></span>
							<label>{{ item.title }}</label>
							<label>{{ item.num }}</label>
						</view>
					</view>
				</view>
			</view>
			<view v-if="operationsList.length > 0" :id="'module-yunwei'" :data-index="2">
				<CellTip title="运维管理"></CellTip>
				<view class="nav">
					<view class="nav-content">
						<view class="nav-item" v-for="(item, index) in operationsList" @click="toNav(item.path)">
							<span :class="'iconfont ' + item.icon"></span>
							<i class="badge" v-if="item.badge">{{ item.badge }}</i>
							<label>{{ item.name }}</label>
						</view>
					</view>
				</view>
			</view>
			<view v-if="serviceList.length > 0" :id="'module-shouhou'" :data-index="3">
				<CellTip title="售后服务管理"></CellTip>
				<view class="nav">
					<view class="nav-content">
						<view class="nav-item" v-for="(item, index) in serviceList" @click="toNav(item.path)">
							<span :class="'iconfont ' + item.icon"></span>
							<i class="badge" v-if="item.badge">{{ item.badge }}</i>
							<label>{{ item.name }}</label>
						</view>
					</view>
				</view>
			</view>
			<view v-if="warehousingList.length > 0" :id="'module-cangchu'" :data-index="4">
				<CellTip title="仓储管理"></CellTip>
				<view class="nav">
					<view class="nav-content">
						<view class="nav-item" v-for="(item, index) in warehousingList" @click="toNav(item.path)">
							<span :class="'iconfont ' + item.icon"></span>
							<label>{{ item.title }}</label>
						</view>
					</view>
				</view>
			</view>
			<view v-if="dispatchList.length > 0" :id="'module-yunshu'" :data-index="5">
				<CellTip title="运输管理"></CellTip>
				<view class="nav">
					<view class="nav-content">
						<view class="nav-item" v-for="(item, index) in dispatchList" @click="toNav(item.path)">
							<span :class="'iconfont ' + item.icon"></span>
							<i class="badge" v-if="item.badge">{{ item.badge }}</i>
							<label>{{ item.name }}</label>
						</view>
					</view>
				</view>
			</view>
			<view v-if="saleManageList.length > 0" :id="'module-yingxiao'" :data-index="6">
				<CellTip title="营销管理"></CellTip>
				<view class="nav">
					<view class="nav-content">
						<view class="nav-item" v-for="(item, index) in saleManageList" @click="toNav(item.path)">
							<span :class="'iconfont ' + item.icon"></span>
							<i class="badge" v-if="item.badge">{{ item.badge }}</i>
							<label>{{ item.name }}</label>
						</view>
					</view>
				</view>
			</view>
			<view v-if="purchaseManageList.length > 0" :id="'module-caigou'" :data-index="7">
				<CellTip title="采购管理"></CellTip>
				<view class="nav">
					<view class="nav-content">
						<view class="nav-item" v-for="(item, index) in purchaseManageList" @click="toNav(item.path)">
							<span :class="'iconfont ' + item.icon"></span>
							<i class="badge" v-if="item.badge">{{ item.badge }}</i>
							<label>{{ item.name }}</label>
						</view>
					</view>
				</view>
			</view>
			<view v-if="pcsList.length > 0" :id="'module-shengchanguanli'" :data-index="8">
				<CellTip title="生产管控"></CellTip>
				<view class="nav">
					<view class="nav-content">
						<view class="nav-item" v-for="(item, index) in pcsList" @click="toNav(item.path)">
							<span :class="'iconfont ' + item.icon"></span>
							<i class="badge" v-if="item.badge">{{ item.badge }}</i>
							<label>{{ item.name }}</label>
						</view>
					</view>
				</view>
			</view>
			<view v-if="qmsList.length > 0" :id="'module-zhiliang'" :data-index="9">
				<CellTip title="质量管理"></CellTip>
				<view class="nav">
					<view class="nav-content">
						<view class="nav-item" v-for="(item, index) in qmsList" @click="toNav(item.path)">
							<span :class="'iconfont ' + item.icon"></span>
							<i class="badge" v-if="item.badge">{{ item.badge }}</i>
							<label>{{ item.name }}</label>
						</view>
					</view>
				</view>
			</view>
			<view v-if="energyManagement.length > 0" :id="'module-nengyuan'" :data-index="10">
				<CellTip title="能源管理"></CellTip>
				<view class="nav">
					<view class="nav-content">
						<view class="nav-item" v-for="(item, index) in energyManagement" @click="toNav(item.path)">
							<span :class="'iconfont ' + item.icon"></span>
							<i class="badge" v-if="item.badge">{{ item.badge }}</i>
							<label>{{ item.name }}</label>
						</view>
					</view>
				</view>
			</view>

			<view v-if="traceabilityList.length > 0" :id="'module-suyuan'" :data-index="11">
				<CellTip title="溯源管理"></CellTip>
				<view class="nav">
					<view class="nav-content">
						<view class="nav-item" v-for="(item, index) in traceabilityList" @click="toNav(item.path)">
							<span :class="'iconfont ' + item.icon"></span>
							<i class="badge" v-if="item.badge">{{ item.badge }}</i>
							<label>{{ item.name }}</label>
						</view>
					</view>
				</view>
			</view>
		</view> 
	</view>
</template>

<script>
	import CellTip from "./CellTip.vue";
	import {
		statistics,
		qualityTodoByPda
	} from "@/api/myTicket";
	export default {
		components: {
			CellTip,
		},
		data() {
			return {
				timer: null,
				src1: "https://cdn.uviewui.com/uview/album/1.jpg",
				workOrder: {}, // 工单统计数据
				qmsList: [],
				//生产类
				productionList: [],
				//仓储管理
				warehousingList: [],
				//运维类
				operationsList: [],
				dispatchList: [],
				internalManagementList: [],
				treeList: [],
				saleManageList: [],
				// 售后服务
				serviceList: [],
				// 溯源管理
				traceabilityList: [],
				// 采购管理
				purchaseManageList: [],
				pcsList: [],
				// 导航相关
				moduleNavList: [],
				energyManagement:[],
				scrollIntoViewId: "",
				currentNavIndex: 0,
				moduleObserver: null,
				// 顶部固定区域高度（状态栏 + nav-bar + 横向导航）
				topNavHeight: 0,
			};
		},
		created() {
			this.getTree();
		},
		onShow() {
			// this.getStatistics();
			this.$nextTick(() => {
				this.calculateTopNavHeight();
			});
		},
		onReady() {
			// 页面准备完成后，滚动到第一个模块
			this.$nextTick(() => {
				if (this.moduleNavList.length > 0) {
					this.goToModule(this.moduleNavList[0], 0);
				}
			});
		},
		onHide() {
			clearTimeout(this.timer);
		},
		onUnload() {
			clearTimeout(this.timer);
		},
		methods: {
			// 计算顶部固定区域高度（动态获取实际高度）
			calculateTopNavHeight() {
				const query = uni.createSelectorQuery().in(this);
				query
					.select(".top-nav-wrapper")
					.boundingClientRect((rect) => {
						if (rect) {
							this.topNavHeight = rect.bottom;
						}
					})
					.exec();
			},
			getStatistics() {
				// 获取工单统计数
				statistics()
					.then((res) => {
						this.workOrder = res;
						this.operationsList.forEach((item) => {
							if (item.name == "保养工单") item.badge = res.maintenanceNum;
							if (item.name == "巡点检工单") item.badge = res.patrolInspection;
							if (item.name == "维修工单") item.badge = res.repairsNum;
						});
					})
					.finally(() => {
						this.timer = setTimeout(() => {
							this.getStatistics();
						}, 12000);
					});
				
			},
			getBrages() {
				 qualityTodoByPda().then((res) => {
					console.log(2)
					this.qmsList.forEach((item) => {
						if (item.name == "质检工单") item.badge = res.workOrderNum;
						if (item.name == "我的质检工单")
							item.badge = res.myWorkOrderNum;
						if (item.name == "我的任务单") item.badge = res.myTaskMonadNum;
						if (item.name == "我的受托单")
							item.badge = res.myRequestEntrustNum;
					});
					// this.qmsList = f.children;
				});
				
				statistics()
					.then((res) => {
						this.workOrder = res;
						this.operationsList.forEach((item) => {
							if (item.name == "保养工单") item.badge = res.maintenanceNum;
							if (item.name == "巡点检工单") item.badge = res.patrolInspection;
							if (item.name == "维修工单") item.badge = res.repairsNum;
						});
					})
			},
			getTree() {
				let _list = uni.getStorageSync("treeList");
				let list = JSON.parse(_list) || [];
				console.log("-----------list--------------");
				console.log(list);
				// 收集所有异步请求的 Promise
				const asyncPromises = [];

				if (list[0] && list[0].children.length > 0) {
					// console.log(list[0].children, "list[0].children ----");
					list[0].children.forEach((f) => {
						if (f.path == "productionManage") {
							this.productionList = f.children;
						} else if (f.path == "operationsList") {
							// const promise = statistics().then((res) => {
								// console.log(3)
								// this.workOrder = res;
								// f.children.forEach((item) => {
								// 	if (item.name == "保养工单") item.badge = res.maintenanceNum;
								// 	if (item.name == "巡点检工单")
								// 		item.badge = res.patrolInspection;
								// 	if (item.name == "维修工单") item.badge = res.repairsNum;
								// });
								this.operationsList = f.children;
							// });
							// asyncPromises.push(promise);
						} else if (f.path == "warehouseManagement") {
							this.warehousingList = f.children;
						} else if (f.path == "saleManageList") {
							this.saleManageList = f.children;
							this.saleManageList.forEach((item) => {
								item.name = item.name.replace("员工", "");
								item.name = item.name.replace("管理员", "");
							});
						} else if (f.path == "internalManagement") {
							// console.log(f, "f");
							this.internalManagementList = f.children;
						} else if (f.path == "serviceList") {
							this.serviceList = f.children;
						} else if (f.path == "traceability") {
							this.traceabilityList = f.children;
						} else if (f.path == "purchasingManage") {
							this.purchaseManageList = f.children;
						} else if (f.path == "qualityManage") {
							// const promise = qualityTodoByPda().then((res) => {
								// console.log(2)
								// f.children.forEach((item) => {
								// 	if (item.name == "质检工单") item.badge = res.workOrderNum;
								// 	if (item.name == "我的质检工单")
								// 		item.badge = res.myWorkOrderNum;
								// 	if (item.name == "我的任务单") item.badge = res.myTaskMonadNum;
								// 	if (item.name == "我的受托单")
								// 		item.badge = res.myRequestEntrustNum;
								// });
								this.qmsList = f.children;
							// });
							// asyncPromises.push(promise);
						} else if (f.path == "productionControlManagement") {
							this.pcsList = f.children;
						} else if (f.path == "dispatchManage") {
							this.dispatchList = f.children;
						} else if (f.path == 'energyManagement') {
							this.energyManagement = f.children

						}
					});
				}

				// 等待所有异步数据加载完成后再生成导航
				// if (asyncPromises.length > 0) {
				// 	// Promise.all(asyncPromises).then(() => {
				// 		console.log(1)
				// 		this.buildNavList();
				// 	// });
				// } else {
				this.buildNavList();
				// }
				this.getBrages();

			},
			// 构建导航列表
			buildNavList() {
				const navMap = {
					internalManagementList: {
						name: "协同办公",
						id: "xietong"
					},
					productionList: {
						name: "生产管理",
						id: "shengchan"
					},
					operationsList: {
						name: "运维管理",
						id: "yunwei"
					},
					serviceList: {
						name: "售后服务",
						id: "shouhou"
					},
					warehousingList: {
						name: "仓储管理",
						id: "cangchu"
					},
					dispatchList: {
						name: "运输管理",
						id: "yunshu"
					},
					saleManageList: {
						name: "营销管理",
						id: "yingxiao"
					},
					purchaseManageList: {
						name: "采购管理",
						id: "caigou"
					},
					pcsList: {
						name: "生产管控",
						id: "shengchanguanli"
					},
					qmsList: {
						name: "质量管理",
						id: "zhiliang"
					},
					traceabilityList: {
						name: "溯源管理",
						id: "suyuan"
					},
				};

				this.moduleNavList = Object.entries(navMap)
					.filter(([key]) => this[key]?.length > 0)
					.map(([, value]) => value);

				
			},
			// 点击导航跳转 - 使用动态获取的顶部高度进行精确定位
			goToModule(item, index) {
				this.currentNavIndex = index;
				this.scrollIntoViewId = "nav-" + item.id;
				setTimeout(() => {
					this.scrollIntoViewId = "";
					const query = uni.createSelectorQuery().in(this);
					query.select("#module-" + item.id).boundingClientRect();
					query.select(".top-nav-wrapper").boundingClientRect();
					query.selectViewport().scrollOffset();
					query.exec((res) => {
						if (res[0] && res[1] && res[2]) {
							const targetTop = res[0].top;
							const fixedBottom = res[1].bottom;
							const currentScrollTop = res[2].scrollTop;
							const scrollTop = currentScrollTop + targetTop - fixedBottom - 10;
							uni.pageScrollTo({
								scrollTop: Math.max(0, scrollTop),
								duration: 300,
							});
						}
					});
				}, 200);
			},
			// 监听导航滚动
			handleNavScroll(e) {
				// 可以在这里添加滚动时的逻辑
			},
			onUnload() {
				if (this.moduleObserver) {
					this.moduleObserver.disconnect();
				}
				clearTimeout(this.timer);
			},

			toNav(url) {
				// console.log(url);
				uni.navigateTo({
					url: url,
				});
			},
			HandlScanCode() {
				let _this = this;
				uni.scanCode({
					success: function(res) {
						console.log(res);
						// 获取扫描结果中的URL
						const scanResult = res.result;
						// 检查URL是否包含traceability
						if (scanResult && scanResult.includes("/traceability")) {
							// 从扫描结果中提取id参数
							let id = "";
							if (scanResult.includes("id=")) {
								// 分割URL获取id参数值
								const idPart = scanResult.split("id=")[1];
								// 如果id后面还有其他参数，只取到第一个&之前的部分
								if (idPart.includes("&")) {
									id = idPart.split("&")[0];
								} else {
									id = idPart;
								}
							}
							// 跳转到溯源页面并传递id
							uni.navigateTo({
								url: `/pages/traceability/scanCode/index?id=${id}`,
							});
							return;
						} else if(scanResult && scanResult.includes("/pages/warehouse/hwQrcode/index")) {
              uni.navigateTo({
                url: `${scanResult}`,
              });
              return
            }
						_this.scantoRouter(scanResult);
					},
				});
			},
			scantoRouter(result) {
				uni.navigateTo({
					url: `/pages/pda/workOrder/extrusionMolding/index?id=${result}`,
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import "index.scss";
</style>