<template>
	<view class="container">
		<UserInfoCard :currentCardNo="currentCardNo" :deviceInfo="deviceInfo" :onlineStatus="onlineStatus" />

		<DeviceStatusCard v-if="userInfo.isDevice" :deviceInfo="deviceInfo" :isRealName="isRealName"
			@authentication="enterDetail('authentication')" />

		<VoiceCard v-if="!userInfo.isDevice" :voiceStats="voiceStats" :dateRangeText="dateRangeText"
			@openDatePicker="openDateRangePicker" />

		<TrafficCard :deviceInfo="deviceInfo" :isDevice="userInfo.isDevice" />

		<WhitelistCard v-if="!userInfo.isDevice" :whitelistData="whitelistData" @refresh="refreshWhitelist"
			@add="showAddWhitelistDialog" @showSms="showSmsCodeDialog" />

		<WifiCard v-if="userInfo.isDevice" :deviceInfo="deviceInfo" @modify="modifyWifi" @copy="copy" />

		<FunctionCard :realNameStatus="realNameStatus" :alreadyBindPhone="alreadyBindPhone"
			:isDevice="userInfo.isDevice" @enter="enterDetail" @sync="onSync">
			<!-- 修改WIFI弹窗 -->
			<up-popup :show="showModifyWifi" mode="center" @close="showModifyWifi=false">
				<view class="wifi-popup">
					<view class="title mb-md">修改WIFI</view>
					<view class="flex-col-g20">
						<view class="flex-col-g8">
							<label class="caption">名称:</label>
							<up-input placeholder="WIFI名称" border="surround" v-model="wifi_info.ssid" />
						</view>
						<view class="flex-col-g8">
							<label class="caption">密码:</label>
							<up-input placeholder="WIFI密码" border="surround" v-model="wifi_info.pwd" />
						</view>
					</view>
					<view class="btn-group mt-20">
						<button class="btn-apple btn-secondary" @tap="showModifyWifi=false">取消</button>
						<button class="btn-apple btn-primary" @tap="confirmModify">确定</button>
					</view>
				</view>
			</up-popup>

			<!-- 重启设备 -->
			<up-modal title="您确定要重启设备吗？" :show="restartShow" showCancelButton @confirm="YesRestart"
				@cancel="restartShow=false" />

			<!-- 恢复出厂设置 -->
			<up-modal title="您确定要恢复出厂设置吗？" :show="recoverShow" showCancelButton @confirm="YesRecover"
				@cancel="recoverShow=false" />

			<!-- 退出登录 -->
			<up-modal title="您确定要退出登录吗？" :show="logoutShow" showCancelButton @confirm="YesLogout"
				@cancel="logoutShow=false" />

			<!-- 添加白名单弹窗 -->
			<up-popup :show="showAddWhitelist" mode="center" @close="showAddWhitelist=false">
				<view class="wifi-popup">
					<view class="title mb-md">添加白名单</view>
					<view class="flex-col-g20">
						<view class="flex-col-g8">
							<label class="caption">姓名:</label>
							<up-input placeholder="请输入姓名" border="surround" v-model="whitelistForm.name" />
						</view>
						<view class="flex-col-g8">
							<label class="caption">手机号:</label>
							<up-input placeholder="请输入手机号" border="surround" v-model="whitelistForm.phone" />
						</view>
					</view>
					<view class="btn-group mt-20">
						<button class="btn-apple btn-secondary" @tap="showAddWhitelist=false">取消</button>
						<button class="btn-apple btn-primary" @tap="confirmAddWhitelist">确定</button>
					</view>
				</view>
			</up-popup>
			<!-- 上传短信码弹窗 -->
			<up-popup :show="showSmsCode" mode="center" @close="showSmsCode=false">
				<view class="wifi-popup">
					<view class="title mb-md">上传短信验证码</view>
					<view class="flex-col-g20">
						<view class="flex-col-g8">
							<label class="caption">手机号: {{smsCodePhone}}</label>
						</view>
						<view class="flex-col-g8">
							<label class="caption">验证码:</label>
							<up-input placeholder="请输入短信验证码" border="surround" v-model="smsCode" />
						</view>
					</view>
					<view class="btn-group mt-20">
						<button class="btn-apple btn-secondary" @tap="showSmsCode=false">取消</button>
						<button class="btn-apple btn-primary" @tap="confirmUploadSmsCode">确定</button>
					</view>
				</view>
			</up-popup>
		</FunctionCard>

		<view class="bottom-spacer"></view>

		<!-- 日期选择器弹窗 -->
		<up-datetime-picker v-if="!userInfo.isDevice" :show="showStartDatePicker" v-model="startDateTimestamp"
			mode="date" @confirm="onStartDateConfirm" @cancel="showStartDatePicker=false"
			@close="showStartDatePicker=false"></up-datetime-picker>
		<up-datetime-picker v-if="!userInfo.isDevice" :show="showEndDatePicker" v-model="endDateTimestamp" mode="date"
			@confirm="onEndDateConfirm" @cancel="showEndDatePicker=false"
			@close="showEndDatePicker=false"></up-datetime-picker>

		<FloatingButton @tap="connectKF" />
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed
	} from 'vue';
	import UserInfoCard from '@/components/UserInfoCard.vue';
	import DeviceStatusCard from '@/components/DeviceStatusCard.vue';
	import VoiceCard from '@/components/VoiceCard.vue';
	import TrafficCard from '@/components/TrafficCard.vue';
	import WhitelistCard from '@/components/WhitelistCard.vue';
	import WifiCard from '@/components/WifiCard.vue';
	import FunctionCard from '@/components/FunctionCard.vue';
	import FloatingButton from '@/components/FloatingButton.vue';
	import { assetApi, deviceApi } from '@/api/index.js';
	import { useUserStore } from '@/store/index.js';

	const userStore = useUserStore();

	let showModifyWifi = ref(false);
	let restartShow = ref(false);
	let recoverShow = ref(false);
	let logoutShow = ref(false);
	let loading = ref(false);

	let userInfo = reactive({
		isDevice: true,
		avatar: ''
	});

	let deviceInfo = reactive({
		battery: 100,
		connect: 0,
		statusStr: '正常',
		expireDate: '',
		currentIccid: '',
		category: '',
		phone: '',
		flowSize: 0,
		totalBytesCnt: 0,
		ssidName: '',
		ssidPwd: '',
		rssi: '强',
		onlineStatus: '0',
		connCnt: 0,
		run_time: 0,
		last_online_time: '',
		lan_ip: '',
		kf_url: '',
		mchList: []
	});

	let isRealName = ref(false);
	let alreadyBindPhone = ref(false);
	let realNameStatus = ref('');
	let wifi_info = reactive({
		ssid: '',
		pwd: ''
	});
	let currentCardNo = ref('');
	let accountName = ref('');
	let voiceCardStatus = reactive({
		cardStatus: '',
		online: '离线'
	});
	let voiceStats = reactive({
		totalVoice: 0,
		usedVoice: 0,
		remainingVoice: 0
	});
	let showStartDatePicker = ref(false);
	let showEndDatePicker = ref(false);
	let startDate = ref('');
	let endDate = ref('');
	let startDateTimestamp = ref(Date.now());
	let endDateTimestamp = ref(Date.now());
	let dateRangeText = ref('');
	let whitelistData = reactive([]);
	let showAddWhitelist = ref(false);
	let whitelistForm = reactive({
		name: '',
		phone: ''
	});
	let showSmsCode = ref(false);
	let smsCodePhone = ref('');
	let smsCode = ref('');

	const loadAssetInfo = async () => {
		const identifier = userStore.state.identifier;
		if (!identifier) return;

		loading.value = true;
		try {
			const data = await assetApi.getInfo(identifier);
			userInfo.isDevice = data.asset_type === 'device';
			currentCardNo.value = data.identifier;
			deviceInfo.statusStr = data.status === 1 ? '正常' : '禁用';
			isRealName.value = data.real_name_status === 1;
			realNameStatus.value = data.real_name_status === 1 ? '已实名' : '未实名';
			deviceInfo.flowSize = data.package_remain_mb || 0;
			deviceInfo.totalBytesCnt = data.package_total_mb || 0;
			deviceInfo.currentIccid = data.identifier;

			if (data.device_realtime) {
				const rt = data.device_realtime;
				deviceInfo.onlineStatus = rt.online_status === 1 ? '1' : '0';
				deviceInfo.battery = rt.battery_level || 100;
				deviceInfo.ssidName = rt.ssid || '';
				deviceInfo.ssidPwd = rt.wifi_password || '';
				deviceInfo.lan_ip = rt.lan_ip || '';
				deviceInfo.connCnt = rt.client_number || 0;
				deviceInfo.run_time = rt.run_time || 0;
				deviceInfo.rssi = rt.rssi || '强';
			}

			if (data.cards && data.cards.length > 0) {
				deviceInfo.mchList = data.cards.map(card => ({
					iccidMark: card.iccid,
					category: card.slot_position
				}));
			}
		} catch (e) {
			console.error('加载资产信息失败', e);
		}
		loading.value = false;
	};

	const modifyWifi = () => {
		wifi_info.ssid = deviceInfo.ssidName;
		wifi_info.pwd = deviceInfo.ssidPwd;
		showModifyWifi.value = true;
	};

	const confirmModify = async () => {
		try {
			await deviceApi.setWifi(
				userStore.state.identifier,
				wifi_info.ssid,
				wifi_info.pwd,
				true
			);
			deviceInfo.ssidName = wifi_info.ssid;
			deviceInfo.ssidPwd = wifi_info.pwd;
			uni.showToast({ title: '修改成功', icon: 'success' });
		} catch (e) {
			console.error('修改WiFi失败', e);
		}
		showModifyWifi.value = false;
	};

	const connectKF = () => uni.showToast({
		title: '正在跳转客服',
		icon: 'none'
	});
	const enterBack = () => uni.showToast({
		title: '正在跳转后台',
		icon: 'none'
	});

	const YesRestart = async () => {
		try {
			await deviceApi.reboot(userStore.state.identifier);
			uni.showToast({ title: '重启指令已发送', icon: 'success' });
		} catch (e) {
			console.error('重启设备失败', e);
		}
		restartShow.value = false;
	};

	const copy = (content) => {
		uni.setClipboardData({
			data: content,
			success: () => uni.showToast({
				title: '复制成功',
				icon: 'none'
			})
		});
	};

	const YesRecover = async () => {
		try {
			await deviceApi.factoryReset(userStore.state.identifier);
			uni.showToast({ title: '恢复出厂设置指令已发送', icon: 'success' });
		} catch (e) {
			console.error('恢复出厂设置失败', e);
		}
		recoverShow.value = false;
	};
	const YesLogout = () => {
		uni.clearStorageSync();
		uni.reLaunch({
			url: '/pages/login/login'
		});
		logoutShow.value = false;
	};

	const onlineStatus = computed(() => {
		if (!userInfo.isDevice) return voiceCardStatus.online || '离线';
		return deviceInfo.onlineStatus === '1' ? '在线' : '离线';
	});

	const initCurrentMonth = () => {
		const now = new Date();
		const year = now.getFullYear();
		const month = String(now.getMonth() + 1).padStart(2, '0');
		startDate.value = `${year}-${month}-01`;
		const lastDay = new Date(year, parseInt(month), 0).getDate();
		endDate.value = `${year}-${month}-${String(lastDay).padStart(2, '0')}`;
		updateDateRangeText();
	};

	const updateDateRangeText = () => {
		if (startDate.value && endDate.value) {
			const [sYear, sMonth, sDay] = startDate.value.split('-');
			const [eYear, eMonth, eDay] = endDate.value.split('-');
			dateRangeText.value = `${sYear}-${sMonth}-${sDay} 至 ${eYear}-${eMonth}-${eDay}`;
		}
	};

	const openDateRangePicker = () => {
		if (startDate.value) startDateTimestamp.value = new Date(startDate.value).getTime();
		showStartDatePicker.value = true;
	};

	const onStartDateConfirm = (e) => {
		const date = new Date(e.value);
		startDate.value =
			`${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
		showStartDatePicker.value = false;
		setTimeout(() => {
			if (endDate.value) endDateTimestamp.value = new Date(endDate.value).getTime();
			else endDateTimestamp.value = e.value;
			showEndDatePicker.value = true;
		}, 300);
	};

	const onEndDateConfirm = (e) => {
		const date = new Date(e.value);
		endDate.value =
			`${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
		showEndDatePicker.value = false;
		if (new Date(startDate.value) > new Date(endDate.value)) {
			uni.showToast({
				title: '开始日期不能大于结束日期',
				icon: 'none'
			});
			return;
		}
		updateDateRangeText();
	};

	const refreshWhitelist = () => uni.showToast({
		title: '刷新成功',
		icon: 'success'
	});

	const showAddWhitelistDialog = () => {
		whitelistForm.name = '';
		whitelistForm.phone = '';
		showAddWhitelist.value = true;
	};

	const confirmAddWhitelist = () => {
		if (!whitelistForm.name || !whitelistForm.phone) {
			uni.showToast({
				title: '请输入姓名和手机号',
				icon: 'none'
			});
			return;
		}
		const phoneReg = /^1[3-9]\d{9}$/;
		if (!phoneReg.test(whitelistForm.phone)) {
			uni.showToast({
				title: '请输入正确的手机号',
				icon: 'none'
			});
			return;
		}
		whitelistData.push({
			name: whitelistForm.name,
			phone: whitelistForm.phone,
			state: '1',
			createTime: new Date().toISOString().split('T')[0]
		});
		uni.showToast({
			title: '添加成功',
			icon: 'none'
		});
		showAddWhitelist.value = false;
	};

	const showSmsCodeDialog = (phone, state) => {
		if (state !== '5' && state !== '3') {
			uni.showToast({
				title: '当前状态无需上传短信验证码',
				icon: 'none'
			});
			return;
		}
		smsCodePhone.value = phone;
		smsCode.value = '';
		showSmsCode.value = true;
	};

	const confirmUploadSmsCode = () => {
		if (!smsCode.value) {
			uni.showToast({
				title: '请输入短信验证码',
				icon: 'none'
			});
			return;
		}
		uni.showToast({
			title: '操作成功',
			icon: 'success'
		});
		showSmsCode.value = false;
	};

	const onSync = () => {
		uni.showToast({ title: '同步成功', icon: 'success' });
	};

	const enterDetail = (name) => {
		switch (name) {
			case 'package-order':
				uni.navigateTo({
					url: '/pages/package-order/package-order'
				});
				break;
			case 'order-list':
				uni.navigateTo({
					url: '/pages/order-list/order-list'
				});
				break;
			case 'back':
				enterBack();
				break;
			case 'switch':
				uni.navigateTo({
					url: '/pages/switch/switch'
				});
				break;
			case 'asset-package':
				uni.navigateTo({
					url: '/pages/asset-package-history/asset-package-history'
				});
				break;
			case 'bind':
				uni.navigateTo({
					url: '/pages/bind/bind'
				});
				break;
			case 'change-phone':
				uni.navigateTo({
					url: '/pages/change-phone/change-phone'
				});
				break;
			case 'device-exchange':
				uni.navigateTo({
					url: '/pages/device-exchange/device-exchange'
				});
				break;
			case 'wallet':
				uni.navigateTo({
					url: '/pages/my-wallet/my-wallet'
				});
				break;
			case 'authentication':
				uni.navigateTo({
					url: '/pages/auth/auth'
				});
				break;
			case 'recover':
				restartShow.value = true;
				break;
			case 'restart':
				restartShow.value = true;
				break;
			case 'out':
				logoutShow.value = true;
				break;
		}
	};

	onMounted(() => {
		initCurrentMonth();
		loadAssetInfo();
	});
</script>

<style scoped lang="scss">
	.wifi-popup {
		width: 600rpx;
		padding: 30rpx;

		.title {
			font-size: 32rpx;
			font-weight: 600;
			color: var(--text-primary);
		}
	}

	.bottom-spacer {
		height: 120rpx;
	}
</style>