<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<wd-navbar :bordered="false" custom-style="background: #ffffff;" safeAreaInsetTop fixed placeholder>
			<template #left>
				<view class="li-ml-15 li-mt-10 li-flex li-items-center">
					<text v-if="hasMultiplePages" class="ri-arrow-left-s-line li-text-70"
						@click="toPages({type:'nav'})"></text>
					<text v-if="!hasMultiplePages" class="ri-home-5-line li-text-55 li-mb-8 li-mr-10"
						@click="toPages({type:'home'})"></text>
					<text class="li-text-42">设置</text>
				</view>
			</template>
		</wd-navbar>

		<view class="content">
			<!-- 设置选项列表 -->
			<view class="section">
				<view class="setting-item" @click="handleEditInfo">
					<view class="left">
						<text class="ri-user-3-line icon"></text>
						<text class="title">个人信息</text>
					</view>
					<text class="ri-arrow-right-s-line arrow"></text>
				</view>

				<view class="setting-item" @click="clearCache">
					<view class="left">
						<text class="ri-delete-bin-6-line icon"></text>
						<text class="title">清除缓存</text>
					</view>
					<text class="value">{{cacheSize}}</text>
				</view>
			</view>

			<view class="section">
				<view class="setting-item" @click="handlePrivacyPolicy">
					<view class="left">
						<text class="ri-lock-line icon"></text>
						<text class="title">隐私政策</text>
					</view>
					<text class="ri-arrow-right-s-line arrow"></text>
				</view>

				<view class="setting-item" @click="handleUserAgreement">
					<view class="left">
						<text class="ri-file-list-3-line icon"></text>
						<text class="title">用户协议</text>
					</view>
					<text class="ri-arrow-right-s-line arrow"></text>
				</view>

				<view class="setting-item" @click="checkUpdate">
					<view class="left">
						<text class="ri-information-line icon"></text>
						<text class="title">关于我们</text>
					</view>
					<view class="right">
						<text class="version">{{appVersion}}</text>
						<text class="ri-arrow-right-s-line arrow"></text>
					</view>
				</view>
			</view>

			<!-- 退出登录按钮 -->
			<view class="logout-wrap">
				<button class="logout-btn" @click="handleLogout">退出登录</button>
			</view>
		</view>


		<wd-message-box />
		<wd-toast />
	</view>
	<zero-loading type="wobble" v-if="loading"></zero-loading>
</template>

