<template>
	<view class="wrap">
		<!-- <view v-show="loading" style="width: 100%; height: 100vh; background: #ffffff; display: flex; justify-content: center; align-items: center">
			<view>
				<image src="../../static/gif/Winter.gif" style="width: 120rpx; height: 120rpx"></image>
				<view>{{ loading_text }}</view>
			</view>
		</view> -->
		<!-- <view></view> -->
		<view class="content">
			<view class="title">欢迎使用WMS PDA</view>
			<u-form ref="uLoginForm" :model="form" :rules="rules">
				<u-form-item :border-bottom="false" prop="username">
					<u-input :border="true" class="u-input-style" v-model="form.username" placeholder="请输入账号" />
				</u-form-item>
				<view class="tips">请使用和ziWMS相同账户</view>
				<u-form-item :border-bottom="false" prop="password">
					<u-input :border="true" class="u-input-style" type="password" v-model="form.password" placeholder="请输入密码" />
				</u-form-item>
				<u-form-item :border-bottom="false" prop="orgName" class="width-form-item">
					<u-input class="input-color" height="80" v-model="form.orgName" type="select" @click="show = true"
						placeholder="请选择组织" />
					<u-select v-model="show" mode="single-column" :list="orgList" @confirm="orgConfirm"></u-select>
				</u-form-item>
			</u-form>
			<button @click="submit" :disabled="loading" class="getCaptcha">进入系统</button>
		</view>
		<view class="buttom">
			<view class="hint">Copyright © 2023 ZXY Technology 1.0.3</view>
		</view>
		<u-toast ref="uTakeOverToast" />
	</view>
</template>

<script>
import { LoginCheck, QueryInfo, getORG } from '../../common/api.js';
//import { installWgt, downWgt } from '../../common/CheckUpdate.js';
//import { plus } from '@dcloudio/uni-app-plus';
import service from '../../common/service.js';
export default {
	data() {
		return {
			form: {
				username: '',
				password: '',
				org:"",
				orgName:""
			},
			show: false,
			rules: {
				username: [{ required: true, message: '请输入账号', trigger: ['blur', 'change'] }],
				password: [{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }],
				orgName: [{ required: true, message: '请选择组织', trigger: ['blur', 'change'] }]
			},
			Queryaram: {
				queryID: '',
				version: '',
				BINDV: {}
			},
			loading: false,
			loading_text: '检查登录状态',
			list: '',
			orgList: [],
		};
	},
	created() {
		this.loading_text = '检查登录状态';
		// uni.getStorage({
		// 	key: 'token',
		// 	success: () => {
		// 		uni.switchTab({
		// 			url: '/pages/material/index'
		// 		});
		// 	},
		// 	fail: () => {
		// 		this.loading = false;
		// 		this.form = {...JSON.parse(uni.getStorageSync('loginInfoObject'))};
		// 	}
		// });
		if(uni.getStorageSync('loginInfoObject')) {
			this.form = {...JSON.parse(uni.getStorageSync('loginInfoObject'))};	
		}
		
		this.$nextTick(function () {
			this.$refs.uLoginForm.setRules(this.rules);
		});
		// this.orgFn()
	},
	mounted() {
		//this.checkUpdate();
		 	// uni.setStorage({
		 	// 	key: 'appversion',
		 	// 	data: NewVersion
		 	// });
			//this.$showMessage('写入内存的版本号是:' + NewVersion);
			//console.log('写入内存的版本号是2:' + plus.runtime.version);
			this.$MyRequest('/login/getORG', {orgNo: null}).then(res => {
				let arr = res.data.resultObj
				console.log(arr)
				this.orgList = arr.map(item => {return {label: item.DESCRIPTION, value: item.ERPFACTORY}})
			})
	},
	methods: {
		// orgFn() {
		// 	this.$MyRequest('/storage/getORG', {}).then(res => {
		// 		let arr = res.data.resultObj
		// 		console.log(arr)
		// 		this.orgList = arr.map(item => {return {label: item.DESCRIPTION, value: item.ERPFACTORY}})
		// 	})
		// },
		orgConfirm(e) {
			console.log(e);
			this.form.orgName = e[0].label;
			this.form.org = e[0].value;
		},
		checkUpdate() {
		  const that = this;
					this.$MyRequest('/pdaDownload/getVersion', {vision:1}).then(res => {
						console.log("运行版本" + plus.runtime.version)
						const version = res.data.resultObj.PDA_VERSION;
						console.log("服务器版本" + res.data.resultObj.PDA_VERSION)
						const downloadUrl = res.data.resultObj.PDA_DOWNLOADURL;
						const currentVersion = plus.runtime.version;
						if (version > currentVersion) {
						  uni.showModal({
						    title: '发现新版本',
						    content: '是否更新应用？',
						    success: function(res) {
						      if (res.confirm) {
						       const downObj =  plus.downloader.createDownload(downloadUrl, {
						          method: 'GET'
						        }, function(d, status) {
						          if (status == 200) {
						            plus.runtime.install(d.filename, {}, function() {
						              plus.runtime.restart();
						            });
						          } else {
						            uni.showToast({
						              title: '下载失败，请重试',
						              icon: 'none'
						            });
						          }
						        });
								downObj.start();
						      }
							   
						    }
						  });
						 
						}
					}).catch(err => {
							this.$showMessage(err)
						})
		},
		submit() {
			 this.$refs.uLoginForm.validate((valid) => {
				if (valid) {
					// this.loading_text = '正在登录';
					// this.loading = true;
					
					// Promise.all([]).then(([userInfo, orderList]) => {
					//         this.userInfo = userInfo;
					//         this.orderList = orderList;
					//       })
					//       .catch((error) => {
					//         console.error(error);
					//       });
					LoginCheck({params:{
						userId : this.form.username,
						password : this.form.password,
						orgNo: this.form.org,
						siteName:"SDK"
					}}).then((res) => {
						let result = JSON.parse(res.data)
						console.log(result)
						if (res && res.status == "success") {
							console.log(res.data.token)
							uni.setStorage({
								key: 'userid',
								data:this.form.username
							});
							uni.setStorage({
								key: 'ut',
								data:  result.token
							});
							// uni.setStorage({
							// 	key: 'token',
							// 	data: result.token
							// });
							console.log(666, result.token)
							uni.setStorageSync('token', result.token);
							uni.setStorage({
								key: 'session',
								data: result.session
							});
							// service.setStorageExpires('utn',res.data.token, 30)
							// service.setStorageExpires('token',res.data.token, 30)
							uni.setStorage({
								key: 'siteName',
								data:"SDK"
							});
							uni.setStorage({
								key: 'orgObject',
								data: JSON.stringify({ERPFACTORY:this.form.org,DESCRIPTION:this.form.orgName})
							});
							uni.setStorage({
								key: 'loginInfoObject',
								data: JSON.stringify(this.form)
							});
							
							console.log(1111111111)
							this.$MyRequest('/menu/getHierarchicalMenuOfPermission', {
								queryId: "GetHierarchicalMenuOfPermissionList",
								version: "sdk001",
								params: {
								  USERID: this.form.username,
								  PLATFORM:"APP"
								}
							}).then(res => {
								if(res.data.code == 200) {
									console.log(222222222)
									let menuList = res.data.data.menuList
									// console.log('menuList', menuList)
									let menuArrayList = this.flatten(menuList)
									// console.log('flatten', menuArrayList)
									let menuArray = [];
									menuArrayList.forEach(item => {
										menuArray.push(item.id);
									});
									// console.log('menuArray', menuArray)
									uni.setStorageSync('menuArray', menuArray);
									
									uni.reLaunch({
									  url: '/pages/material/index'
									})
									// uni.switchTab({
									// 	url: '/pages/material/index'
									// });
								} else {
									this.loading = false;
								}
							})
							
							// #ifdef APP-PLUS
							// 初始化
							const init_scan_Module = uni.requireNativePlugin("ScanModule")
							let init = init_scan_Module.InitSDK()
							console.log("初始化",init)
							this.loading = false;
							// #endif
						} else {
							this.showToast('登录失败：' + res['message'] || '');
							this.loading = false;
						}
					});
				} else {
					return;
				}
			});
		},
		showToast(text, type) {
			this.$refs.uTakeOverToast.show({
				title: text,
				type: type,
				position: 'bottom'
			});
		},
		flatten (arr){
		    return arr.reduce((result, item)=> {
		        return result.concat(item,(Array.isArray(item.children) ? this.flatten(item.children) : []));
		    }, []);
		}
	}
};
</script>

