<template>
	<view class="setting-container" :style="{height: `${windowHeight}px`}">
		<view class="menu-list">
			<view class="list-cell list-cell-arrow" @click="handleToPwd">
				<view class="menu-item-box">
					<uni-icons type="locked" size="18" color="#007AFF" class="menu-icon" />
					<view>修改密码</view>
				</view>
			</view>
			<view class="list-cell list-cell-arrow" @click="handleToUpgrade">
				<view class="menu-item-box">
					<uni-icons type="refreshempty" size="18" color="#007AFF" class="menu-icon" />
					<view>检查更新</view>
				</view>
			</view>
			<view class="list-cell list-cell-arrow" @click="handleRevert">
				<view class="menu-item-box">
					<uni-icons type="undo" size="18" color="#007AFF" class="menu-icon" />
					<view>版本回退</view>
				</view>
			</view>
			<view class="list-cell list-cell-arrow" @click="handleBaseUrl">
				<view class="menu-item-box">
					<uni-icons type="gear" size="18" color="#007AFF" class="menu-icon" />
					<view>配置服务器地址</view>
				</view>
			</view>
			<view class="list-cell list-cell-arrow" @click="handleCleanTmp">
				<view class="menu-item-box">
					<uni-icons type="trash" size="18" color="#007AFF" class="menu-icon" />
					<view>清理缓存</view>
				</view>
			</view>
		</view>
		<view class="cu-list menu">
			<view class="cu-item item-box">
				<view class="content text-center" @click="handleLogout">
					<text class="text-black">退出登录</text>
				</view>
			</view>
		</view>
		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog mode="input" message="成功消息" :duration="2000" :before-close="true" @close="close"
				@confirm="confirm">
				<uni-easyinput type="text" v-model="baseUrl" placeholder="请输入服务器地址" />
				<!-- <uni-easyinput type="text" v-model="wmsUrl" placeholder="请输入WMS服务器地址" /> -->
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
import { listReleases } from '@/api/system/update'
import { getLatestRelease } from '@/utils/parseRelease'

export default {
	data() {
		return {
			// baseUrl: getApp().globalData.config.baseUrl,
			baseUrl: uni.getStorageSync('base_url'),
			// wmsUrl: uni.getStorageSync('wms_url'),
			windowHeight: uni.getSystemInfoSync().windowHeight
		}
	},
	methods: {
		handleToPwd() {
			this.$tab.navigateTo('/pages/mine/pwd/index')
		},
		// 检查更新
		async handleToUpgrade() {
			// 向 Gitea 请求 Releases 数据
			this.$modal.loading('获取版本信息中...');
			const res = await listReleases();
			this.$modal.closeLoading();
			if (!res) {
				this.$modal.msg('获取版本信息失败');
				console.log('获取版本信息失败');
				return;
			}
			const latest = getLatestRelease(res);
			console.log(latest)

			const { latestVersion, download_url } = latest;

			let currentVersion;

			plus.runtime.getProperty(plus.runtime.appid, (appInfo) => {
				// 获取版本号
				currentVersion = appInfo.version
				if (!currentVersion || !latestVersion) {
					this.$modal.msg('获取版本信息失败');
					return;
				}
				// 比较版本号，判断是否有新版本
				const isLatestVersion = this.isLatest(currentVersion, latestVersion);
				if (!isLatestVersion) {
					// 提示用户更新
					uni.showModal({
						title: '更新提示',
						content: '检测到新版本，是否立即更新？',
						success: (res) => {
							if (res.confirm) {
								// 用户确认更新，下载新版本
								this.downloadAndInstall(download_url);
							}
						}
					});
				} else {
					this.$modal.msg('当前已是最新版本');
					console.log('当前已是最新版本');
				}
			});
		},
		// 版本回退
		handleRevert() {
			this.$tab.navigateTo('/pages/mine/revert/index')
		},
		handleCleanTmp() {
			// this.$modal.showToast('模块建设中~')
			// uni.clearStorage({
			// 	success: function() {
			// 		console.log('所有本地存储已清除');
			// 	},
			// 	fail: function() {
			// 		console.log('清除失败');
			// 	}
			// });

		},
		handleLogout() {
			this.$modal.confirm('确定注销并退出系统吗？').then(() => {
				this.$store.dispatch('LogOut').then(() => {
					this.$tab.reLaunch('/pages/index')
				})
			})
		},
		handleBaseUrl() {
			this.$refs.popup.open()
		},
		close() {
			this.$refs.popup.close()
		},
		confirm() {
			// 输入框的值
			uni.setStorage({
				key: 'base_url',
				data: this.baseUrl
			})
			// uni.setStorage({
			// 	key: 'wms_url',
			// 	data: this.wmsUrl
			// })
			// TODO 做一些其他的事情，手动执行 close 才会关闭对话框
			// ...
			this.$refs.popup.close()
		},
		// 比较版本号
		isLatest(currentVersion, remoteVersion) {
			const current = Number(currentVersion.split('.').join(''));
			const remote = Number(remoteVersion.split('.').join(''));

			// console.log(`compare:\n当前版本: ${current}\n最新版本: ${remote}`);
			return Boolean(current >= remote);
		},
		// 下载并安装新版本
		downloadAndInstall(url) {
			console.log('app-name:', __uniConfig.name)
			var dtask = plus.downloader.createDownload(url, {
					filename: __uniConfig.name
				},
				function(d, status) {
					// 下载完成  
					plus.runtime.install(
					  plus.io.convertLocalFileSystemURL(d.filename),
					  {},
					  () => {
					    // ✅ 安装成功
					    uni.showToast({
					      title: '安装成功，正在重启',
					      duration: 1500
					    });
					    setTimeout(() => {
					      plus.runtime.restart();
					    }, 1500);
					  },
					  (error) => {
					    // ❌ 安装失败
					    console.error('安装失败：', error);
					    uni.showToast({
					      title: error.message || error.msg || '安装失败',
					      duration: 2000
					    });
					  }
					);
				});
			try {
				console.log('开始下载');
				dtask.start(); // 开启下载的任务
				var prg = 0;
				var showLoading = plus.nativeUI.showWaiting("正在下载"); //创建一个showWaiting对象 
				dtask.addEventListener('statechanged', function(
					task,
					status
				) {
					// 给下载任务设置一个监听 并根据状态  做操作
					switch (task.state) {
						case 1:
							showLoading.setTitle("正在下载");
							break;
						case 2:
							showLoading.setTitle("已连接到服务器");
							break;
						case 3:
							prg = parseInt(
								(parseFloat(task.downloadedSize) /
									parseFloat(task.totalSize)) *
								100
							);
							showLoading.setTitle("  正在下载" + prg + "%  ");
							break;
						case 4:
							plus.nativeUI.closeWaiting();
							//下载完成
							break;
					}
				});
			} catch (err) {
				plus.nativeUI.closeWaiting();
				uni.showToast({
					title: '更新失败',
					mask: false,
					duration: 1500
				});
			}
		}
	}
}
</script>

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

.item-box {
	background-color: #FFFFFF;
	margin: 30rpx;
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	padding: 10rpx;
	border-radius: 8rpx;
	color: #303133;
	font-size: 32rpx;
}
</style>