<script setup lang="ts">
	import { logout } from '@/api/login'
	import { ref, reactive, onMounted } from 'vue';
	import { useNavigation } from '@/hooks/useNavigation';
	import { onLoad } from '@dcloudio/uni-app'
	import { useMessage } from '@/uni_modules/wot-design-uni'
	import { useToast } from '@/uni_modules/wot-design-uni';

	const Toast = useToast();
	const message = useMessage()

	// 使用导航 composable
	const {
		hasMultiplePages,   // 是否有多个页面在路由栈中
		isTabBarPage,       // 当前页面是否为 tabBar 页面
		checkRouteStack     // 检查当前路由栈状态的方法
	} = useNavigation()
	const loading = ref<boolean>(false)


	// 缓存大小
	const cacheSize = ref('获取中...');

	// 应用版本
	const appVersion = ref('v1.0.0');


	/**
	 * 格式化手机号码为带星号格式
	 */
	const formatPhone = (phone) => {
		if (!phone) return '';
		return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
	};

	// 页面跳转
	const toPages = ({ type }) => {
		if (type === 'nav') {
			uni.navigateBack()
		} else if (type === 'home') {
			uni.switchTab({
				url: '/pages/index/index'
			})
		}
	}

	/**
	 * 处理修改用户信息
	 */
	const handleEditInfo = () => {
		uni.navigateTo({
			url: '/pagesB/setting/editInfo'
		});
	};

	/**
	 * 获取缓存大小
	 */
	const getCacheSize = () => {
		// #ifdef APP-PLUS
		try {
			plus.cache.calculate(size => {
				const sizeInMB = (size / (1024 * 1024)).toFixed(1);
				cacheSize.value = size > 0 ? sizeInMB + 'MB' : '0KB';
			});
		} catch (e) {
			// 如果获取缓存失败，显示默认值
			console.error('获取APP缓存大小失败:', e);
			cacheSize.value = '0KB';
		}
		// #endif

		// #ifdef MP
		try {
			uni.getStorageInfo({
				success: (res) => {
					const size = res.currentSize;
					if (size <= 0) {
						cacheSize.value = '0KB';
					} else if (size < 1024) {
						cacheSize.value = size + 'KB';
					} else {
						cacheSize.value = (size / 1024).toFixed(1) + 'MB';
					}
				},
				fail: (err) => {
					console.error('获取小程序缓存大小失败:', err);
					cacheSize.value = '0KB';
				},
				complete: () => {
					// 如果30秒后还是"获取中..."状态，则置为0KB
					setTimeout(() => {
						if (cacheSize.value === '获取中...') {
							cacheSize.value = '0KB';
						}
					}, 3000);
				}
			});
		} catch (e) {
			console.error('获取缓存异常:', e);
			cacheSize.value = '0KB';
		}
		// #endif

		// #ifdef H5
		try {
			// 计算localStorage大小（粗略估计）
			let size = 0;
			for (let key in localStorage) {
				if (localStorage.hasOwnProperty(key)) {
					size += localStorage[key].length * 2; // UTF-16 字符占用2字节
				}
			}

			if (size <= 0) {
				cacheSize.value = '0KB';
			} else if (size < 1024) {
				cacheSize.value = size + 'B';
			} else if (size < 1048576) { // 1024 * 1024
				cacheSize.value = (size / 1024).toFixed(1) + 'KB';
			} else {
				cacheSize.value = (size / 1048576).toFixed(1) + 'MB';
			}
		} catch (e) {
			console.error('获取H5缓存大小失败:', e);
			cacheSize.value = '0KB';
		}
		// #endif
	}

	/**
	 * 清除缓存
	 */
	const clearCache = () => {
		message.alert({
			msg: '清除缓存需重新登录，请谨慎操作！',
			title: '提示',
			type: 'confirm',
		})
			.then(() => {
				clearAll()
			})
	};

	const clearAll = () => {
		uni.showLoading({
			title: '清理中...'
		});
		// #ifdef APP-PLUS
		try {
			plus.cache.clear(() => {
				uni.hideLoading();
				cacheSize.value = '0KB';
				Toast.success('缓存已清理')
			}, err => {
				console.error('清理APP缓存失败:', err);
				uni.hideLoading();
				Toast.error('清理失败')
			});
		} catch (e) {
			console.error('清理缓存异常:', e);
			uni.hideLoading();
			Toast.error('清理失败')
		}
		// #endif

		// #ifdef MP
		try {
			uni.clearStorageSync();
			setTimeout(() => {
				uni.hideLoading();
				cacheSize.value = '0KB';
				Toast.success('缓存已清理')
			}, 500);
		} catch (e) {
			console.error('清理小程序缓存失败:', e);
			uni.hideLoading();
			Toast.error('清理失败')
		}
		// #endif

		// #ifdef H5
		try {
			localStorage.clear();
			setTimeout(() => {
				uni.hideLoading();
				cacheSize.value = '0KB';
				Toast.success('缓存已清理')
			}, 500);
		} catch (e) {
			uni.hideLoading();
			Toast.error('清理失败')
		}
		// #endif
		confirmLogout()
	}

	/**
	 * 查看隐私政策
	 */
	const handlePrivacyPolicy = () => {
		uni.navigateTo({
			url: '/pagesB/agreement/index?type=2'
		});
	};

	/**
	 * 查看用户协议
	 */
	const handleUserAgreement = () => {
		uni.navigateTo({
			url: '/pagesB/agreement/index?type=1'
		});
	};

	/**
	 * 检查更新
	 */
	const checkUpdate = () => {
		// uni.showToast({
		// 	title: '当前已是最新版本',
		// 	icon: 'none'
		// });
		Toast.success('当前已是最新版本')
	};

	/**
	 * 显示退出登录确认框
	 */
	const handleLogout = () => {
		message.alert({
			msg: '确定退出吗?',
			title: '退出登录',
			type: 'confirm',
		})
			.then(() => {
				confirmLogout()
				uni.showLoading({
					title: '退出中...'
				})
			})
	};

	/**
	 * 确认退出登录
	 */
	const confirmLogout = async () => {
		// loading.value = true

		const res = await logout()
		if (res.code == 200) {
			uni.hideLoading()
			uni.removeStorageSync('token');
			uni.removeStorageSync('userInfo');
			uni.reLaunch({
				url: '/pages/login/index'
			});
		}
	};

	onMounted(() => {
		checkRouteStack();

		// 获取缓存大小
		getCacheSize();

		// 获取应用版本
		// #ifdef APP-PLUS
		plus.runtime.getProperty(plus.runtime.appid, (res) => {
			appVersion.value = 'v' + res.version;
		});
		// #endif
	});
</script>

<style lang="scss">
	page {
		background-color: #f5f7fa;
	}

	.content {
		padding: 28rpx 32rpx 120rpx;
	}

	.section {
		background-color: #ffffff;
		border-radius: 18rpx;
		margin-bottom: 28rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
	}

	.setting-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 34rpx 32rpx;
		position: relative;

		&:not(:last-child)::after {
			content: '';
			position: absolute;
			left: 32rpx;
			right: 32rpx;
			bottom: 0;
			height: 1px;
			background-color: #f0f2f5;
			transform: scaleY(0.5);
		}

		&:active {
			background-color: #f8f9fa;
		}

		.left {
			display: flex;
			align-items: center;

			.icon {
				font-size: 42rpx;
				margin-right: 24rpx;
				color: #3370ff;
				opacity: 0.85;
			}

			.title {
				font-size: 30rpx;
				color: #333333;
				font-weight: 450;
				letter-spacing: 0.5rpx;
			}
		}

		.arrow {
			color: #c0c0c0;
			font-size: 34rpx;
		}

		.value {
			font-size: 28rpx;
			color: #999999;
		}

		.right {
			display: flex;
			align-items: center;

			.version {
				font-size: 28rpx;
				color: #999999;
				margin-right: 12rpx;
			}
		}
	}

	.logout-wrap {
		padding: 60rpx 40rpx;

		.logout-btn {
			width: 100%;
			height: 90rpx;
			line-height: 90rpx;
			background: linear-gradient(135deg, #398CFF 0%, #2170E8 100%);
			color: #ffffff;
			font-size: 32rpx;
			font-weight: 500;
			border-radius: 45rpx;
			border: none;
			box-shadow: 0 4rpx 12rpx rgba(57, 140, 255, 0.3);
			transition: all 0.3s ease;

			&:active {
				transform: scale(0.98);
				box-shadow: 0 2rpx 8rpx rgba(57, 140, 255, 0.2);
				opacity: 0.9;
			}
		}
	}

	.dialog-content {
		padding: 30rpx;
		text-align: center;
		font-size: 28rpx;
		color: #333;
		line-height: 1.5;
	}
</style>