<template>
	<view>
		<uv-navbar title="设备监控中心" :placeholder="true" :titleStyle="{ color: '#ffffff' }" leftIconColor="#ffffff"
			bgColor="#1d345e" @leftClick="goBack"></uv-navbar>
		<scroll-view :style="{height: `calc(100vh - ${(headTop + 44) + 'px'})`,}" :scroll-top="scrollTop"
			scroll-with-animation="true" scroll-y="true" @scrolltolower="loadMore" @scroll="handleScroll"
			:lower-threshold="50">
			<uv-drop-down :is-sticky="false" ref="dropDown" sign="dropDown_1" text-active-color="#3c9cff"
				:extra-icon="{name:'arrow-down',color:'#666',size:'26rpx'}"
				:extra-active-icon="{name:'arrow-up',color:'#3c9cff',size:'26rpx'}" :defaultValue="defaultValue"
				:custom-style="{padding: '0 30rpx',justifyContent: 'center'}" @click="selectMenu">
				<uv-drop-down-item name="order" type="2" :label="dropdownMenuData.order.label"
					:value="dropdownMenuData.order.value">
				</uv-drop-down-item>
			</uv-drop-down>
			<uv-drop-down-popup sign="dropDown_1" :click-overlay-on-close="true" :currentDropItem="currentDropItem"
				@clickItem="clickItem"></uv-drop-down-popup>
			<view class="box_configuration" v-if="tionData.length > 0">
				<view class="card_box_tion" v-for="(item,index) in tionData" :key="index" @click="goToDetails(item)">
					<view class="circle_icon_tion">
						<text class="iconfont tion_icon">&#xe9d9;</text>
					</view>
					<view>
						<view class="title_tion">{{item.deviceName}}</view>
						<view class="box_tag_tion">{{titleType}}</view>
					</view>
				</view>
				<view v-if="pageNum > 1">
					<uv-load-more :status="status" color="#ffffff" />
				</view>
			</view>
			<view style="margin-top:30%;" v-else>
				<x-empty></x-empty>
			</view>
		</scroll-view>
		<view class="top-back" @click="topBack" v-if="backShow">
			<text class="iconfont icon_back_top">&#xe806;</text>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, watch, computed, nextTick } from 'vue'
	import { GetDeviceType, getDevices } from "@/api/configuration";
	import { onShow, onLoad, onPageScroll, onReady } from "@dcloudio/uni-app";
	
	const pageNum = ref(1)
	const pageSize = ref(10)
	const loadingMore = ref(true)
	const titleType : any = ref('')
	const deviceType : any = ref('')
	const tionData : any = ref([])
	const activeName = ref('order')
	// 表示value等于这些值，就属于默认值
	const defaultValue = [0, 'all', '0']
	const dropdownMenuData : any = reactive({
		order: {
			label: '设备类型',
			value: 'all',
			activeIndex: 0,
			color: '#333',
			activeColor: '#3c9cff',
			child: []
		},
	})
	const scrollTop : any = ref(-1)
	const backShow : any = ref(false)
	// 记录当前滚动位置
	const currentScrollTop = ref(0)
	const status = ref('loadmore')
	const headTop = ref(0)
	// 防抖函数
	function debounce(func : any, wait : any) {
		let timeout : any = null
		return function executedFunction(...args : any) {
			const later = () => {
				clearTimeout(timeout)
				func(...args)
			}
			clearTimeout(timeout)
			timeout = setTimeout(later, wait)
		}
	}
	// 处理滚动事件
	const handleScroll = debounce((e : any) => {
		scrollTop.value = -1
		currentScrollTop.value = e.detail.scrollTop
		// 滚动超过200px显示返回顶部按钮
		backShow.value = e.detail.scrollTop > 200
	}, 100)
	// 返回顶部
	function topBack() {
		scrollTop.value = 0
		setTimeout(() => {
			backShow.value = false
		}, 300)
	}
	// 加载更多数据
	const loadMore = () => {
		if (!loadingMore.value) {
			getList(deviceType.value)
		}
	};
	function getType() {
		GetDeviceType({}).then((res : any) => {
			if (res.code == 200) {
				const result = Object.entries(res.data).map(([value, label]) => ({
					label,
					value
				}))
				dropdownMenuData.order.label = result[0].label
				dropdownMenuData.order.value = result[0].value
				dropdownMenuData.order.child = result
				titleType.value = result[0].label
				deviceType.value = result[0].value
				pageNum.value = 1
				tionData.value = []
				getList(result[0].value)
			}
		})
	}
	function getList(type : any) {
		getDevices({
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			device_type: type,
		}).then((res : any) => {
			if (res.code == 200) {
				const convertedData = Object.entries(res.data).map(([deviceName, deviceData] : any) => ({
					deviceName,
					...deviceData
				}));
				if (convertedData.length > 0) {
					tionData.value = tionData.value.concat(convertedData)
				}
				if (convertedData.length < pageSize.value) {
					status.value = 'nomore'
					loadingMore.value = true
				} else {
					status.value = 'loading'
					loadingMore.value = false
					pageNum.value++
				}
				const arrData = getCardDisplayData(convertedData[0])
			}
		})
	}
	const getCardDisplayData = (device : any) => {
		const importantKeys = ['运行状态', '故障报警', '送风温度', '水阀反馈', '自动状态', '过滤网压差'];
		const result : any = {};

		importantKeys.forEach(key => {
			if (device[key] !== undefined) {
				result[key] = device[key];
			}
		});

		const allKeys = Object.keys(device).filter(key => key !== 'deviceName');
		let count = Object.keys(result).length;
		for (const key of allKeys) {
			if (count >= 4) break;
			if (!result[key]) {
				result[key] = device[key];
				count++;
			}
		}

		return result;
	};
	// 获取当前下拉筛选项
	const currentDropItem = computed(() => {
		// @ts-ignore
		return dropdownMenuData[activeName.value];
	})
	/**
	 * 点击每个筛选项回调
	 * @param {Object} e { name, active, type } = e
	 */
	function selectMenu(e : any) {
		const { name } = e;
		activeName.value = name;
	}
	/**
	 * 点击菜单回调处理
	 * @param {Object} e 选中项 { label,value } = e
	 */
	function clickItem(e : any) {
		const { label, value } = e;
		titleType.value = label
		deviceType.value = value
		if (defaultValue.indexOf(value) == -1) {
			dropdownMenuData[activeName.value].label = label
			dropdownMenuData[activeName.value].value = value
		} else {
			dropdownMenuData[activeName.value].label = activeName.value == 'order' ? '设备类型' : '文档格式'
			dropdownMenuData[activeName.value].value = 'all'
		}
		pageNum.value = 1
		tionData.value = []
		getList(value)
	}
	// 返回上一页
	function goBack() {
		uni.navigateBack({
			delta: 1,
		});
	}
	// 跳转到设备组态详情页
	function goToDetails(alarm : any) {
		uni.navigateTo({
			url: `/pages/configuration/details?alarmId=${alarm.deviceName}&type=${deviceType.value}`,
		});
	}
	onShow(() => {
		// #ifdef APP-PLUS
		plus.navigator.setStatusBarStyle("light");
		// #endif
		const { safeAreaInsets } : any = uni.getSystemInfoSync()
		headTop.value = safeAreaInsets.top
		nextTick(() => {
			getType()
		})
	});
