<template>
	<view class="content">
		<uni-icons class="setting" type="gear" @click="handleServerSettings" size="50" color="#fff"></uni-icons>
		<view class="login_logo">
			<!-- <image :src="logo || 'https://img.picgo.net/2024/04/18/login_logo45cb6a5eb95c8c1c.png'"></image> -->
			<view class="logo_bj">{{ logoName || '中赢' }}</view>
		</view>
		<view class="login-title">
			<label>工业互联网平台</label>

			<text>{{ companyName }}</text>
		</view>
		<view>
			<view class="login-content">
				<view>
					<view class="form">
						<view class="login-input">
							<label class="icon-lable"></label>
							<input name="input" v-model="userInfo.username" placeholder="请输入账号" />
						</view>
						<view class="login-input">
							<label class="icon-lable2"></label>
							<input class="" name="input" password v-model="userInfo.passwd" placeholder="请输入密码" />
						</view>
						<button @click="submit">登录</button>
						<view class="password-memo">
							<checkbox-group @change="checkboxChange">
								<label>
									<checkbox value="1" :checked="isMemo" />
									记住密码
								</label>
							</checkbox-group>
						</view>
						
					</view>
				</view>
			</view>
		</view>
		<view class="version">
			<text>当前版本：{{ currentVersion }}</text>
		</view>
		<ServerSetting ref="serverSettingRef" @setServerStatus="setServerStatus" />
		<!-- 下载进度弹窗 -->
		<view class="download-modal" v-if="downloadVisible" @touchmove.stop.prevent>
			<view class="download-mask"></view>
			<view class="download-dialog">
				<view class="download-title">正在下载安装包</view>
				<view class="progress-bar-wrapper">
					<view class="progress-bar-bg">
						<view class="progress-bar-fill" :style="{ width: downloadProgress + '%' }"></view>
					</view>
					<text class="progress-text">{{ downloadProgress }}%</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		postJ
	} from '@/utils/api.js'
	import {
		login,
		usName,
		getLatestVersion
	} from '@/api/common.js'
	import {
		getResourcesTree
	} from '@/api/pda/common.js'

	import {
		setMemo,
		isMemo,
		removeMemo,
		setPassword,
		getPassword
	} from '@/utils/passwordMemo.js'
	import ServerSetting from '@/components/ServerSetting/index'

	export default {
		components: {
			ServerSetting
		},
		data() {
			return {
				currentVersion: '',
				userInfo: {
					username: '',
					passwd: ''
				},
				isMemo: isMemo(),
				loginDisabled: false,

				companyName: null,
				logo: null,
				logoName: '',
				downloadVisible: false,
				downloadProgress: 0
			}
		},
		onLoad() {
			const {
				appVersion
			} = uni.getAppBaseInfo()
			this.currentVersion = appVersion
			if (this.isMemo) {
				const userInfo = getPassword()
				if (userInfo?.username) this.userInfo = userInfo
			}

			this.getUsName()
			// 进入登录页自动检测版本更新
			this.checkVersionForLogin()
		},
		mounted() {
			// #ifdef APP-PLUS
			this.$nextTick(() => {
				this.$refs.serverSettingRef && this.$refs.serverSettingRef.serverCheck()
			})
			// #endif
			// uni.reLaunch({
			//           url: "/pages/home/home",
			//         });
		},
		methods: {
			getUsName() {
				usName().then(res => {
					this.companyName = res.companyName
					this.logo = res.logo
					this.logoName = res.logoName
				})
			},
			setServerStatus(val) {
				this.loginDisabled = !val
			},
			//登录
			// submit() {
			//   // #ifdef APP-PLUS
			//   if (!this.apiUrl) {
			//     this.$refs.serverSettingRef.open();
			//     return;
			//   }
			//   // #endif

			//   const params = {
			//     loginName: this.userInfo.username,
			//     loginPwd: this.userInfo.passwd,
			//   };

			//   login(params)
			//     .then((res) => {
			//       if (this.isMemo) {
			//         setPassword(this.userInfo);
			//       }
			//       let data = res.data;
			//       uni.setStorageSync("token", data.token);
			//       uni.setStorageSync("userInfo", data);
			//       uni.showToast({
			//         title: "登录成功",
			//         icon: "success",
			//         duration: 2000,
			//       });
			//       setTimeout(() => {
			//         uni.reLaunch({
			//           url: "/pages/home/home",
			//         });
			//       }, 2000);
			//     })
			//     .catch((err) => {
			//       console.log(err, 222);
			//       uni.showToast({
			//         title: err.message || err,
			//         icon: "none",
			//         duration: 2000,
			//       });
			//     });
			// },
			handlUpdate() {
				// #ifdef APP-PLUS
				this.checkVersionForLogin()
				// #endif
			},

			// 版本检查和更新逻辑(封装方法)
			async checkVersionForLogin() {
				// #ifndef APP-PLUS
				return 'h5_platform'; // H5场景直接返回
				// #endif

				// #ifdef APP-PLUS
				try {
					const versionInfo = await getLatestVersion()
					const { appVersion } = uni.getAppBaseInfo()

					// 已是最新版本
					if (appVersion === versionInfo.versionCode) {
						return 'latest_version'
					}

					// 发现新版本,显示更新提示
					const confirmUpdate = await this.showUpdateModal(versionInfo.releaseNotes, false)
					if (!confirmUpdate) {
						return 'skip_update'
					}

					// 执行下载和安装
					return await this.downloadAndInstall(versionInfo.fileStorePath, true)
				} catch (error) {
					console.error('版本检查失败:', error)
					return 'version_check_failed'
				}
				// #endif
			},

			// 显示更新确认弹窗(封装方法)
			showUpdateModal(releaseNotes, showCancel) {
				return new Promise((resolve) => {
					uni.showModal({
						title: '发现新版本',
						content: '更新说明：' + releaseNotes,
						confirmText: '立即更新',
						cancelText: showCancel ? '暂不更新' : '',
						showCancel,
						success: (res) => {
							resolve(res.confirm)
						},
						fail: () => resolve(false)
					})
				})
			},

			// 下载并安装更新(封装方法)
			downloadAndInstall(fileStorePath, showSuccessTip) {
				return new Promise((resolve, reject) => {
					const downloadUrl = `${Vue.prototype.webviewUrl}/kd-aiot/${fileStorePath}`
					const downloadTask = uni.downloadFile({
						url: downloadUrl,
						success: async (data) => {
							if (data.statusCode !== 200) {
								this.handleDownloadError('download_failed', reject)
								return
							}

							try {
								const savedFilePath = await this.saveDownloadedFile(data.tempFilePath)
								await this.installUpdate(savedFilePath, showSuccessTip, resolve, reject)
							} catch (error) {
								this.handleDownloadError('install_failed', reject)
							}
						}
					})

					// 显示下载进度
					this.showDownloadProgress(downloadTask)
				})
			},

			// 保存下载的文件(封装方法)
			saveDownloadedFile(tempFilePath) {
				return new Promise((resolve, reject) => {
					uni.saveFile({
						tempFilePath,
						success: (res) => resolve(res.savedFilePath),
						fail: (err) => reject(err)
					})
				})
			},

			// 安装更新(封装方法)
			installUpdate(filePath, showSuccessTip, resolve, reject) {
				plus.runtime.install(
					filePath,
					{ force: true },
					() => {
						if (showSuccessTip) {
							uni.showToast({
								title: '更新成功，应用即将重启',
								icon: 'success',
								duration: 2000
							})
						}
						resolve('updated')
					},
					() => this.handleDownloadError('install_failed', reject)
				)
			},

		// 显示下载进度(封装方法)
		showDownloadProgress(downloadTask) {
			this.downloadVisible = true
			this.downloadProgress = 0

			downloadTask.onProgressUpdate((res) => {
				this.downloadProgress = res.progress
				if (res.progress >= 100) {
					this.downloadVisible = false
				}
			})

			// 确保任务异常时关闭弹窗
			if (downloadTask && typeof downloadTask.onStop === 'function') {
				downloadTask.onStop(() => { this.downloadVisible = false })
			}
			if (downloadTask && typeof downloadTask.onError === 'function') {
				downloadTask.onError(() => { this.downloadVisible = false })
			}
		},

		// 处理下载错误(封装方法)
		handleDownloadError(errorType, reject) {
			this.downloadVisible = false
			uni.showToast({
				title: '更新失败',
				icon: 'none'
			})
			if (reject) reject(errorType)
		},
			// 登录方法
			async submit() {
				// #ifdef APP-PLUS
				if (!this.apiUrl) {
					this.$refs.serverSettingRef.open()
					return
				}

				// 检查版本更新
				const updateResult = await this.checkVersionForLogin()
				console.log('版本检查结果:', updateResult)

				// 更新成功时停止登录流程(应用即将重启)
				if (updateResult === 'updated') return
				// #endif

				// 执行登录
				await this.performLogin()
			},

			// 执行登录逻辑(封装方法)
			async performLogin() {
				const params = {
					loginName: this.userInfo.username,
					loginPwd: this.userInfo.passwd
				}

				try {
					const res = await postJ(this.apiUrl + '/main/user/login', params)

					// 记住密码
					if (this.isMemo) {
						setPassword(this.userInfo)
					}

					// 保存用户信息
					const data = res.data
					uni.setStorageSync('token', data.token)
					uni.setStorageSync('userInfo', data)

					// 获取权限树
					await this.getTree()

					// 显示成功提示并跳转
					uni.showToast({
						title: '登录成功',
						icon: 'success',
						duration: 2000
					})

					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}, 2000)

				} catch (error) {
					uni.showToast({
						title: error.message || '登录失败',
						icon: 'none',
						duration: 2000
					})
				}
			},
			handleServerSettings() {
				this.$refs.serverSettingRef.open()
			},
			checkboxChange(e) {
				this.isMemo = e.detail.value[0] === '1'
				if (this.isMemo) {
					setMemo()
				} else {
					removeMemo()
				}
			},
			formatRouter(list) {
				let authorities = [];

				const fn = (list) => {
					let arr = [];
					for (const p of list) {
						if (p.menuType === 2) {
							// p.children = [];
							authorities.push(p);
						}
						//  else {
						if (p.children?.length) {
							p.children = fn(p.children);
						} else {
							p.children = [];
						}
						arr.push(p);
						// }
					}

					return arr;
				};

				fn(list);

				return authorities
			},
			getTree() {
				getResourcesTree().then(res => {
					console.log(res)
					if (res.length == 0) {
						uni.showToast({
							title: '您还未配置权限',
							icon: 'none'
						})
					}
					let List = JSON.stringify(res || [])
					let authorities =this.formatRouter(res[0].children)
					uni.setStorageSync('treeList', List)
					uni.setStorageSync('authorities', JSON.stringify(authorities)) //按钮
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'login.scss';
	.version {
		font-size: 12px;
		color: #999;
		position: absolute;
		bottom: 10rpx;
		text-align: center;
		width: 100%;
	}

	.download-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 9999;
		display: flex;
		align-items: center;
		justify-content: center;

		.download-mask {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: rgba(0, 0, 0, 0.5);
		}

		.download-dialog {
			position: relative;
			width: 560rpx;
			background: #fff;
			border-radius: 20rpx;
			padding: 50rpx 40rpx 40rpx;
			box-sizing: border-box;

			.download-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				text-align: center;
				margin-bottom: 40rpx;
			}

			.progress-bar-wrapper {
				display: flex;
				align-items: center;
				gap: 20rpx;

				.progress-bar-bg {
					flex: 1;
					height: 20rpx;
					background: #e8e8e8;
					border-radius: 10rpx;
					overflow: hidden;

					.progress-bar-fill {
						height: 100%;
						background: linear-gradient(90deg, #4a90e2, #357abd);
						border-radius: 10rpx;
						transition: width 0.3s ease;
					}
				}

				.progress-text {
					font-size: 28rpx;
					color: #666;
					min-width: 80rpx;
					text-align: right;
				}
			}
		}
	}
</style>
