<template>
	<view class="page-container uni-column">
		<view class="uni-row" style="align-items: center;margin:8rpx 0 16rpx 0">
			<image class="logo" src="../../static/images/logo.png" @click="handleShowGear" />
			<uni-icons v-if="showGear > 4" class="icon-gear" type="gear-filled" size="60" style="z-index: 5;"
				@click="toggle('top')"></uni-icons>
			<view style="position: absolute; right: 12px;top: -4px;"><text>版本号:{{versionName}}</text></view>
		</view>
		<view class="title uni-row" v-if="loggedUsers.length > 0">
			<text>点击头像切换用户</text>
		</view>
		<!-- 输入框示例 -->
		<uni-popup ref="inputDialog" type="dialog" style="z-index: 2;">
			<uni-popup-dialog ref="inputClose" mode="input" title="手动设置" placeholder="请输入管理员密码"
				@confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>
		<!-- 弹出层 -->
		<uni-popup ref="popup" background-color="#fff" style="z-index: 1;">
			<view style="height: auto;">
				<view v-if="showWrite" style="margin: 20rpx auto 10rpx;width: 90%;">
					<view>手动设置: &nbsp;服务器、检查、下载、炉号</view>
					<view class="baseUrl uni-row">
						<input v-model="baseUrl" placeholder="服务器地址" />
						<button @click="handleSetting" style="background-color: #1684fc;color: white;">设置</button>
					</view>
					<view class="baseUrl uni-row">
						<input v-model="path.checkAppURL" placeholder="检查更新" style="width: 100%;" />
						<!-- <button @click="handleSetting2" style="background-color: #1684fc;color: white;">确定</button> -->
					</view>
					<view class="baseUrl uni-row">
						<input v-model="path.updateAppURL" placeholder="app更新" style="width: 100%;" />
						<!-- <button @click="handleSetting2" style="background-color: #1684fc;color: white;">确定</button> -->
					</view>
					<view class="baseUrl uni-row">
						<input v-model="path.furnaceNoURL" placeholder="获取炉号信息地址" style="width: 100%;" />
						<!-- <button @click="handleSetting3" style="background-color: #1684fc;color: white;">确定</button> -->
					</view>
				</view>
				<view class="uni-row" style="justify-content: space-between;align-items: center;width: 90%;margin: 10rpx auto 20rpx;
				box-sizing: border-box;">
					<view style="margin-right: 32rpx;">设置网络地址:</view>
					<view class="uni-row" style="align-items: center;">
						<view style="margin-right: 24rpx;">内网</view>
						<switch :checked="baseUrl == path.publicURL" @change="switchChange" />
						<view style="margin-left: 24rpx;">外网</view>
					</view>
					<view style="width: 64rpx;height: 64rpx;background-color: white;border-radius: 50%;"
						@click="handleShowInputDialog('center')"></view>
				</view>
			</view>
		</uni-popup>

		<view class="add-user-btn uni-row" @click="handleShowLoginDialog(null)">
			<view class="icon uni-row">
				<text class="label">+</text>
			</view>
			<view class="btn-label">
				<text class="label">添加新账号</text>
			</view>
		</view>
		<view v-for="(item, index) in loggedUsers" class="item-user uni-row" @click="handleSelectUser(item)"
			@longpress="handleLongPressUser(item)">
			<view class="user-avatar uni-row"><text
					class="label">{{ item.nickName ? item.nickName.charAt(0) : null }}</text></view>
			<view class="user-info">
				<view class="nickname">
					<text class="label">{{item.nickName}}</text>
				</view>
				<view class="username">
					<text class="label">{{item.userName}}</text>
				</view>
			</view>
		</view>
		<dialog-login ref="loginDialog" />
	</view>
</template>