</script>

<style>
	.box_configuration {
		display: flex;
		flex-direction: column;
		padding-bottom: 30rpx;
	}

	.card_box_tion {
		display: flex;
		align-items: center;
		background-color: rgba(85, 110, 143, .3);
		border-radius: 10rpx;
		margin: 20rpx 20rpx 0rpx 20rpx;
		padding: 20rpx;
	}

	.circle_icon_tion {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background-color: #3e99f7;
		padding: 30rpx;
		margin-right: 15rpx;
	}

	.tion_icon {
		font-size: 50rpx;
		color: #fff;
	}

	.title_tion {
		font-size: 30rpx;
		color: #fff;
		margin-bottom: 12rpx;
	}

	.box_tag_tion {
		width: fit-content;
		width: -webkit-fit-content;
		width: -moz-fit-content;
		color: #dddddd;
		padding: 2rpx 10rpx;
		font-size: 26rpx;
		background-color: rgba(235, 238, 245, .3);
		border-radius: 5rpx;
	}

	.top-back {
		position: fixed;
		right: 30rpx;
		bottom: 120rpx;
		width: 80rpx;
		height: 80rpx;
		background: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: white;
		font-size: 28rpx;
		z-index: 999;
		animation: heart 0.3s;

		@keyframes heart {
			0% {
				right: -30rpx;
			}

			100% {
				right: 30rpx;
			}
		}
	}

	.icon_back_top {
		font-size: 46rpx;
	}
</style>