<template>
	<view class="content">
		<!-- 导航栏 -->
		<!-- 顶部导航栏 -->
		<uni-nav-bar
			left-icon="left"
			title="设置与帮助"
			@clickLeft="goBack"
			fixed
			color="#8B2316"
			height="180rpx"
			:border="false"
			backgroundColor="#eeeeee"
		></uni-nav-bar>
		
		
		
		<!-- 设置选项列表 -->
		<view class="settings-list">
			<!-- #ifdef APP -->
			<!-- 消息通知 -->
			<view class="setting-item" @click="toggleNotification">
				<text class="setting-text">消息通知</text>
				<view class="setting-right">
					<text class="setting-status">{{notice_on?'已':'未'}}开启</text>
					
				</view>
			</view>
			<!-- #endif -->
			<!-- 修改登录密码 -->
			<view class="setting-item" @click="goToChangePassword">
				<text class="setting-text">修改登录密码</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
			
			<!-- 更换手机号 -->
			<view class="setting-item" @click="goToChangeMobile">
				<text class="setting-text">更换手机号</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
			<!-- #ifdef APP -->
			<!-- 版本更新 -->
			<view class="setting-item" @click="checkUpdate">
				<text class="setting-text">版本更新</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
			<!-- #endif -->
			<!-- 关于肝胆相照 -->
			<view class="setting-item" @click="goToPage('https://doc.igandan.com/app/html/about/2017/about2.html')">
				<text class="setting-text">关于肝胆相照</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>

			<!-- 分享肝胆相照APP -->
			<view class="setting-item" @click="shareToggle">
				<text class="setting-text">分享肝胆相照APP</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>

			<!-- 肝胆相照直播群 -->
			<view class="setting-item" @click="goToPage('https://wx.igandan.com/qun/gdxzqun')">
				<text class="setting-text">肝胆相照直播群</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
			
			<!-- 微信关联 -->
			<view class="setting-item" @click="goToWechatLink">
				<text class="setting-text">微信关联</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
			<!-- #ifdef APP -->
			<!-- 清除缓存 -->
			<view class="setting-item" @click="clearCache">
				<text class="setting-text">清除缓存</text>
				<view class="setting-right">
					<text class="cache-size">{{fileSizeString}}</text>
					<uni-icons type="right" size="20" color="#999"></uni-icons>
				</view>
			</view>
			<!-- #endif -->
			<!-- 意见反馈 -->
			<view class="setting-item" @click="goToFeedback">
				<text class="setting-text">意见反馈</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
			
			<!-- 注销账户 -->
			<view class="setting-item" @click="goToDeleteAccount">
				<text class="setting-text">注销账户</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
			
			<!-- 注册协议 -->
			<view class="setting-item" @click="goToPage('https://doc.igandan.com/app/integral/expert_zcxy.html')">
				<text class="setting-text">注册协议</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
			
			<!-- 隐私政策 -->
			<view class="setting-item" @click="goToPage('https://doc.igandan.com/app/integral/permission_expert.html')">
				<text class="setting-text">隐私政策</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
		</view>
		
		<!-- 退出登录按钮 -->
		<view class="logout-section">
			<button class="logout-btn" @click="logout">退出登录</button>
		</view>
		
		<view>
			<!-- 分享弹窗 -->
			<uni-popup ref="shareRef" type="bottom" safeArea backgroundColor="#fff">
				<view class="share-popup">
					<view class="share-title">分享到</view>
					<view class="share-content">
						<view class="share-item" @click="shareToWechat">
							<view class="share-icon wechat-icon">
								<text class="share-icon-text">微</text>
							</view>
							<text class="share-text">微信</text>
						</view>
						<view class="share-item" @click="shareToMoments">
							<view class="share-icon moments-icon">
								<text class="share-icon-text">朋</text>
							</view>
							<text class="share-text">朋友圈</text>
						</view>
						<view class="share-item" @click="shareToWeibo">
							<view class="share-icon weibo-icon">
								<text class="share-icon-text">微</text>
							</view>
							<text class="share-text">新浪微博</text>
						</view>
					</view>
					<view class="share-cancel" @click="closeShare">
						<text>取消</text>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script setup>
	import { ref } from 'vue';
	import {
		onShow
	} from "@dcloudio/uni-app";
	import my_api from '@/api/my_api.js'
	const notice_on = ref(false)
	
	const fileSizeString = ref("0B")
	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};
	
	// 切换消息通知
	const toggleNotification = () => {
		// 实现消息通知开关逻辑
		uni.showToast({
			title: '消息通知设置',
			icon: 'none'
		});
	};
	
	 const formatSize = () => {
		plus.cache.calculate(function(size) {  
			let sizeCache = parseInt(size);  
			if (sizeCache == 0) {  
				fileSizeString.value = "0B";  
			} else if (sizeCache < 1024) {  
				fileSizeString.value = sizeCache + "B";  
			} else if (sizeCache < 1048576) {  
				fileSizeString.value = (sizeCache / 1024).toFixed(2) + "KB";  
			} else if (sizeCache < 1073741824) {  
				fileSizeString.value = (sizeCache / 1048576).toFixed(2) + "MB";  
			} else {  
				fileSizeString.value = (sizeCache / 1073741824).toFixed(2) + "GB";  
			}  
		});  
	}
				
	const isNoticeOn = () => {
	    // #ifdef APP-PLUS  
	    if (plus.os.name == "Android") {  
	        var main = plus.android.runtimeMainActivity();  
	        var NotificationManagerCompat = plus.android.importClass("android.support.v4.app.NotificationManagerCompat");  
	        if (NotificationManagerCompat == null) {  
	            NotificationManagerCompat = plus.android.importClass("androidx.core.app.NotificationManagerCompat");  
	        }  
	        var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();  
			notice_on.value = areNotificationsEnabled
	        return areNotificationsEnabled;  
	    } else if (plus.os.name == "iOS") {  
	        var isIosOn = undefined;  
	        var types = 0;  
	        var app = plus.ios.invoke("UIApplication", "sharedApplication");  
	        var settings = plus.ios.invoke(app, "currentUserNotificationSettings");  
	        if (settings) {  
	            types = settings.plusGetAttribute("types");  
	            plus.ios.deleteObject(settings);  
	        } else {  
	            types = plus.ios.invoke(app, "enabledRemoteNotificationTypes");  
	        }  
	        plus.ios.deleteObject(app);  
	        isIosOn = 0 != types;  
			notice_on.value = isIosOn
	        return isIosOn;  
	    }  
	    // #endif  
	}  
	
	const goToPage = (url) => {
		uni.navigateTo({
				url: '/pages/webview/webview?url=' + url
			});
	};
	// 跳转到修改密码页面
	const goToChangePassword = () => {
		uni.navigateTo({
			url: '/pages_app/changePassword/index'
		});
	};
	
	// 跳转到更换手机号页面
	const goToChangeMobile = () => {
		uni.navigateTo({
			url: '/pages_app/changeMobile/changeMobile'
		});
	};
	
	// 检查版本更新
	const checkUpdate = () => {
		// #ifdef APP-PLUS
		plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
			console.log('App 名称:', widgetInfo.name);
			console.log('App 版本号 (version):', widgetInfo.version); // 如：1.0.0
			console.log('App 版本代码 (versionCode):', widgetInfo.versionCode); // 数字，如：100
		});

		my_api.checkVersion().then(res=>{
			console.log(res)
		}).catch(err=>{
			console.log(err)
			if(err.data.code === 80002){
				if(err.data.data.apk_path){
					appdownLoad(err.data.data.apk_path)
				}else{
					uni.showToast({
						title: err.data.msg || '当前版本已是最新版本',
						icon: 'none'
					})
				}
			}
		})
		// #endif
	};
	
	//执行下载app
