<template>
	<view class="settings-page">
		<upload-app-vue :isHome="false" ref="uploadApp"></upload-app-vue>
		<!-- 顶部导航栏 -->
		<custom-navbar title="设置" :showBack="true"></custom-navbar>

		<!-- 内容区域 -->
		<view class="content">
			<!-- 账户安全 -->
			<view class="section-list">
				<view class="list-item" @click="navigateTo('/pages/settings/password')">
					<view class="item-left flex-row-center">
						<image class="item-left-img"
							src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/82abd15d-eb6f-423c-be25-4f71d32dfcbb.png">
						</image>
						<text class="item-text">修改密码</text>
					</view>
					<image
						src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/34d8b914-58bd-46d7-9d88-08ed446f26c4.png"
						class="arrow-right" mode="aspectFit"></image>
				</view>

				<view class="list-item">
					<view class="item-left flex-row-center">
						<image class="item-left-img"
							src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/8c69954f-9b73-4493-ab8d-5bd3d4951313.png">
						</image>
						<text class="item-text">绑定手机</text>
					</view>
					<view class="item-right">
						<image src="/static/images/sign-green.png" class="sign-icon" mode="aspectFit"></image>
						<text class="phone-number">{{account}}</text>
						<image
							src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/34d8b914-58bd-46d7-9d88-08ed446f26c4.png"
							class="arrow-right" mode="aspectFit"></image>
					</view>
				</view>

				<view class="list-item" @click="navigateTo('/pages/agreement/agreement?type=4')">
					<view class="item-left flex-row-center">
						<image class="item-left-img"
							src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/e42a5659-88e1-47dd-82a9-f0d08fcd7382.png">
						</image>
						<text class="item-text">隐私政策</text>
					</view>
					<image
						src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/34d8b914-58bd-46d7-9d88-08ed446f26c4.png"
						class="arrow-right" mode="aspectFit"></image>
				</view>

				<view class="list-item" @click="navigateTo('/pages/agreement/agreement?type=3')">
					<view class="item-left flex-row-center">
						<image class="item-left-img"
							src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/5278dec3-c0b0-44c3-b099-e0d9253b8afe.png">
						</image>
						<text class="item-text">用户协议</text>
					</view>
					<image
						src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/34d8b914-58bd-46d7-9d88-08ed446f26c4.png"
						class="arrow-right" mode="aspectFit"></image>
				</view>

				<view class="list-item" @click="deleteAccount">
					<view class="item-left flex-row-center">
						<image class="item-left-img"
							src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/d12d5407-0db9-4f3a-96c9-7df4def364cd.png">
						</image>
						<text class="item-text">注销账号</text>
					</view>
					<image
						src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/34d8b914-58bd-46d7-9d88-08ed446f26c4.png"
						class="arrow-right" mode="aspectFit"></image>
				</view>

				<view class="list-item" @click="navigateTo('/pages/message/settings')">
					<view class="item-left flex-row-center">
						<image class="item-left-img"
							src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/94382bb8-2819-4710-aa65-f615e49c7cf6.png">
						</image>
						<text class="item-text">消息通知</text>
					</view>
					<view class="item-right">
						<text class="cache-size">订单、优惠通知等</text>
						<image
							src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/34d8b914-58bd-46d7-9d88-08ed446f26c4.png"
							class="arrow-right" mode="aspectFit"></image>
					</view>
				</view>

				<view class="list-item" @click="clearStorage">
					<view class="item-left flex-row-center">
						<image class="item-left-img"
							src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/5b7919c1-14a8-4b87-ba06-86cbb413228b.png">
						</image>
						<text class="item-text">清除缓存</text>
					</view>
					<view class="item-right">
						<text class="cache-size">{{ cacheSize }}</text>
						<image
							src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/34d8b914-58bd-46d7-9d88-08ed446f26c4.png"
							class="arrow-right" mode="aspectFit"></image>
					</view>
				</view>

				<view class="list-item" @click="uploadApp">
					<view class="item-left flex-row-center">
						<image class="item-left-img"
							src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/c6f188af-abbf-47be-b1b9-c6622470eadd.png">
						</image>
						<text class="item-text">检查更新</text>
					</view>
					<view class="item-right">
						<text class="version">{{version_number}}</text>
						<image
							src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/34d8b914-58bd-46d7-9d88-08ed446f26c4.png"
							class="arrow-right" mode="aspectFit"></image>
					</view>
				</view>
			</view>
			<!-- 退出登录按钮 -->
			<view class="logout-btn" @click="logout">
				<text class="logout-text">退出登录</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		unRegisterPush
	} from '@/uni_modules/TencentCloud-Push';
	import request from '../../utils/request'
	import uploadApp from '../../utils/uploadApp'
	export default {
		data() {
			return {
				statusBarHeight: 0,
				account: '',
				version_number: '',
				cacheSize: '0 MB',
				systemInfo: {}
			}
		},
		async onLoad() {
			this.systemInfo = await uni.getSystemInfoSync();
			this.getCache()
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight
			// 获取用户信息
			this.getUserInfo();
			this.getVersionNum();
		},
		methods: {
			async getCache() {
				if (this.systemInfo.platform == 'h5') {
					return
				}
				let that = this
				// 计算缓存大小
				plus.cache.calculate(function(size) {
					// 格式化缓存大小
					let formattedSize;
					if (size < 1024) {
						formattedSize = size + " B";
					} else if (size < 1024 * 1024) {
						formattedSize = (size / 1024).toFixed(2) + " KB";
					} else if (size < 1024 * 1024 * 1024) {
						formattedSize = (size / (1024 * 1024)).toFixed(2) + " MB";
					} else {
						formattedSize = (size / (1024 * 1024 * 1024)).toFixed(2) + " GB";
					}
					that.cacheSize = formattedSize
					console.log("当前缓存大小为: " + formattedSize);
				}, function(error) {
					console.error("计算缓存大小失败: ", error);
				});
			},
			getUserInfo() {
				request.post('/user/getuser', {
					type: 1
				}).then(result => {
					console.log('result', result)
					this.account = this.formatPhone(result.data.account);

				})
			},
			getVersionNum() {
				// 获取当前app的版本
				const systemInfo = uni.getSystemInfoSync();
				// 应用程序版本号
				// 条件编译，只在APP渲染
				// #ifdef APP
				this.version_number = systemInfo.appWgtVersion;
				// #endif
				// #ifdef H5
				this.version_number = systemInfo.appVersion;
				console.log(systemInfo.appVersion, '版本号');
				// #endif
				// #ifdef MP-WEIXIN
				const accountInfo = uni.getAccountInfoSync();
				this.version_number = accountInfo.miniProgram.version // 小程序 版本号
				console.log(accountInfo.miniProgram.version, '小程序版本号')
				// #endif
			},
			// 检查版本自动更新
			// getUpdateInfo() {
			//   return new Promise(async (resolve, reject) => {
			//     const systemInfo = await uni.getSystemInfoSync();
			//     // 获取手机型号
			//     const deviceBrand = systemInfo.deviceBrand;
			//     console.log('deviceBrand',deviceBrand)
			//     let type = deviceBrand == 'apple' ? '1' : deviceBrand == 'huawei' ? '2' : deviceBrand == 'honor' ? '3' : deviceBrand == 'xiaomi' ? '4' : deviceBrand == 'oppo' ? '5' : deviceBrand == 'vivo' ? '6' : '';
			//     const response = await request.post('/user/getappversion',{type});
			//     console.log(response)
			// 	resolve({
			// 	  version: response.data.version,
			// 	  downloadUrl: response.data.url // APK下载地址
			// 	})
			//   })
			// },
			// installApp(downloadUrl) {
			//   console.log(downloadUrl)
			//   // 下载APK
			//   const downloadTask = uni.downloadFile({
			//     url: 'https://app.mrrweb.com.cn/mrrapp.com.1.1.4.apk',
			//     success: (downloadResult) => {
			// 		console.log('downloadResult',downloadResult)
			//       if (downloadResult.statusCode === 200) {
			//         // 安装APK
			//         plus.runtime.install(downloadResult.tempFilePath, {
			//           force: false
			//         }, () => {
			//           console.log('安装成功')
			// 		  // plus.runtime.restart();
			//         }, (err) => {
			// 			console.log('err',err)
			//           uni.showToast({ title: '安装失败', icon: 'none' })
			//         })
			//       }
			//     },
			// 	fail(err) {
			//     	console.log('err',err)
			//     }
			//   })

			//   // 监听下载进度
			//   downloadTask.onProgressUpdate((res) => {
			//     console.log('下载进度:', res.progress)

			//   })
			// },
			// showUpdateDialog(updateInfo) {
			//   uni.showModal({
			//     title: `发现新版本`,
			//     content: '是否更新最新版本？',
			//     confirmText: '立即更新',
			//     cancelText: '稍后再说',
			//     success: (res) => {
			//       if (res.confirm) {
			//         // #ifdef APP-PLUS
			//         if (plus.os.name === 'iOS') {
			//           plus.runtime.openURL(updateInfo.downloadUrl)
			//         } else {
			//           this.installApp(updateInfo.downloadUrl)
			//         }
			//         // #endif
			//       }
			//     }
			//   })
			// },
			async uploadApp() {

				try {
					this.$refs.uploadApp.uploadApp('setting')
				} catch (error) {
					console.error('检查更新失败:', error)
					uni.showToast({
						title: '检查更新失败',
						icon: 'none'
					})
				}
			},

			formatPhone(phone) {
				if (typeof phone == 'number') {
					phone = phone.toString();
				}
				return phone.substr(0, 3) + '****' + phone.substr(7, 11)
			},
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 页面导航
			navigateTo(url) {
				uni.navigateTo({
					url
				})
			},
			//清除所有本地存储数据，但「保留指定 key」
			async clearAllExceptSpecified(keysToKeep = ['setVersion', 'searchCity', 'userAdrees', 'startLocate',
				'isLocation'
			]) {
				let keepData = {};

				try {
					// 第一步：取出并保存要保留的本地存储数据
					for (let key of keysToKeep) {
						try {
							let data = await uni.getStorageSync(key);
							keepData[key] = data; // 暂存值
						} catch (err) {
							keepData[key] = null; // 若key不存在，暂存为null
						}
					}

					// 第二步：全量清除所有本地存储数据
					await uni.clearStorage();

					// 第三步：重新存入保留的本地存储数据
					for (let key of keysToKeep) {
						if (keepData[key] !== null) {
							await uni.setStorageSync(key, keepData[key]);
						}
					}

					console.log('已清除所有缓存，保留指定key');
					
					// #ifdef APP-PLUS
					unRegisterPush(
						// 成功回调
						(res) => {
							console.log('反注册推送成功', res);
							// 清理本地存储的推送token（可选，建议做）
						},
						// 失败回调
						(err) => {
							console.error('反注册推送失败', err);
						}
					);
					// #endif
					
				} catch (err) {
					console.error('操作失败：', err);
				}
			},
			async clearStorage() {
				let that = this
				await uni.showModal({
					title: '提示',
					content: '确定要清除缓存吗？',
					success: async (res) => {
						if (res.confirm) {

							// TODO: 实现清楚缓存逻辑
							plus.cache.clear(function() {
								uni.showToast({
									title: "清除成功",
									icon: "none"
								});
								this.cacheSize = "0 MB"; // 清理后重置缓存显示
							}.bind(this)); // 绑定this指向页面实例
						}
					}
				})
			},
			async deleteAccount() {
				let that = this
				await uni.showModal({
					title: '提示',
					content: '本次注销将要停止使用美融融所有权力，请确认您没有未完成的订单，检查账户余额，是否注销？',
					success: async (res) => {
						if (res.confirm) {

							// TODO: 实现注销账号逻辑
							request.post('/user/cancellation').then(res => {
								if (res.state == 1) {
									that.clearAllExceptSpecified();
									uni.reLaunch({
										url: '/pages/my/my'
									})
								}
							})
						}
					}
				})
			},
			// 退出登录
			async logout() {
				let that = this
				await uni.showModal({
					title: '提示',
					content: '确定要退出登录吗？',
					success: async (res) => {
						if (res.confirm) {
							// uni.removeStorageSync('access_token');
							// uni.removeStorageSync('refresh_token');
							// uni.clearStorageSync();
							await that.clearAllExceptSpecified();
							// TODO: 实现退出登录逻辑
							uni.reLaunch({
								url: '/pages/my/my'
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="less">
	.content {
		border-top: 1rpx solid rgba(0, 0, 0, 0.05);
	}

	.section-list {
		background-color: #FFFFFF;
		margin: 20rpx 20rpx 0 20rpx;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.list-item {
		padding: 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1rpx solid #F5F5F5;
	}

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

	.item-left {
		gap: 16rpx;

		.item-left-img {
			width: 36rpx;
			height: 36rpx;
		}

		.item-text {
			font-weight: 500;
			font-size: 28rpx;
			color: #000000;
			text-align: left;
			font-style: normal;
		}
	}



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

	.phone-number {
		font-size: 28rpx;
		color: #666666;
		margin-left: 8rpx;
		margin-right: 12rpx;
	}

	.verified-icon {
		color: #00C853;
		margin-right: 8rpx;
	}

	.cache-size,
	.version {
		font-weight: 400;
		font-size: 26rpx;
		color: #666666;
		line-height: 37rpx;
		margin-right: 10rpx;
	}

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

	.logout-btn {
		height: 98rpx;
		background-color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 48rpx 20rpx;
		border-radius: 20rpx;
	}

	.logout-text {
		font-weight: 500;
		font-size: 30rpx;
		color: #333333;
		line-height: 42rpx;
	}

	.sign-icon {
		width: 30rpx;
		height: 30rpx;
	}

	.arrow-right {
		width: 10rpx;
		height: 18rpx;
	}

	/* 平台适配 */
	/* #ifdef H5 */
	.nav-bar {
		padding-top: 0 !important;
	}

	/* #endif */

	/* #ifdef MP-WEIXIN */
	.nav-bar {
		padding-top: calc(var(--status-bar-height) + constant(safe-area-inset-top)) !important;
		padding-top: calc(var(--status-bar-height) + env(safe-area-inset-top)) !important;
	}

	/* #endif */
</style>