<template>
	<view class="">
		<uni-nav-bar fixed="true" statusBar="true" left-icon="back" @clickLeft="back" title="系统设置">
		</uni-nav-bar>
		<u-cell-group>
			<picker @change="handlePicker" :range="['是', '否']">
				<u-cell title="记住密码" :isLink="true" arrow-direction="right">
					<text slot="value" class="u-slot-value">{{
            isMemo ? '是' : '否'
          }}</text>
				</u-cell>
			</picker>
			<u-cell title="修改密码" :isLink="true" arrow-direction="right" @click="$refs.passwordModalRef.open()">
			
		
			</u-cell>
			<u-cell title="服务器地址" :isLink="true" arrow-direction="right" @click="handleServerSettings">
				<text slot="value" class="u-slot-value" :key="apiAdress">{{
          apiAdress
        }}</text>
			</u-cell>
			<u-cell :title="'当前版本 ' + currentVersion" :isLink="true" arrow-direction="right">
				<text slot="value" class="u-slot-value" @click="handlUpdate">{{
					Nversion == currentVersion ? '' : `发现新版本(${Nversion})`}}
				</text>
			</u-cell>
		</u-cell-group>
		<view class="flex-buttom">
			<view class="btn" @click="loginOut"> 退出登录 </view>
			<view class="copyright">
				<view>版权所有© 2019-2025中赢合力</view>
				<view>湘ICP备20015098号</view>
			</view>
		</view>
		<updatePop ref="updatePop" :versionNum="versionNum" :downloadUrl="downloadUrl" :sizes="VersionInfo.fileSize">
		</updatePop>
		<passwordModal ref="passwordModalRef"></passwordModal>
		<ServerSetting ref="serverSettingRef" @setServerStatus="setServerStatus" />
	</view>
</template>