<script setup>
	import {
		onMounted,
		ref
	} from 'vue'
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app'
	import {
		getUserInfo,
		getNickNameByUserName
	} from '@/api/login/index.js'
	import path from '@/api/base/path.js'
	import {
		getAppInfoListByType
	} from '@/api/business/app.js'
	import {
		getToken
	} from '@/utils/auth'
	import upgrade from '@/uni_modules/lgen-upgrade/js_sdk/upgrade.js'
	// 登录过的用户 
	const loggedUsers = ref([])
	const loginDialog = ref(null)
	const userInfo = ref({})
	const users = ref([])
	const nickName = ref('')
	const useInnerUrl = ref(true)
	const baseUrl = ref(null)
	const showGear = ref(0)
	const appInfo = ref({})
	const newAppInfo = ref({})
	const updateFlag = ref(true) // 是否更新标志,如果为false,不能登录
	const popup = ref(null)
	const showWrite = ref(0)
	const inputDialog = ref(null)
	const showInputDialog = ref(0)
	const versionName = ref(null)

	onLoad(() => {
		//uni.clearStorageSync();
		initBaseUrl();
		getCurrentVersion()
			//getUser();
			!useInnerUrl.value && setTimeout(doCheckUpdata, 500)
		initPdfUrl();
	})

	onReady(() => {

	})

	function getCurrentVersion() {
		uni.getSystemInfo({
			success: function(res) {
				versionName.value = res.appVersion;
			}
		});
		console.log(versionName.value)
	}

	function doCheckUpdata() {
		checkUpdate().then(res => {
			updateFlag.value = res;
			console.log(updateFlag.value)
			if (!res) {
				uni.showModal({
					title: '更新',
					content: '发现新版本',
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							update();
						}
					}
				})
			}
		})
	}

	function initPdfUrl() {
		if (uni.getStorageSync('baseUrl')) {
			const urlList = JSON.parse(uni.getStorageSync('baseUrl'))
			// console.log(urlList)
			if (urlList.pdfAppURL == null) {
				// uni.showToast({
				// 	title: "更新url"
				// })
				urlList.pdfAppURL = path.pdfAppURL
				uni.setStorageSync('baseUrl', JSON.stringify(urlList));
			}
		}
	}

	function checkUpdate() {
		console.log("88888")
		uni.getSystemInfo({
			success: function(res) {
				appInfo.value = res;
			}
		});
		// false 版本号不一致,更新,true不需要更新
		let flag = getAppInfoListByType(path.checkAppURL, {
			type: appInfo.value.osName
		}).then(res => {
			console.log(res)
			newAppInfo.value = res.rows[0];
			console.log(newAppInfo.value, "111")
			if (res.rows[0]) {
				return appInfo.value.appWgtVersion === newAppInfo.value.versionName;
			} else {
				return true;
			}
		})
		console.log("flag", flag)
		return flag;
	}

	function update() {
		upgrade.downloadInstallApp(path.updateAppURL + newAppInfo.value.url);
	}

	function init() {
		uni.getStorageInfo({
			success: function(res) {
				for (let i = 0; i < res.keys.length; i++) {
					let storagekey = res.keys[i];
					uni.getStorage({
						key: storagekey,
						success: function(res) {
							if (storagekey !== 'token' && storagekey !== '__DC_STAT_UUID' &&
								storagekey !== 'baseUrl') {
								getNickNameByUserName(storagekey).then((response) => {
									if (response.code == 200) {
										loggedUsers.value.push({
											userName: storagekey,
											password: res.data,
											nickName: response.msg
										})
									}
								})
							}
							if (storagekey == 'baseUrl') {
								baseUrl.value = JSON.parse(res.data).baseUrl;
								path.checkAppURL = JSON.parse(res.data).checkAppURL;
								path.updateAppURL = JSON.parse(res.data).updateAppURL;
								path.furnaceNoURL = JSON.parse(res.data).furnaceNoURL;
								path.pdfAppURL = JSON.parse(res.data).pdfAppURL;
							}
						}
					});
				}
			}
		});
	}

	function initBaseUrl() {
		let urlList = {
			baseUrl: useInnerUrl ? path.innerURL : path.baseURL,
			checkAppURL: useInnerUrl ? '' : path.checkAppURL,
			updateAppURL: useInnerUrl ? path.innerUpdateAppURL : path.updateAppURL,
			furnaceNoURL: useInnerUrl ? path.innerFurnaceNoURL : path.furnaceNoURL,
			pdfAppURL: useInnerUrl ? path.innerPdfAppURL : path.pdfAppURL
		}
		uni.getStorage({
			key: 'baseUrl',
			fail: function() {
				uni.setStorageSync('baseUrl', JSON.stringify(urlList));
			},
			complete: function() {
				init();
			}
		});
	}

	function handleShowGear() {
		showGear.value += 1;
	}

	function handleShowWrite() {
		showWrite.value += 1;
	}

	function handleShowInputDialog(type) {
		showInputDialog.value += 1;
		if (showInputDialog.value > 4) {
			inputDialog.value.open(type);
		}
	}

	function dialogInputConfirm(val) {
		if (val == 'admin888') {
			showWrite.value = true;
		} else {
			uni.showToast({
				icon: 'none',
				title: '密码错误'
			})
		}
	}

	function toggle(type) {
		showGear.value += 1;
		if (showGear.value > 5) {
			showGear.value = 0;
		}
		showWrite.value = false;
		showInputDialog.value = 0;
		popup.value.open(type);
	}

	function switchChange(e) {
		if (e.detail.value) {
			baseUrl.value = path.publicURL;
			path.checkAppURL = path.publicURL;
			path.updateAppURL = path.outUpdateAppURL;
			path.furnaceNoURL = path.outFurnaceNoURL;
			path.pdfAppURL = path.outPdfAppURL
			handleSetting();
		} else {
			baseUrl.value = path.innerURL;
			path.checkAppURL = path.innerURL;
			path.updateAppURL = path.innerUpdateAppURL;
			path.furnaceNoURL = path.innerFurnaceNoURL;
			path.pdfAppURL = path.innerPdfAppURL
			handleSetting();
		}
	}

	function handleSetting() {
		let urlList = {
			baseUrl: baseUrl.value,
			checkAppURL: path.checkAppURL,
			updateAppURL: path.updateAppURL,
			furnaceNoURL: path.furnaceNoURL,
			pdfAppURL: path.pdfAppURL,
		}
		uni.setStorage({
			key: 'baseUrl',
			data: JSON.stringify(urlList),
			success: function() {
				uni.showToast({
					icon: "success",
					title: "设置成功"
				});
				doCheckUpdata();
			}
		});

	}

	const handleShowLoginDialog = (user) => {
		// 判断更新否,没更新不能登录
		if (!updateFlag.value) {
			uni.showToast({
				icon: 'none',
				title: '请更新后再登录'
			})
			setTimeout(doCheckUpdata, 500);
		} else {
			let _user = user ?? {}
			// 调用子组件中的方法
			loginDialog.value.open(_user)
		}
	}
	const handleSelectUser = (user) => {
		handleShowLoginDialog(user)
	}

	const handleLongPressUser = (user) => {
		uni.showModal({
			title: '提示', // 标题
			content: '是否删除此账号', // 提示内容
			cancelText: "取消", // 取消按钮的文字
			confirmText: "确认", // 确认按钮的文字
			//点击确定之后执行的代码
			success(res) {
				if (res.confirm) {
					uni.removeStorage({
						key: user.userName, // 键名		
						success: () => {
							uni.showToast({
								title: '删除成功',
								icon: 'success',
								duration: 3000,
							});
							loggedUsers.value = [];
							init();
						}, // 成功回调函数

						fail: () => {}, // 失败回调函数

					})
				}
			}
		});

	}
	const handleAddUser = () => {
		uni.setStorage({
			key: 'logged-users',
			data: {
				users: ''
			},
			success: () => {}
		})
	}
