<template>
	<view v-if="visible" class="popup-overlay" :class="{ 'popup-overlay-enter': showAnimation }">
		<view class="popup-fixed" :class="{ 'popup-scale-enter': showAnimation }">
			<view class="popup-container">
				<view class="popup-header">
					<text class="popup-title">设备信息</text>
					<view class="popup-close" @click="handleClose">
						<image src="/static/icon_close.png" class="close-icon" mode="aspectFit"></image>
					</view>
				</view>

				<scroll-view class="popup-content" scroll-y="true">
					<view class="info-section" v-if="deviceData">
						<!-- 标识与编码 -->
						<view class="info-group">
							<!-- <text class="group-title">标识与编码</text> -->
							<view class="info-item" v-if="deviceData?.machine_id != null">
								<text class="info-label">设备ID:</text>
								<text class="info-value">{{ deviceData?.machine_id }}</text>
							</view>
							<view class="info-item" v-if="deviceData?.machine_code">
								<text class="info-label">设备码:</text>
								<text class="info-value">{{ deviceData?.machine_code }}</text>
							</view>
							<view class="info-item" v-if="deviceData?.code != null">
								<text class="info-label">应用编码:</text>
								<text class="info-value">{{ deviceData?.code }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">应用版本:</text>
								<text class="info-value">{{ appVersionText }}</text>
							</view>
							<view class="info-item" v-if="deviceData?.app_value?.label != null">
								<text class="info-label">应用类型:</text>
								<text class="info-value">{{ deviceData?.app_value?.label }}</text>
							</view>
							<view class="info-item" v-if="deviceData?.language_value?.label != null">
								<text class="info-label">默认语言:</text>
								<text class="info-value">{{ deviceData?.language_value?.label }}</text>
							</view>
							<!-- <text class="group-title">状态与绑定</text> -->
							<view class="info-item" v-if="deviceData?.flag != null && deviceData?.flag?.value != null">
								<text class="info-label">设备状态:</text>
								<text class="info-value"
									:class="getStatusClass(deviceData?.flag?.value)">{{ getOnlineStatusText(deviceData?.flag?.value) }}</text>
							</view>
							<view class="info-item"
								v-if="deviceData?.bind_device != null && deviceData?.bind_device?.value != null">
								<text class="info-label">绑定状态:</text>
								<text class="info-value">{{ getBindStatusText(deviceData?.bind_device?.value) }}</text>
							</view>
							<view class="info-item" v-if="deviceData?.device_id != null">
								<text class="info-label">唯一标识:</text>
								<text class="info-value">{{ deviceData?.device_id }}</text>
							</view>
							<view class="info-item" v-if="deviceData?.currency_symbols">
								<text class="info-label">货币符号:</text>
								<text class="info-value">{{ deviceData?.currency_symbols }}</text>
							</view>
							<view class="info-item" v-if="deviceData?.create_time">
								<text class="info-label">创建时间:</text>
								<text class="info-value">{{ deviceData?.create_time }}</text>
							</view>
							<view class="info-item" v-if="deviceData?.update_time">
								<text class="info-label">更新时间:</text>
								<text class="info-value">{{ deviceData?.update_time }}</text>
							</view>
							<!-- 摄像头位置选择 -->
							<view class="info-item">
								<text class="info-label">摄像头前置开启:</text>
								<switch :checked="cameraPositionFront" @change="handleCameraPositionChange" color="#FD3DA0" />
							</view>
							<!-- 镜像开关 -->
							<view class="info-item">
								<text class="info-label">摄像头镜像开启:</text>
								<switch :checked="cameraMirrorEnabled" @change="handleMirrorChange" color="#FD3DA0" />
							</view>
						</view>
					</view>

					<!-- 无数据提示 -->
					<view v-else class="no-data">
						<text class="no-data-text">暂无设备信息</text>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	// 定义设备信息的类型结构
	type ValueItem = {
		label : string | null
		value : string | number | null
	}

	type MachineInfo = {
		partner_name : string | null
		machine_code : string | null
	}

	type DeviceInfo = {
		machine_id : string | null
		machine_code : string | null
		code : string | null
		app_value : ValueItem | null
		language_value : ValueItem | null
		flag : ValueItem | null
		bind_device : ValueItem | null
		device_id : string | null
		print_quota : number | string | null
		machine : MachineInfo | null
		currency_symbols : string | null
		create_time : string | null
		update_time : string | null
	}

	type DeviceInfoProps = {
		visible : boolean
		closeOnOverlay : boolean
		deviceInfo : UTSJSONObject | null
	}

	type DeviceInfoEmits = {
		(e : 'close') : void
	}

	const props = withDefaults(defineProps<DeviceInfoProps>(), {
		visible: false,
		closeOnOverlay: true,
		deviceInfo: null
	})

	const emit = defineEmits<DeviceInfoEmits>()

	const showAnimation = ref(false)

	// 应用版本（仅在 APP 平台获取），其他平台显示为“未知”
	type AppBaseInfo = {
		appVersion : string
	}
	const appVersion = ref<string | null>(null)
	const appVersionText = computed(() : string => {
		if (appVersion.value != null) {
			return appVersion.value as string
		}
		return '未知'
	})

	// 镜像开关状态
	const cameraMirrorEnabled = ref<boolean>(false)
	// 摄像头位置状态（true=前置，false=后置）
	const cameraPositionFront = ref<boolean>(false)
	
	onMounted(() : void => {
		// #ifdef APP
		const info = uni.getAppBaseInfo()
		appVersion.value = info.appVersion
		// #endif
		
		// 从缓存读取镜像状态和摄像头位置
		const storedMirror = uni.getStorageSync('cameraMirror')
		const storedPosition = uni.getStorageSync('cameraPosition')
		
		// 处理 storedMirror 可能是字符串或布尔值的情况
		if (storedMirror != null) {
			if (typeof storedMirror == 'boolean') {
				cameraMirrorEnabled.value = storedMirror as boolean
			} else if (typeof storedMirror == 'string') {
				cameraMirrorEnabled.value = (storedMirror as string) === 'true'
			} else {
				cameraMirrorEnabled.value = false
			}
		} else {
			cameraMirrorEnabled.value = false
		}
		
		cameraPositionFront.value = storedPosition != null ? (storedPosition as string) === 'front' : false
	})
	
	// 处理摄像头位置变化
	const handleCameraPositionChange = (e : UniSwitchChangeEvent) => {
		const checked = e.detail.value
		cameraPositionFront.value = checked
		const position = checked ? 'front' : 'back'
		// 保存到全局状态
		const app = getApp()
		app.globalData.cameraPosition = position
		// 保存到缓存
		uni.setStorageSync('cameraPosition', position)
		console.log('摄像头位置已更新:', checked ? '前置' : '后置')
	}
	
	// 处理镜像开关变化
	const handleMirrorChange = (e : UniSwitchChangeEvent) => {
		const checked = e.detail.value
		cameraMirrorEnabled.value = checked
		// 保存到全局状态
		const app = getApp()
		app.globalData.cameraMirror = checked
		// 保存到缓存
		uni.setStorageSync('cameraMirror', checked)
		console.log('摄像头镜像状态已更新:', checked)
	}

	// 将 UTSJSONObject 转换为类型安全的 DeviceInfo
	const deviceData = computed(() : DeviceInfo | null => {
		if (props.deviceInfo == null) return null

		const data = props.deviceInfo as UTSJSONObject

		// 辅助函数：安全获取 ValueItem
		const getValueItem = (key : string) : ValueItem | null => {
			const item = data[key]
			if (item == null) return null
			const obj = item as UTSJSONObject
			return {
				label: obj.getString('label'),
				value: obj['value'] as string | number | null
			}
		}

		// 辅助函数：安全获取 MachineInfo
		const getMachineInfo = () : MachineInfo | null => {
			const machine = data['machine']
			if (machine == null) return null
			const obj = machine as UTSJSONObject
			return {
				partner_name: obj.getString('partner_name'),
				machine_code: obj.getString('machine_code')
			}
		}

		return {
			machine_id: data.getString('machine_id'),
			machine_code: data.getString('machine_code'),
			code: data.getString('code'),
			app_value: getValueItem('app_value'),
			language_value: getValueItem('language_value'),
			flag: getValueItem('flag'),
			bind_device: getValueItem('bind_device'),
			device_id: data.getString('device_id'),
			print_quota: data['print_quota'] as number | string | null,
			machine: getMachineInfo(),
			currency_symbols: data.getString('currency_symbols'),
			create_time: data.getString('create_time'),
			update_time: data.getString('update_time')
		}
	})

	// 监听弹窗显示状态，控制动画
	watch(() : boolean => props.visible, (newVal : boolean) : void => {
		if (newVal) {
			// 每次打开弹窗时重新从缓存读取状态
			const storedMirror = uni.getStorageSync('cameraMirror')
			const storedPosition = uni.getStorageSync('cameraPosition')
			
			// 处理 storedMirror 可能是字符串或布尔值的情况
			if (storedMirror != null) {
				if (typeof storedMirror == 'boolean') {
					cameraMirrorEnabled.value = storedMirror as boolean
				} else if (typeof storedMirror == 'string') {
					cameraMirrorEnabled.value = (storedMirror as string) === 'true'
				} else {
					cameraMirrorEnabled.value = false
				}
			} else {
				cameraMirrorEnabled.value = false
			}
			
			cameraPositionFront.value = storedPosition != null ? (storedPosition as string) === 'front' : false
			
			console.log('弹窗打开 - 摄像头镜像:', cameraMirrorEnabled.value)
			console.log('弹窗打开 - 摄像头位置:', cameraPositionFront.value ? '前置' : '后置')
			
			nextTick(() => {
				showAnimation.value = true
				console.log('deviceInfo', deviceData.value)
			})
		} else {
			showAnimation.value = false
		}
	}, { immediate: false })

	// 处理遮罩层点击
	const handleOverlayClick = () => {
		if (props.closeOnOverlay) {
			handleClose()
		}
	}

	// 关闭弹窗
	const handleClose = () => {
		showAnimation.value = false
		setTimeout(() => {
			emit('close')
		}, 200)
	}

	// 将 0/1 或 '0'/'1' 统一为字符串; 其他返回 null
	const toBinaryString = (value : string | number | null) : string | null => {
		if (value == null) return null
		const t = typeof value
		if (t == 'number') {
			const numVal = value as number
			if (numVal == 1) return '1'
			if (numVal == 0) return '0'
			return null
		}
		if (t == 'string') {
			const strVal = value as string
			if (strVal == '1' || strVal == '0') return strVal
			return null
		}
		return null
	}

	// 获取"在线/离线/未知"文本
	const getOnlineStatusText = (value : string | number | null) : string => {
		const v = toBinaryString(value)
		if (v == null) return '未知'
		if (v == '1') return '在线'
		if (v == '0') return '离线'
		return '未知'
	}

	// 获取绑定状态文本（已绑定/未绑定/未知）
	const getBindStatusText = (value : string | number | null) : string => {
		const v = toBinaryString(value)
		if (v == null) return '未知'
		if (v == '1') return '已绑定'
		if (v == '0') return '未绑定'
		return '未知'
	}

	// 获取"是/否/未知"文本（用于是否直接打印、是否无限打印）
	const getYesNoText = (value : string | number | null) : string => {
		const v = toBinaryString(value)
		if (v == null) return '未知'
		if (v == '1') return '是'
		if (v == '0') return '否'
		return '未知'
	}

	// 获取状态样式类（在线/离线/未知）
	const getStatusClass = (value : string | number | null) : string => {
		const v = toBinaryString(value)
		if (v == null) return 'status-unknown'
		if (v == '1') return 'status-online'
		if (v == '0') return 'status-offline'
		return 'status-unknown'
	}
</script>

<style>
	.popup-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 9999;
		display: flex;
		justify-content: center;
		align-items: center;
		opacity: 0;
		transition: opacity 0.2s ease;
	}

	.popup-overlay-enter {
		opacity: 1;
	}

	.popup-fixed {
		width: 90%;
		max-width: 600rpx;
		height: 70%;
		background: #FFFFFF;
		border-radius: 20rpx;
		transform: scale(0.8);
		transition: transform 0.2s ease;
	}

	.popup-scale-enter {
		transform: scale(1);
	}

	.popup-container {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.popup-header {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #F0F0F0;
	}

	.popup-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
	}

	.popup-close {
		width: 40rpx;
		height: 40rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background: #000000;
		border-radius: 9999rpx;
	}

	.close-icon {
		width: 30rpx;
		height: 34rpx;
	}

	.popup-content {
		flex: 1;
		padding: 0 30rpx 30rpx 30rpx;
	}

	.info-section {
		width: 100%;
	}

	.info-group {
		margin-bottom: 40rpx;
	}

	.group-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 20rpx;
	}

	.info-item {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: flex-start;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #F5F5F5;
	}

	.info-item:last-child {
		border-bottom: none;
	}

	.info-label {
		font-size: 28rpx;
		color: #333333;
		flex-shrink: 0;
		font-weight: bold;
		;
		width: 260rpx;
	}

	.info-value {
		font-size: 28rpx;
		color: #666666;
		flex: 1;
		text-align: right;
		/* 长文本换行显示，避免被截断 */
		white-space: normal;
	}

	.status-online {
		color: #52C41A;
	}

	.status-offline {
		color: #FF4D4F;
	}

	.status-unknown {
		color: #999999;
	}

	.no-data {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200rpx;
	}

	.no-data-text {
		font-size: 28rpx;
		color: #999999;
	}
</style>