<template>
	<view class="device-detail">
		<uni-nav-bar fixed="true" statusBar="true" left-icon="back" title="设备监测" @clickLeft="back"></uni-nav-bar>

		<view class="top-wrapper">
			<uni-section>
				<uni-easyinput prefixIcon="search" style="width: 460rpx" v-model="form.keyWord" placeholder="编码、名称、固资编码">
				</uni-easyinput>
			</uni-section>
			<view style="display: flex;">
				<button class="search_btn" @click="search">搜索</button>
				<view class="more_search">
					<image src="~@/static/moreSearch.svg" mode="" @click="handlScreen"></image>
				</view>
			</view>
		</view>

		<view class="update-time">更新时间：{{ updateTime }}</view>

		<scroll-view scroll-y class="device-list">
			<view class="device-card" v-for="(item, index) in deviceList" :key="index" @click="$refs.internetDetailRef.open(item.id)">
				<view class="card-header">
					<view class="card-title">
						 <view class="device-name">{{item.postName}}</view>
                        <text class="device-name">{{ item.name+ (item.codeNumber ? '-' + item.codeNumber : '') }}</text>
						
					    <text v-if="item.status == 2" class="alarm-icon">🚨</text>
                    </view>
					<u-tag
						:text="getStatusLabel(item.status)"
						:type="getStatusType(item.status, 1)"
						size="mini"
						:customStyle="{ marginLeft: 'auto' }"
					/>
				</view>

				<view class="status-tag-wrap">
					<u-tag :text="getStatusText(item.iotList.length ? 1 : 0)" :type="getStatusType(item.iotList.length ? 1 : 0)" size="mini" />
				</view>

                <view class="data-grid">
                    <view class="data-item" v-for="iotItem in item.iotList" >
                        <span class="data-label">{{ iotItem.name }}</span>
                        <span class="data-value">{{
                        iotItem.dataType.type == 'enum' ||
                        iotItem.dataType.type == 'bool'
                            ? iotItem.dataType.specs[iotItem.value]
                            : iotItem.value +
                            ' ' +
                            ((iotItem.unit && iotItem.unit) || '')
                        }}</span>
                    </view>
                </view>
			</view>
		</scroll-view>

        <screen ref="screen" @succeed="handleFilter" :postId="form.postId" :postName="form.postName"></screen>
		<internetDetail ref="internetDetailRef"></internetDetail>
	</view>
</template>

<script>
import screen from './deviceScreen.vue'
import internetDetail from './internetDetail.vue'
import { getDeviceCount } from '@/api/home'
import { businessStatus } from '@/enum/dict'
export default {
    components: {
        screen,internetDetail
    },
	data() {
		return {
			deviceType: '',
			unit: '',
			updateTime: '',
			deviceList: [],
            form: {
                keyWord: '',
                postId: '',
                postName: ''
            }
		}
	},
	computed: {

	},
	created() {
		this.updateTime = this.formatDate(new Date())
		this.fetchDeviceData()
	},
	methods: {
        handlScreen() {
            this.$refs.screen.open()
        },
        async getData() {
            const res = await getDeviceCount({
                size: 9999
            })

        },
	
		handleFilter(data) {
            console.log('data---', data)
            for (let key of Object.keys(data)) {
                this.form[key] = data[key]
            }
			this.fetchDeviceData()
		},
		formatDate(date) {
			const y = date.getFullYear()
			const m = String(date.getMonth() + 1).padStart(2, '0')
			const d = String(date.getDate()).padStart(2, '0')
			const h = String(date.getHours()).padStart(2, '0')
			const min = String(date.getMinutes()).padStart(2, '0')
			const s = String(date.getSeconds()).padStart(2, '0')
			return `${y}-${m}-${d} ${h}:${min}:${s}`
		},
        // 获取状态文本
      getStatusText(status) {
        const textMap = {
          1: '在线',
          0: '离线',
          fault: '故障'
        };
        return textMap[status] || status;
      },
		getStatusType(status, type) {
            const typeMap = !type
            ? {
                1: 'success',
                0: 'info',
                fault: 'error'
                }
            : {
                0: 'success',
                1: 'success',
                4: 'success',
                5: 'warning',
                2: 'error',
                3: 'error'
            };
            return typeMap[status];

		},
        getStatusLabel(status) {
            return businessStatus.find(item => item.code == status)?.label
        },
		async fetchDeviceData() {
            const res = await getDeviceCount({
                ...this.form,
                size: 9999
            })

            let deviceData = res.list.map((item) => {
                let iotList = [];
                if (item.iotPointDataList) {
                item.iotPointDataList.forEach((element) => {
                    let data = item.iotModel.properties.find(
                    (iotModel) => iotModel.identifier == element.identifier
                    );
                    if (data) {
                    iotList.push({
                        ...element,
                        dataType: data.dataType
                    });
                    }
                });
                }

                item['iotList'] = item.iotDashboardPoint.length
                ? iotList.filter((iotListItem) =>
                    item.iotDashboardPoint.find(
                        (Point) =>
                        Point.identifier == iotListItem.identifier &&
                        Point.checked1
                    )
                    )
                : iotList.filter((iotListItem, index) => index < 4);
                return item;
            });
			// TODO: 替换为实际接口调用
			this.deviceList = deviceData

            console.log(deviceData)
            
		}
	}
}
</script>