</script>

<style lang="scss">
	.page-container {
		overflow: auto;
	}

	.logo {
		width: 120rpx;
		height: 120rpx;
		margin: 0 auto;
	}

	.title {
		height: 80rpx;
		justify-content: center;
		align-items: center;
		color: #999999;
	}

	.icon-gear {
		position: fixed;
		right: 40rpx;
		font-size: 60rpx;
	}

	.baseUrl {
		border: 2rpx solid gray;
		width: 100%;
		margin: 20rpx auto;
		border-radius: 12rpx;
		align-items: center;

		input {
			width: 70%;
			padding: 16rpx 24rpx;
		}

		button {
			width: 30%;
		}
	}

	.item-user {
		margin: 32rpx;
		margin-top: 0;
		padding: 32rpx;
		background-color: #FFFFFF;
		align-items: center;

		.user-avatar {
			width: 128rpx;
			height: 128rpx;
			border-radius: 64rpx;
			background-color: #F1F2F3;
			justify-content: center;
			align-items: center;

			.label {
				font-size: 64rpx;
			}
		}

		.user-info {
			flex: 1;
			height: 96rpx;
			padding-left: 32rpx;

			.nickname {
				.label {
					font-weight: bold;
					font-size: 40rpx;
				}
			}

			.username {
				margin-top: 8rpx;

				.label {
					font-size: 32rpx;
				}
			}
		}
	}

	.add-user-btn {
		margin: 32rpx;
		padding: 32rpx;
		background-color: #FFFFFF;
		align-items: center;

		.icon {
			width: 128rpx;
			height: 128rpx;
			align-items: center;
			justify-content: center;
			background-color: #F1F2F3;
			border-radius: 64rpx;

			.label {
				color: #FFFFFF;
				font-size: 128rpx;
			}
		}

		.btn-label {
			flex: 1;
			padding-left: 32rpx;

			.label {
				font-size: 40rpx;
			}
		}
	}
</style>