<style lang="scss" scoped>
.wrap {
	background-image: url('../../static/img/login1.png'); /* 背景图片路径 */
	background-color: #A1CDDF; /* 背景图片路径 */
	background-size: cover;
	background-repeat: no-repeat;
	background-position: center center;
	height: 100vh;
	.content {
		width: 600rpx;
		margin: auto;
		padding-top: 250upx;
		.input-color {
			border: 1px solid cornsilk;
			    border-radius: 10rpx;
			    padding: 0 20rpx !important
		}
		.input-color .uni-input-placeholder {
			color:dimgray !important
		}
		.input-color /deep/ .uni-input-input {
			color:cornsilk !important
		}
		.input-color /deep/ .u-icon__icon {
			color: cornsilk !important
		}
		.width-form-item {
			width: 500upx;
		}
		.title {
			text-align: left;
			font-size: 60rpx;
			font-weight: 500;
			margin-bottom: 70rpx;
		}
		.tips {
			color: dimgray;
			margin-bottom: 30rpx;
			margin-top: 8rpx;
		}
		.getCaptcha {
			background-color: rgb(253, 140, 64);
			color: #ffffff;
			border: none;
			font-size: 30rpx;
			padding: 12rpx 0;
			margin-top: 60rpx;
		}

		.u-input-style {
			font-size: 30rpx;
			background: #ffffff;
			height: 80rpx;
		}
	}
	.buttom {
		.hint {
			font-size: 30rpx;
			color: $u-tips-color;
			text-align: center;
			position: absolute;
			bottom: 0px;
			margin: 0 auto;
			left: 15%;

			.link {
				color: $u-type-warning;
			}
		}
	}
}
</style>