const appdownLoad = (url) => {
	uni.showLoading({
		title: '安装包下载中……'
	})
	const downloadTask = uni.downloadFile({
		url: url, //服务器 app 的下载地址
		success: (downloadResult) => {
			uni.hideLoading();
			console.log(downloadResult)
			if (downloadResult.statusCode === 200) {
				uni.showModal({
					title: '',
					content: '下载成功，是否允许安装新版本？',
					confirmText: '确定',
					success: function(res) {
						if (res.confirm == true) {
							plus.runtime.install( //安装
								downloadResult.tempFilePath, {
									force: true
								},
								function(res) {
									utils.showToast('更新成功，重启中');
									plus.runtime.restart();
								}
							);
						}
					}
				});
			}
		}
	});
}

	// 跳转到关于页面
	const goToAbout = () => {
		uni.showToast({
			title: '关于肝胆相照',
			icon: 'none'
		});
	};
	
	const shareRef = ref()
	// 分享APP
	const shareToggle = () => {
		shareRef.value.open()
	}
	
	// 关闭分享弹窗
	const closeShare = () => {
		shareRef.value.close()
	}
	
	// 分享到微信
	const shareToWechat = () => {
		// #ifdef APP-PLUS
		// 使用系统分享

		uni.share({
			provider: "weixin",
			scene: "WXSceneSession",
			type: 1,
			summary: "肝胆相照APP - 专业的医疗健康平台，快来下载体验吧！\n下载链接：https://www.igandan.com",
			success: function (res) {
				console.log("success:" + JSON.stringify(res));
			},
			fail: function (err) {
				console.log("fail:" + JSON.stringify(err));
			}
		});
		// #endif
		
		// #ifdef H5
		// H5环境下的分享
		if (navigator.share) {
			navigator.share({
				title: '肝胆相照APP',
				text: '专业的医疗健康平台，快来下载体验吧！',
				url: 'https://www.igandan.com'
			}).then(() => {
				uni.showToast({
					title: '分享成功',
					icon: 'success'
				})
			}).catch(() => {
				uni.showToast({
					title: '分享失败',
					icon: 'none'
				})
			})
		} else {
			// 复制到剪贴板
			uni.setClipboardData({
				data: '肝胆相照APP - 专业的医疗健康平台，快来下载体验吧！\n下载链接：https://www.igandan.com',
				success: () => {
					uni.showToast({
						title: '已复制到剪贴板',
						icon: 'success'
					})
				}
			})
		}
		// #endif
		
		// #ifdef MP-WEIXIN
		// 微信小程序分享
		uni.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		})
		// #endif
		
		closeShare()
	}
	
	// 分享到朋友圈
	const shareToMoments = () => {
		// #ifdef APP-PLUS
		uni.share({
			provider: "weixin",
			scene: "WXSceneTimeline",
			type: 1,
			summary: "肝胆相照APP - 专业的医疗健康平台，快来下载体验吧！\n下载链接：https://www.igandan.com",
			success: function (res) {
				console.log("success:" + JSON.stringify(res));
			},
			fail: function (err) {
				console.log("fail:" + JSON.stringify(err));
			}
		});
		// #endif
		
		// #ifdef H5
		// 复制到剪贴板
		uni.setClipboardData({
			data: '肝胆相照APP - 专业的医疗健康平台，快来下载体验吧！\n下载链接：https://www.igandan.com',
			success: () => {
				uni.showToast({
					title: '已复制到剪贴板，可分享到朋友圈',
					icon: 'success'
				})
			}
		})
		// #endif
		
		// #ifdef MP-WEIXIN
		uni.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		})
		// #endif
		
		closeShare()
	}
	
	// 分享到新浪微博
	const shareToWeibo = () => {
		// #ifdef APP-PLUS
		plus.share.sendWithSystem({
			type: 'text',
			content: '肝胆相照APP - 专业的医疗健康平台，快来下载体验吧！\n下载链接：https://www.igandan.com'
		}, () => {
			uni.showToast({
				title: '分享成功',
				icon: 'success'
			})
		}, (err) => {
			console.log('分享失败：', err)
			uni.showToast({
				title: '分享失败',
				icon: 'none'
			})
		})
		// #endif
		
		// #ifdef H5
		// 复制到剪贴板
		uni.setClipboardData({
			data: '肝胆相照APP - 专业的医疗健康平台，快来下载体验吧！\n下载链接：https://www.igandan.com',
			success: () => {
				uni.showToast({
					title: '已复制到剪贴板，可分享到微博',
					icon: 'success'
				})
			}
		})
		// #endif
		
		closeShare()
	}
	
	// 跳转到直播群页面
	const goToLiveGroup = () => {
		uni.navigateTo({
			url: '/pages_app/groupMsg/groupMsg'
		});
	};
	
	// 跳转到微信关联页面
	const goToWechatLink = () => {
		uni.navigateTo({
			url: '/pages_app/wechatContact/wechatContact'
		});
	};
	
	// 清除缓存
	const clearCache = () => {
		uni.showModal({
			title: '提示',
			content: '确定要清除缓存吗？',
			success: (res) => {
				if (res.confirm) {
					let os = plus.os.name;  
					if (os == 'Android') {  
						let main = plus.android.runtimeMainActivity();  
						let sdRoot = main.getCacheDir();  
						let files = plus.android.invoke(sdRoot, "listFiles");  
						let len = files.length;  
						for (let i = 0; i < len; i++) {  
							let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径  
							plus.io.resolveLocalFileSystemURL(filePath, function(entry) {  
								if (entry.isDirectory) {  
									entry.removeRecursively(function(entry) { //递归删除其下的所有文件及子目录  
										uni.showToast({  
											title: '缓存清理完成',  
											duration: 2000  
										});  
										formatSize(); // 重新计算缓存  
									}, function(e) {  
										console.log(e.message)  
									});  
								} else {  
									entry.remove();  
								}  
							}, function(e) {  
								console.log('文件路径读取失败')  
							});  
						}  
					} else { // ios暂时未找到清理缓存的方法，以下是官方提供的方法，但是无效，会报错  
						plus.cache.clear(function() {  
							uni.showToast({  
								title: '缓存清理完成',  
								duration: 2000  
							});  
							formatSize();  
						});  
					}  
				}
			}
		});
	};
	
	// 跳转到意见反馈页面
	const goToFeedback = () => {
		uni.navigateTo({
			url: '/pages_app/feedback/feedback'
		});
	};
	
	// 跳转到注销账户页面
	const goToDeleteAccount = () => {
		uni.navigateTo({
			url: '/pages_app/feedback/feedback-logoff'
		});
	};
	
	// 跳转到注册协议页面
	const goToAgreement = () => {
		uni.showToast({
			title: '注册协议',
			icon: 'none'
		});
	};
	
	// 跳转到隐私政策页面
	const goToPrivacy = () => {
		uni.showToast({
			title: '隐私政策',
			icon: 'none'
		});
	};
	
	// 退出登录
	const logout = () => {
		uni.showModal({
			title: '退出登录',
			content: '确定要退出登录吗？',
			success: (res) => {
				if (res.confirm) {
					logoutIm();
				}
			}
		});
	};
	const logoutIm=() => {
      uni.clearStorageSync();
      // 退出登录
      uni.$UIKitNIM.V2NIMLoginService.logout().then(() => {
        uni.$UIKitStore.destroy();
         uni.reLaunch({
          url: "/pages_app/login/login",
        });
      });
    };
	onShow(() => {
		isNoticeOn()
	});
