<template>
	<view class="content">
		<!-- 功能列表 -->
		<uni-list class="mt10" :border="false">
			<uni-list-item :title="$t('settings.userInfo')" to="/pages/info/userInfo?changePwd=0"
				link="navigateTo">
			</uni-list-item>
			<!-- <uni-list-item v-if="userInfo.mobile" :title="$t('settings.changePassword')" :to="'/subpages/ucenter/login-page/pwd-retrieve/pwd-retrieve?phoneNumber='+ userInfo.mobile" link="navigateTo"></uni-list-item> -->
		</uni-list>
		<uni-list class="mt10" :border="false">
			<uni-list-item :title="$t('settings.changePassword')" to="/pages/info/userInfo?changePwd=1"
				link="navigateTo">
			</uni-list-item>
			<!-- <uni-list-item v-if="userInfo.mobile" :title="$t('settings.changePassword')" :to="'/subpages/ucenter/login-page/pwd-retrieve/pwd-retrieve?phoneNumber='+ userInfo.mobile" link="navigateTo"></uni-list-item> -->
		</uni-list>
		<uni-list class="mt10" :border="false">
			<!-- #ifndef H5 -->
			<!-- #ifdef APP-PLUS -->
			<!-- 检查push过程未结束不显示，push设置项 -->
			<uni-list-item :title="$t('settings.clearTmp')" @click="clearTmp" link></uni-list-item>
			<!-- <uni-list-item v-show="pushIsOn != 'wait'" :title="$t('settings.pushServer')" @click.native="pushIsOn?pushServer.off():pushServer.on()"  showSwitch :switchChecked="pushIsOn"></uni-list-item> -->
			<!-- #endif -->
			<!-- <uni-list-item v-if="supportMode.includes('fingerPrint')" :title="$t('settings.fingerPrint')" @click.native="startSoterAuthentication('fingerPrint')" link></uni-list-item> -->
			<!-- <uni-list-item v-if="supportMode.includes('facial')" :title="$t('settings.facial')" @click="startSoterAuthentication('facial')" link></uni-list-item> -->
			<!-- #endif -->
			<!-- <uni-list-item  :title="$t('settings.changeLanguage')" @click="changeLanguage"
				:rightText="currentLanguage" link></uni-list-item> -->
			<!-- #ifdef APP-PLUS -->
			<uni-list-item :title="$t('settings.version')" @click="onVersionClick" link></uni-list-item>
			<!-- #endif -->
		</uni-list>
		<!-- #ifdef MP-WEIXIN -->
		<uni-list class="mt10" :border="false">
			<uni-list-item clickable @click="deactivate" :title="$t('settings.deactivate')"></uni-list-item>
		</uni-list>
		<!-- #endif -->
		<!-- 退出/登录 按钮 -->
		<view class="bottom-back">
			<u-button type="primary" @click="clickLogout">{{hasLogin?$t('settings.logOut'):$t('settings.login')}}</u-button>
		</view>

		<u-loading-page :loading="loadingShow" fontSize="50" iconSize="50" loadingMode="spinner" color="green"
			bgColor="#e8e8e8" :loading-text="percentage+'%'"></u-loading-page>
	</view>
</template>

