<template>
	<view class="page-container">
		<!-- 顶部导航 -->
		<view class="header">
			<view class="search-area">
				<view class="filter-box">
					<view v-for="(item, index) in statusList" :key="index"
						:class="['filter-item', item.selected ? 'filter-item-active' : '']" @click="toggleFilter(index)">
						{{ item.name }}
					</view>
				</view>
			</view>
		</view>
		<!-- 列表区域 -->
		<scroll-view class="list-container" scroll-y @scrolltolower="loadMore" @refresherrefresh="refresh" refresher-enabled
			:refresher-triggered="isRefreshing">
			<view v-if="filteredPoleList.length > 0">
				<view v-for="(item, index) in filteredPoleList" :key="index" class="pole-card">
					<view class="pole-number">{{ item.name+item.number }}</view>
					<view class="pole-info">
						<text :class="['pole-status', `status-${item.status}`]">
							{{ getStatusText(item.status) }}
						</text>
						<view class="light-control">
							<view>
								<text class="pole-light">灯光状态</text>
								<switch :checked="item.lightOn" @change="(e) => handleSwitchChange(e, index, item.number)"
									:disabled="item.status === 'offline'" color="#1890ff" class="light-switch" />
							</view>
							<view>
								<button class="pole-button" size="mini" @click="goDetail(item)" type="primary">查看详情</button>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 空状态 -->
			<view v-else class="empty-state">
				<uni-icons type="info" size="50" color="#999" />
				<text class="empty-text">暂无数据</text>
				<button class="refresh-btn" @click="refresh">刷新</button>
			</view>
		</scroll-view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, reactive, onMounted, computed } from 'vue';
import { clientGet } from '../../utils/request';

	const BASE_URL = import.meta.env.VITE_APP_BASE_URL;
	const showSearch = ref(false);
	const isRefreshing = ref(false);
	const statusList = reactive<{ name : string, selected : boolean }[]>([
		{ name: '在线', selected: false },
		{ name: '离线', selected: false }
	]);
	const poleList = ref<{ name ?: string, number : string, status : 'normal' | 'offline', lightOn : boolean }[]>([
		{ name: '灯杆', number: '40005289', status: 'normal', lightOn: false },
		{ name: '灯杆', number: '40005272', status: 'normal', lightOn: false },
		{ name: '灯杆', number: '40005274', status: 'normal', lightOn: false },
		{ name: '灯杆', number: '40005281', status: 'normal', lightOn: false },
	]);

	const handleSwitchChange = async (e : any, index : number, poleNumber : string) => {
		if (poleList.value[index].status === 'offline') {
			uni.showToast({
				title: '设备离线无法操作',
				icon: 'none'
			});
			return;
		}
		let res;
		if (e.detail.value) {
			res = await turnLightOrTurnOff(poleNumber, true)
		} else {
			res = await turnLightOrTurnOff(poleNumber, false)
		}
		if(res){
			poleList.value[index].lightOn = e.detail.value;
		}else{
			uni.showToast({
				title:'操作失败',
				duration:1000
			})
		}
	};

	const turnLightOrTurnOff = async (poleNumber : string, isTurn : boolean) => {
		uni.showLoading({
			title:"正在操作..."
		})
		const res = await clientGet('/pole/instruct/issued/reportEnvironmentalData',{
				cmd: '6011',
				lightNums: poleNumber,
				packageId: '1050',
				brightness: (isTurn ? 100 : 0).toString()
			})
		uni.hideLoading();
		if ((res as any).code === 200) {
			uni.showToast({
				title: "操作成功",
				duration: 1000
			})
			return true;
		}
		return false;
	}

	const getStatusText = (status : string) => {

		const statusMap : Record<string, string> = {
			normal: '在线',
			offline: '离线'
		};
		return statusMap[status] || status;
	};

	const toggleSearch = () => {
		showSearch.value = !showSearch.value;
	};

	const toggleFilter = (index : number) => {
		statusList[index].selected = !statusList[index].selected;
	};

	const goBack = () => {
		uni.navigateBack();
	};

	const goDetail = (item : any) => {
		uni.setStorageSync("poleNumber",item.number);
		uni.navigateTo({
			url: `/pages/poleDetail/index`
		});
	};

	const loadMore = () => {
		// 加载更多数据
		console.log('load more');
	};

	const refresh = async () => {
		statusList.forEach(item => {
			item.selected = false;
		})
		isRefreshing.value = true;
		await getPoleListStatus();
		isRefreshing.value = false;
	};

	const getPoleStatus = async (poleNumber : string) => {
		const res = await clientGet("/pole/instruct/issued/equipmentStatus",{
				cmd: '6012',
				lightNums: poleNumber,
				packageId: '1050'
			});
		return res;
	};

	const getPoleListStatus = async () => {
		uni.showLoading({
			title: "正在获取最新数据...",
			mask: true,
		});
		try {
			const resList = [];
			for (let s of poleList.value) {
				console.log(s.number);
				const res = await getPoleStatus(s.number);
				resList.push(res);
			}
			poleList.value = resList.map(item => {
				const data = JSON.parse(JSON.parse(item.data).params);
				if (data.length < 1) {
					console.error('获取数据失败');
					uni.showToast({
						title: '获取数据失败',
						duration: 2000
					});
					return;
				}
				const light_num = data[0].light_num;
				const brightness = data[0].brightness;
				const onlineStatus = data[0].onlineStatus;
				const name = poleList.value.filter(item => {
					return item.number === light_num;
				})[0]?.name;
				const isLightOn = parseInt(brightness) === 100;
				const status = parseInt(onlineStatus) === 1;
				return ({
					name,
					number: light_num,
					status: status ? 'normal' : 'offline',
					lightOn: isLightOn
				});
			});
		} finally {
			uni.hideLoading();
		}
	};

	const filteredPoleList = computed(() => {
		const selectedStatuses = statusList.filter(item => item.selected).map(item => item.name);
		if (selectedStatuses.length === 0) {
			return poleList.value;
		}
		return poleList.value.filter(pole => {
			const statusText = getStatusText(pole.status);
			return selectedStatuses.includes(statusText);
		});
	});

	onMounted(() => {
		getPoleListStatus();
	});