</script>

<style scoped>
	.content {
		background-color: #f5f5f5;
		/* min-height: 100vh; */
		padding-bottom: 160rpx; /* 为固定的退出登录按钮留出空间 */
	}
	
	/* 导航栏样式 */
	.nav-bar {
		display: flex;
		align-items: center;
		height: 88rpx;
		background-color: #ffffff;
		padding: 0 30rpx;
		position: relative;
	}
	
	.nav-left {
		position: absolute;
		left: 30rpx;
		z-index: 1;
	}
	
	.nav-icon {
		font-size: 40rpx;
		color: #ff0000;
		font-weight: bold;
	}
	
	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 36rpx;
		color: #ff0000;
		font-weight: 500;
	}
	
	/* 设置列表样式 */
	.settings-list {
		background-color: transparent;
		
	}
	
	.setting-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		background-color: #ffffff;
	}
	.setting-item:nth-child(2){
		margin-top: 20rpx;
	}
	.setting-item:last-child {
		border-bottom: none;
	}
	
	.setting-text {
		font-size: 32rpx;
		color: #333333;
	}
	
	.setting-right {
		display: flex;
		align-items: center;
	}
	
	.setting-status {
		font-size: 28rpx;
		color: #666666;
		margin-right: 20rpx;
	}
	
	.cache-size {
		font-size: 28rpx;
		color: #666666;
		margin-right: 20rpx;
	}
	
	.setting-arrow {
		font-size: 32rpx;
		color: #cccccc;
	}
	
	/* 退出登录按钮样式 */
	.logout-section {
		/* position: fixed;
		bottom: 0;
		left: 0;
		right: 0; */
		padding: 30rpx;
		background-color: #fff;
		border-top: 1rpx solid #e0e0e0;
		z-index: 999;
	}
	
	.logout-btn {
		width: 100%;
		height: 88rpx;
		background-color: #ffffff;
		border: 2rpx solid #8B2316;
		border-radius: 10rpx;
		color: #8B2316;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.logout-btn:active {
		background-color: #fff0f0;
	}
	
	/* 分享弹窗样式 */
	.share-popup {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		padding: 40rpx 0 0;
	}
	
	.share-title {
		text-align: center;
		font-size: 32rpx;
		color: #333;
		margin-bottom: 40rpx;
		font-weight: 500;
	}
	
	.share-content {
		display: flex;
		justify-content: space-around;
		padding: 0 40rpx 40rpx;
	}
	
	.share-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		flex: 1;
	}
	
	.share-icon {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 20rpx;
	}
	
	.wechat-icon {
		background-color: #07C160;
	}
	
	.moments-icon {
		background-color: #07C160;
	}
	
	.weibo-icon {
		background-color: #E6162D;
	}
	
	.qq-icon {
		background-color: #12B7F5;
	}
	
	.share-icon-text {
		font-size: 50rpx;
		color: #fff;
		font-weight: bold;
	}
	
	.share-text {
		font-size: 24rpx;
		color: #666;
	}
	
	.share-cancel {
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-top: 1rpx solid #f0f0f0;
		font-size: 32rpx;
		color: #333;
	}
	
	.share-cancel:active {
		background-color: #f5f5f5;
	}
</style>