<script>
	// import pushServer from './dc-push/push.js';
	import {
		mapMutations,
		mapGetters,
		mapActions
	} from 'vuex';
	import {
		logoff
	} from "../../api/login";
	export default {
		data() {
			return {
				// pushServer:pushServer,
				supportMode: [],
				pushIsOn: "wait",
				currentLanguage: "",
				versionShow: false,
				version: "",
				versionCode: "",
				downloadUrl: "http://218.201.62.165:8003/Log/E%E8%BF%90%E8%90%A5.apk",
				isForceUpdate: "1",
				percentage: 0,
				loadingShow: false,
			}
		},
		computed: {
			...mapGetters({
				'userInfo': 'user/info',
				'hasLogin': 'user/hasLogin',
			}),
			i18nEnable() {
				return getApp().globalData.config.i18n.enable
			}
		},
		onLoad() {
			if (uni.getStorageSync('CURRENT_LANG') == "en") {
				this.currentLanguage = 'English';
			} else if (uni.getStorageSync('CURRENT_LANG') == "pt") {
				this.currentLanguage = 'Português';
			} else if (uni.getStorageSync('CURRENT_LANG') == "uz") {
				this.currentLanguage = "O'zbekcha";
			} else {
				this.currentLanguage = '简体中文';
			}
			// uni.setNavigationBarTitle({
			// })
			// // #ifdef APP-PLUS || MP-WEIXIN
			// uni.checkIsSupportSoterAuthentication({
			// 	success: (res) => {
			// 		console.log(res);
			// 		this.supportMode = res.supportMode
			// 	},
			// 	fail: (err) => {
			// 		console.log(err);
			// 	}
			// })
			// // #endif
		},
		onShow() {
			// 检查手机端获取推送是否开启
			//#ifdef APP-PLUS
			// setTimeout(()=>{
			// 	this.pushIsOn = pushServer.isOn();
			// },300)
			//#endif
		},
		methods: {
			clickLogout() {
				if (this.hasLogin) {
					uni.showModal({
						title: this.$t('settings.tips'),
						content: this.$t('settings.exitLogin'),
						cancelText: this.$t('settings.cancelText'),
						confirmText: this.$t('settings.confirmText'),
						success: res => {
							if (res.confirm) {
								// this.logout()
								// uni.navigateBack();
								this.reloadInfo()
							}
						},
						fail: () => {},
						complete: () => {}
					});
				} else {
					uni.reLaunch({
						url: '/pages/login/login'
					});
				}
			},
			reloadInfo(){
				uni.removeStorageSync('token')
				uni.removeStorageSync('tenantId')
				uni.removeStorageSync('userId')
				uni.removeStorageSync('userName')
				uni.removeStorageSync('userInfo')
				uni.removeStorageSync('userType')
				uni.removeStorageSync('tenantInfo')
				uni.removeStorageSync('currentTenantId')
				uni.removeStorageSync('currentVehicleInfo')
				uni.removeStorageSync('isAuditUser')
				uni.removeStorageSync('isDealerUser')
				uni.removeStorageSync('isDriverUser')
				uni.removeStorageSync('enterpriseInfo')
				uni.removeStorageSync('serverAddress');
				uni.removeStorageSync('serverPrefix');
				uni.reLaunch({
					url: '/pages/login/login'
				});
				getApp().globalData.tabIndex = 'home';
			},
			clearTmp() {
				uni.showLoading({
					title: this.$t('settings.clearing'),
					mask: true
				});
				/*
				任何临时存储或删除不直接影响程序运行逻辑（清除缓存必定造成业务逻辑的变化，如：打开页面的图片不从缓存中读取而从网络请求）的内容都可以视为缓存。主要有storage、和file写入。
				缓存分为三部分		
					原生层（如：webview、x5播放器的、第三方sdk的、地图组件等）
					前端框架（重启就会自动清除）
					开发者自己的逻辑（如：
						本示例的 检测更新功能下载了apk安装包，
						其他逻辑需要根据开发者自己的业务设计
						比如：有聊天功能的应用，聊天记录是否视为缓存，还是单独提供清除聊天记录的功能由开发者自己设计
					）
				*/
				uni.getSavedFileList({
					success: res => {
						if (res.fileList.length > 0) {
							uni.removeSavedFile({
								filePath: res.fileList[0].filePath,
								complete: res => {
									console.log(res);
									uni.hideLoading()
									uni.showToast({
										title: this.$t('settings.clearedSuccessed'),
										icon: 'none'
									});
								}
							});
						} else {
							uni.hideLoading()
							uni.showToast({
								title: this.$t('settings.clearedSuccessed'),
								icon: 'none'
							});
						}
					},
					complete: e => {
						console.log(e);
					}
				});
			},
			deactivate() {
				console.log('注销用户')
				console.log(uni.getStorageSync("userInfo"))
				let tenantInfo = uni.getStorageSync('tenantInfo').filter(item => item.statusFlag == '1')
				console.log(tenantInfo)
				if (tenantInfo.length > 0&&!uni.getStorageSync('isDriverUser')) {
					uni.showModal({
						// title: '提示',
						content: this.$t('settings.havaTenantInfo'),
						showCancel: false,
						confirmText: this.$t('settings.confirmText'),
						success: function(r) {
							if (r.confirm) {
								uni.redirectTo({
									url: '/subpages/tenant/list'
								})
							}
						}
					})
				} else {
					uni.showModal({
						// title: '提示', 
						content: this.$t('settings.confirmdeactivate'),
						showCancel: true,
						cancelText: this.$t('settings.cancelText'),
						confirmText: this.$t('settings.confirmText'),
						success: (r) =>{
							if (r.confirm) {
								logoff(uni.getStorageSync("userInfo")).then(res => {
									if (res.statusCode == 200) {
										this.reloadInfo()
									}
								})
							}
						}
					})
				}

			},
			//切换语言
			changeLanguage() {
				console.log('语言切换')
				uni.showActionSheet({
					itemList: ["English", "简体中文", "Português","O'zbekcha",'Russian'],
					success: res => {
						let language = uni.getStorageSync('CURRENT_LANG')
						console.log(res.tapIndex,language);
						if ((res.tapIndex === 0 && language != 'en') || (res.tapIndex === 1 && language !=
								'zh-Hans') || (res.tapIndex === 2 && language != 'pt') || (res.tapIndex === 3 && language != 'uz') || (res.tapIndex === 4 && language != 'ru')) {
							const globalData = getApp().globalData
							console.log(globalData, '--------------');
							console.log(language);
							if (res.tapIndex === 0) {
								language = globalData.locale = 'en'
							} else if (res.tapIndex === 1) {
								language = globalData.locale = 'zh-Hans'
							} else if (res.tapIndex === 2) {
								language = globalData.locale = 'pt'
							} else if (res.tapIndex === 3) {
								language = globalData.locale = 'uz'
							}else if (res.tapIndex === 4) {
								language = globalData.locale = 'ru'
							}
							uni.setStorageSync('CURRENT_LANG', language)
							getApp().globalData.$i18n.locale = language
							if (res.tapIndex === 0) {
								this.currentLanguage = 'English'
							} else if (res.tapIndex === 1) {
								this.currentLanguage = '简体中文'
							} else if (res.tapIndex === 2) {
								this.currentLanguage = 'Português'
							} else if (res.tapIndex === 3) {
								this.currentLanguage = "O'zbekcha"
							}else if (res.tapIndex === 4) {
								this.currentLanguage = "Russian"
							}
							if (uni.setLocale) {
								uni.setLocale(language)
							}
							uni.reLaunch({
								url: '/pages/login/login',
								complete: () => {
									uni.$emit("changeLanguage", language)
								}
							})
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			onVersionClick() {
				//#ifdef APP-PLUS
				var that = this;
				// 获取本地应用资源版本号
				plus.runtime.getProperty(plus.runtime.appid, (info) => {
					console.log(JSON.stringify(info));
					that.version = info.version;
					that.versionCode = info.versionCode;
					console.log("获取到的版本信息、", that.version, that.versionCode);
					uni.showActionSheet({
						itemList: ["版本号 " + that.versionCode + that.version],
						success: res => {
							uni.getSystemInfo({
								success: (res) => {
									console.log("当前平台信息、", res.platform);
									//检测当前平台，如果是安卓则启动安卓更新  
									if (res.platform == "android") {
										that.AndroidCheckUpdate();
									}
								}
							})
						},
						fail: () => {},
						complete: () => {}
					});
				})

				//#endif
			},

			AndroidCheckUpdate() {
				let that = this;
				plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
					that.version = wgtinfo.version //客户端版本号
					console.log('当前app版本信息：' + that.version);
				})
				that.getUpdateVersion()
			},
			getUpdateVersion() {
				let that = this;
				// 是否强制更新（0 否；1 是）
				uni.showModal({
					// 更新提醒
					title: '发现新版本，是否更新',
					content: '此版本号：' + that.version + '\xa0\xa0\xa0' + '待更新版本号：11',
					success: res => {
						if (res.confirm) {
							that.downWgt(); //下载文件
						} else if (res.cancel) {
							console.log('that.isForceUpdate：' + that.isForceUpdate);
							// 不更新强制退出app
							if (that.isForceUpdate == 1) {
								console.log('that.isForceUpdate1：' + that.isForceUpdate);
								uni.showModal({
									// 更新提醒
									title: '发现新版本，是否更新',
									content: '此版本为强制更新版本如不升级将退出APP',
									success: res => {
										if (res.confirm) {
											console.log('不更新强制退出app');
											plus.runtime.quit();
										} else if (res.cancel) {
											that.AndroidCheckUpdate();
										}
									}
								});
							}
						}
					}
				});


				complete: () => {}
			},
			downWgt() {
				let that = this;
				console.log('url:' + that.downloadUrl)
				that.loadingShow = true;
				const downloadTask = uni.downloadFile({ //执行下载
					url: that.downloadUrl, //下载地址
					timeout: 1000 * 30, //30秒超时时间
					success: downloadResult => { //下载成功
						that.showdownLine = false
						uni.hideLoading();
						console.log('downloadResult.statusCode' + downloadResult.statusCode)
						if (downloadResult.statusCode == 200) {
							console.log('更新中')
							uni.showModal({
								title: '',
								showCancel: false,
								content: '更新成功，马上重启',
								confirmText: '重启',
								confirmColor: '#EE8F57',
								success: function(res) {
									if (res.confirm == true) {
										plus.runtime.install( //安装
											downloadResult.tempFilePath, {
												force: true
											},
											function(res) {
												utils.showToast('更新成功，重启中');
												plus.runtime.restart();
											}
										);
									}
								}
							});
						}
					},
					fail: err => {
						uni.hideLoading();
						that.showdownLine = false
						that.$u.toast(err.errMsg)
						console.log(err)
					},
					complete: com => {
						console.log(com)
					}
				});

				// 下载进度
				downloadTask.onProgressUpdate(res => {
					// that.$u.toast(res.progress)
					that.percentage = res.progress
					console.log('下载进度' + that.percentage);
				});
			},

		}
	}
</script>

<style>
	.progress-box {
		display: flex;
		height: 50rpx;
		margin-bottom: 60rpx;
	}

	/* #ifndef APP-NVUE */
	page {
		flex: 1;
		width: 100%;
		height: 100%;
	}

	uni-button:after {
		border: none;
		border-radius: 0;
	}

	/* #endif */
	.content {
		/* #ifndef APP-NVUE */
		/* display: flex; */
		width: 750rpx;
		height: 100vh;
		/* #endif */
		flex-direction: column;
		flex: 1;
		background-color: #F9F9F9;
	}

	.versionMain {
		width: 200rpx;
		height: 200rpx;
	}

	.bottom-back {
		padding: 0 40rpx;
	}

	.bottom-back-text {
		font-size: 33rpx;
	}

	.mt10 {
		margin-top: 10px;
	}

	/* #ifndef APP-NVUE  || VUE3 */
	.content /deep/ .uni-list {
		background-color: #F9F9F9;
	}

	.content /deep/ .uni-list-item--disabled,
	.list-item {
		height: 50px;
		margin-bottom: 1px;
	}

	/* #endif */
</style>