<style lang="scss" scoped>
.top-wrapper {
		display: flex;
		height: 88rpx;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;

		/deep/.uni-section {
			margin-top: 0px;
		}

		/deep/.uni-section-header {
			padding: 0px;

		}

		.search_btn {
			width: 120rpx;
			height: 70rpx;
			line-height: 70rpx;
			background: $theme-color;
			font-size: 28rpx;
			color: #fff;
		}

		.menu_icon {
			width: 44rpx;
			height: 44rpx;
			margin-left: 14rpx;
		}

		.more_search {
			display: flex;
			align-items: center;
			height: 70rpx;
			line-height: 70rpx;

		}

		/deep/.u-input {
			border: 1rpx solid #ccc;

			.u-input__content__field-wrapper__field {
				height: 40rpx !important;
			}
		}

		image {
			width: 52rpx;
			height: 52rpx;
			margin-left: 10rpx;
		}

	}
.device-detail {
	// height: 100vh;
	display: flex;
	flex-direction: column;
	// background-color: #1a1b1f;
	// color: #fff;
}

.nav-bar {
	flex-shrink: 0;
}

.filter-bar {
	display: flex;
	align-items: center;
	padding: 16rpx 24rpx;
	// background-color: #22232a;

	.picker-text {
		font-size: 26rpx;
		color: #ccc;
	}

	.filter-btn {
		flex-shrink: 0;
		margin-left: auto;
		padding: 10rpx 28rpx;
		border: 1rpx solid #4caf50;
		border-radius: 8rpx;
		color: #4caf50;
		font-size: 26rpx;
	}
}

.update-time {
	padding: 12rpx 24rpx;
	font-size: 24rpx;
	color: #999;
	// background-color: #1a1b1f;
}

.device-list {
	flex: 1;
	padding: 20rpx 24rpx;
}

.device-card {
	// background-color: #25262c;
	border-radius: 16rpx;
	padding: 28rpx 24rpx;
	margin-bottom: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    border: 1rpx solid #ccc;
}

.card-header {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
    justify-content: space-between;

	.device-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.alarm-icon {
		margin-left: 12rpx;
		font-size: 32rpx;
	}
}

.status-tag-wrap {
    display: flex;
	margin-bottom: 16rpx;
}

.data-grid {
	display: flex;
	margin-top: 12rpx;
    flex-wrap: wrap;
	.data-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
        width: 50%;
        padding: 10rpx 20rpx;
		.data-label {
			font-size: 26rpx;
			color: #333;
		}

		.data-value {
			font-size: 28rpx;
			color: #333;
			font-family: monospace;
		}

		.text-red {
			color: #f44336;
		}
	}
}
</style>