</script>

<style scoped>
	page {
		height: 100%;
	}

	.page-container {
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
	}

	.header {
		flex-shrink: 0;
		background-color: #ffffff;
	}

	.search-area {
		padding: 20rpx 30rpx;
		background-color: #ffffff;
	}

	.search-box {
		display: flex;
		align-items: center;
		background-color: #f5f5f5;
		padding: 16rpx 20rpx;
		border-radius: 8rpx;
	}

	.search-input-icon {
		width: 16px;
		height: 16px;
		margin-right: 16rpx;
	}

	.search-input {
		flex: 1;
		font-size: 14px;
	}

	.filter-box {
		display: flex;
		margin-top: 20rpx;
		gap: 20rpx;
	}

	.filter-item {
		padding: 10rpx 30rpx;
		border-radius: 30rpx;
		font-size: 14px;
		border: 1px solid #ddd;
		color: #666;
	}

	.filter-item-active {
		background-color: #e6f7ff;
		border-color: #1890ff;
		color: #1890ff;
	}

	.list-container {
		flex: 1;
		overflow: auto;
		padding: 20rpx;
	}

	.pole-card {
		background-color: #ffffff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 650rpx;
	}

	.pole-number {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.pole-info {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		gap: 10rpx;
	}

	.pole-status {
		font-size: 14px;
		padding: 4rpx 16rpx;
		border-radius: 4rpx;
	}

	.status-normal {
		background-color: #f6ffed;
		color: #52c41a;
	}

	.status-fault {
		background-color: #fff2f0;
		color: #ff4d4f;
	}

	.status-offline {
		background-color: #f5f5f5;
		color: #999;
	}

	.pole-light {
		font-size: 14px;
		color: #666;
		margin-right: 10rpx;
	}

	.light-control {
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-wrap: wrap;
		gap: 10rpx;
	}

	.light-state {
		font-size: 14px;
		color: #1890ff;
	}

	.light-icon {
		width: 16px;
		height: 16px;
	}

	.light-switch {
		transform: scale(0.8);
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 200rpx;
	}

	.empty-text {
		margin: 30rpx 0;
		font-size: 14px;
		color: #999;
	}

	.refresh-btn {
		width: 200rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 14px;
		color: #fff;
		background-color: #1890ff;
		border-radius: 40rpx;
	}
</style>