<script>
	import {
		postJ,
		get
	} from '@/utils/api.js'
	import updatePop from './components/updatePop.vue'
	import passwordModal from './components/password-modal.vue'
	import {
		setMemo,
		isMemo,
		removeMemo
	} from '@/utils/passwordMemo.js'
	import ServerSetting from '@/components/ServerSetting/index'
	import {
		getLatestVersion
	} from '@/api/common.js'
	export default {
		components: {
			updatePop,
			ServerSetting,passwordModal
		},
		data() {
			return {
				show: false,
				versionNum: '',
				downloadUrl: '',
				currentVersion: '',
				isMemo: isMemo(),
				apiAdress: '',
				Nversion: '',
				VersionInfo: ''
			}
		},
		onLoad() {
			const apiInfo = uni.getStorageSync('apiInfo')

			this.apiAdress =
				apiInfo.hostname &&
				`${apiInfo.protocal || ''}${apiInfo.hostname || ''}:${apiInfo.port || ''}`

			const {
				appVersion
			} = uni.getAppBaseInfo()
			this.currentVersion = appVersion
			getLatestVersion().then(res => {
				this.Nversion = res.versionCode
			})

			// this.currentVersion = plus?.runtime.version
			// this.getbb()
		},
		created() {

		},
		methods: {
			handlePicker(e) {
				this.isMemo = e.detail.value === 0
				if (e.detail.value === 0) {
					setMemo()
				} else {
					removeMemo()
				}
			},
			setServerStatus(val) {
				if (val) {
					const apiInfo = uni.getStorageSync('apiInfo')

					this.apiAdress = `${apiInfo.protocal || ''}${apiInfo.hostname || ''}:${
          apiInfo.port || ''
        }`
				}
			},
			handleServerSettings() {
				this.$refs.serverSettingRef.open()
			},
			loginOut() {

				uni.showModal({
					title: '提示',
					content: '确认退出登录',
					success: res => {
						console.log(res, res.confirm, '-----确认退出登录');
						if (res.confirm) {
							console.log('-----确认退出登录9999999');
							// uni.clearStorage()
							try {
								postJ(this.apiUrl + '/main/user/logout')
									.then(res => {

										uni.showToast({
											title: '退出成功',
											icon: 'success',
											duration: 500
										})


										setTimeout(() => {
											uni.removeStorageSync('token')
											uni.removeStorageSync('userInfo')
											uni.removeStorageSync('treeList')
											uni.reLaunch({
												url: '/pages/login/login'
											})

										}, 500)

									})
									.catch(err => {
										console.log(err);
										uni.showToast({
											title: '退出失败',
											icon: 'none'
										})
									})

							} catch (error) {
								console.log(error, 'error----')
								uni.reLaunch({
									url: '/pages/login/login'
								})
							}
						} else if (res.cancel) {
							console.log('用户点击取消')
						}
					}
				})
			},
			handlUpdate() {
				// get(this.apiUrl + '/versioning/getLatestData').then(res => {
				// 	console.log(res);
				// 	if (res.success) {
				// 		const currentVersion = this.currentVersion
				// 		const Nversion = res.data.version

				// 		console.log(currentVersion, Nversion);
				// 		this.VersionInfo = res.data
				// 		if (currentVersion !== Nversion) {
				// 			this.$refs.updatePop.open()
				// 			this.versionNum = Nversion
				// 			this.downloadUrl = this.apiUrl + res.data.path
				// 		} else {
				// 			uni.showToast({
				// 				title: '暂无新版本',
				// 				icon: 'none'
				// 			})
				// 		}
				// 	}
				// })

				// #ifdef APP-PLUS
				getLatestVersion().then(res => {
					console.log('res:', res)
					const {
						appVersion
					} = uni.getAppBaseInfo()
					if (appVersion != res.versionCode) {
						uni.showModal({
							title: '发现新版本',
							content: '更新说明：' + res.releaseNotes,
							confirmText: '立即更新',
							showCancel: false,
							success: (val) => {
								if (val.confirm) {
									const downloadTask = uni.downloadFile({
										url: `${Vue.prototype.webviewUrl}/kd-aiot/${res.fileStorePath}`,
										success: (data) => {
											if (data.statusCode === 200) {
												uni.saveFile({
													tempFilePath: data
														.tempFilePath,
													success: (saveRes) => {
														// uni.showToast({
														// 	title: '下载成功',
														// 	icon: 'success'
														// });
														// uni.hideLoading();
														// uni.showLoading({
														// 	title: "正在更新...",
														// 	mask: true,
														// });
														// 调用安装逻辑
														plus.runtime.install(
															saveRes
															.savedFilePath, {
																force: true
															},
															function() {
																// uni
																// 	.hideLoading();
															},
															function() {
																// uni
																// 	.hideLoading();
																uni.showToast({
																	title: '更新失败',
																	icon: 'error'
																});
															});

													}
												});
											}
										}
									});

									// 先显示初始的loading提示
									uni.showLoading({
										title: "正在下载安装包: 0%",
										mask: true,
									});

									// 记录上次显示的进度，避免频繁更新
									let lastProgress = 0;
									let loadingVisible = true;

									downloadTask.onProgressUpdate((ress) => {
										console.log('下载进度:', ress)

										// 只在进度有明显变化（每10%）或者达到100%时更新提示
										if ((ress.progress > lastProgress && ress.progress %
												10 === 0) || ress.progress === 100) {
											// 先隐藏再显示以更新内容
											if (loadingVisible) {
												uni.hideLoading();
											}

											if (ress.progress < 100) {
												uni.showLoading({
													title: "正在下载安装包: " + (ress
														.progress > lastProgress ? ress.progress : lastProgress) + "%",
													mask: true,
												});
												loadingVisible = true;
											} else {
												loadingVisible = false;
											}
											lastProgress = ress.progress > lastProgress ? ress.progress : lastProgress;
										}
									})

									// 确保任务完成时隐藏loading
									downloadTask.onStop(() => {
										if (loadingVisible) {
											uni.hideLoading();
											loadingVisible = false;
										}
									})
									downloadTask.onError(() => {
										if (loadingVisible) {
											uni.hideLoading();
											loadingVisible = false;
										}
									})
								}
							}
						});
					}

				}).catch(err => {
					console.log('err:', err)
				})
				// #endif
			},
			getbb() {
				get(this.apiUrl + '/versioning/getLatestData').then(res => {
					if (res.success) {
						this.Nversion = res.data.version
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.u-slot-value {
		color: #157a2c;
	}

	.flex-buttom {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 20rpx;
		box-sizing: border-box;

		.btn {
			color: #157a2c;
			font-size: 28rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			border: 1px solid #157a2c;
			border-radius: 10rpx;
			height: 80rpx;
		}
	}

	.copyright {
		color: #555;
		font-size: 28rpx;
		text-align: center;
		padding: 20rpx 0;
	}
</style>