<template>
	<view>
		<view style="color: #fff;">
			<tn-nav-bar backgroundColor="#207CF7" :bottomShadow="false"
				:isBack="!isNewUser">{{isNewUser?'完善':'修改'}}用户信息</tn-nav-bar>
			<view :style="{ height: tobheight + 'px' }"></view>
		</view>
		<form @submit="formSubmit">
			<view class='personal-data'>
				<view class='list'>
					<view class='item acea-row row-between-wrapper'>
						<view>头像</view>
						<view class="avatar-box" @click.stop='uploadpic'>
							<image mode="aspectFill" :src="userinfo.avatar?userinfo.avatar:'/static/images/head.jpg'">
							</image>
						</view>


						<!-- #ifdef MP-WEIXIN -->
						<button style="padding: 0;" class="getbutton" open-type="chooseAvatar"
							@chooseavatar="onChooseAvatar"></button>
						<!-- #endif -->


					</view>
					<view class='item acea-row row-between-wrapper'>
						<view>昵称</view>
						<view class='input'><input type='nickname' name='nickname' placeholder="请输入昵称"
								:value='userinfo.nickname' @input="handleNickNameInput"></input>
						</view>
					</view>

					<!-- 新增用户信息内容 -->
					<view class='item acea-row row-between-wrapper'>
						<view>手机号</view>
						<view class='input'><input type='phone' name='phone' placeholder="请输入手机号"
								:value='userinfo.phone'></input>
						</view>
					</view>

					<view class='item acea-row row-between-wrapper'>
						<view>密码</view>
						<view class='input'><input type='safe-password' name='password' placeholder="请输入登录密码(选填)"
								:value='userinfo.password'></input>
						</view>
					</view>

					<view class='item acea-row row-between-wrapper'>
						<view>姓名</view>
						<view class='input'><input type='text' name='name' placeholder="请输入您的真实姓名(选填)"
								:value='userinfo.name' @input="handleNameInput"></input>
						</view>
					</view>



					<view v-if="userinfo.id_number" class='item acea-row row-between-wrapper'>
						<view>ID号</view>
						<view class='input acea-row row-between-wrapper'>
							<input type='text' :value='userinfo.id_number' disabled='true' class='id'></input>
							<u-icon name="lock" size="22" color="#868686"></u-icon>
						</view>
					</view>


					<!-- #ifdef MP -->
					<view class='item acea-row row-between-wrapper'>
						<view>权限设置</view>
						<view class="input" @click="Setting">
							点击管理<u-icon name="arrow-right" size="17" color="#868686" top="1"></u-icon>
						</view>
					</view>
					<!-- #endif -->


				</view>
				<button class='modifyBnt' style="" hover-class="hoversubmit" formType="submit">保存修改</button>


				<!-- #ifdef H5 || APP-PLUS -->
				<view class="modifyBnt2 bg-color" style="margin-top: 40rpx;background: #ededed;" @click="outLogin">退出登录
				</view>
				<!-- #endif -->
			</view>
		</form>

	</view>
</template>

<script>
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	import {
		apiurl
	} from '@/common/request/request';
	// import Header from '@/components/header.vue';
	export default {
		// components: {
		// 	Header
		// },
		data() {
			return {
				loginType: 'h5', //app.globalData.loginType
				userIndex: 0,
				switchUserInfo: [],
				isAuto: false, //没有授权的不会自动授权
				isShowAuth: false, //是否隐藏授权
				canvasWidth: "",
				canvasHeight: "",
				canvasStatus: false,
				fileSizeString: '',
				version: '',
				ifimg: false,
				userinfo: {},
				tobheight: 45,
				platform: this.$platform.get(),
				isNewUser: false
			};
		},
		computed: {
			...mapGetters(['appInfo', 'isLogin', 'userInfo'])
		},
		onLoad(o) {
			if (o.isNewUser) {
				this.isNewUser = o.isNewUser
			}
			// this.isNewUser = true


			let that = this;
			that.userinfo = JSON.parse(JSON.stringify(that.userInfo))

			// that.userinfo = {
			// 	avatar: "https://v.swdz.com/addons/wike_aging/public/static/storage/20230517/7a01df223b06717edca445b333de2741.png",
			// 	coin: 667,
			// 	create_time: "2023-04-03 07:52:47",
			// 	create_time_int: 1680479567,
			// 	id: 4825,
			// 	id_number: "7498213065",
			// 	nickname: "roobe",
			// 	openid_miniapp: null,
			// 	openid_wechat: null,
			// 	status: 1,
			// 	token: "7f27f80f-a09a-5163-d06d-44109d599f66",
			// 	vip_time: 1712545777,

			// 	phone: 15609038521,
			// 	name: '李万涛',
			// 	password: 'li000022'
			// }

			console.log('修改用户信息页-用户信息：', that.userInfo);
			if (this.platform == 'wxMiniProgram') {
				var menumtop = uni.getMenuButtonBoundingClientRect().top - uni.getSystemInfoSync().statusBarHeight;
				var paddingtop = uni.getSystemInfoSync().statusBarHeight + menumtop;
				this.tobheight = menumtop + paddingtop + uni.getMenuButtonBoundingClientRect().height;
			}

		},
		methods: {
			...mapActions(['logout']),
			handleNameInput(e) {
				let reg = /^[A-Za-z\u4E00-\u9FA5]+$/
				if (!reg.test(e.target.value) && e.target.value != '') {
					// e.target.value = ''
					uni.showToast({
						title: '姓名只能包含中文或英文',
						icon: 'none'
					})
				}
			},
			handleNickNameInput(e) {
				if (e.target.value != '' && e.target.value.length > 6) {
					// e.target.value = ''
					uni.showToast({
						title: '昵称最多六个字符',
						icon: 'none'
					})
				}
				if (!e.target.value) {
					uni.showToast({
						title: '请填写昵称',
						icon: 'none'
					})
				}
			},
			isNew() {
				this.$util.Tips({
					title: '当前为最新版本'
				});
			},

			onChooseAvatar(e) {
				var that = this;
				// console.log(e.detail.avatarUrl);
				// this.userinfo.avatar = e.detail.avatarUrl
				// this.ifimg = true
				uni.uploadFile({
					url: apiurl('common/upload'),
					filePath: e.detail.avatarUrl,
					name: 'file',
					formData: {
						accept: 'image',
						upload_type: 'ali-oss'
					},
					success: res2 => {
						let a = JSON.parse(res2.data);
						if (a.code == 0) {
							that.userinfo.avatar = a.data.path
							that.ifimg = true
						} else {
							uni.showToast({
								title: '上传图片失败',
								icon: 'none'
							})
							that.ifimg = false
						}
					}
				});
			},
			updateApp() {
				this.$refs.appUpdate.update(); //调用子组件 检查更新
			},
			formatSize() {
				let that = this;
				plus.cache.calculate(function(size) {
					let sizeCache = parseInt(size);
					if (sizeCache == 0) {
						that.fileSizeString = "0B";
					} else if (sizeCache < 1024) {
						that.fileSizeString = sizeCache + "B";
					} else if (sizeCache < 1048576) {
						that.fileSizeString = (sizeCache / 1024).toFixed(2) + "KB";
					} else if (sizeCache < 1073741824) {
						that.fileSizeString = (sizeCache / 1048576).toFixed(2) + "MB";
					} else {
						that.fileSizeString = (sizeCache / 1073741824).toFixed(2) + "GB";
					}
				});
			},

			initData() {
				uni.showModal({
					title: '清楚缓存',
					content: '确定清楚本地缓存数据吗?',
					success: (res) => {
						if (res.confirm) {
							this.clearCache()
							this.formatSize()
						} else if (res.cancel) {
							return that.$util.Tips({
								title: '已取消'
							});
						}
					}
				});
			},
			clearCache() {
				let that = this;
				let os = plus.os.name;
				if (os == 'Android') {
					let main = plus.android.runtimeMainActivity();
					let sdRoot = main.getCacheDir();
					let files = plus.android.invoke(sdRoot, "listFiles");
					let len = files.length;
					for (let i = 0; i < len; i++) {
						let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径  
						plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
							if (entry.isDirectory) {
								entry.removeRecursively(function(entry) { //递归删除其下的所有文件及子目录  
									uni.showToast({
										title: '缓存清理完成',
										duration: 2000
									});
									that.formatSize(); // 重新计算缓存  
								}, function(e) {
									console.log(e.message)
								});
							} else {
								entry.remove();
							}
						}, function(e) {
							console.log('文件路径读取失败')
						});
					}
				} else { // ios暂时未找到清理缓存的方法，以下是官方提供的方法，但是无效，会报错  
					plus.cache.clear(function() {
						uni.showToast({
							title: '缓存清理完成',
							duration: 2000
						});
						that.formatSize();
					});
				}
			},

			/**
			 * 小程序设置
			 */
			Setting: function() {
				uni.openSetting({
					success: function(res) {}
				});
			},

			/**
			 * 退出登录
			 * 
			 */
			outLogin: function() {
				let that = this;
				if (that.loginType == 'h5') {
					uni.showModal({
						confirmColor: '#207CF7',
						title: '提示',
						content: '确认退出登录?',
						success: function(res) {
							if (res.confirm) {
								// getLogout()
								// 	.then(res => {
								// console.log(res.code);
								// uni.clearStorageSync()

								that.logout();
								// that.$store.commit("LOGOUT");
								// uni.navigateBack({})
								uni.reLaunch({
									url: '/pages/user/signin'
								})
								// })
								// .catch(err => {});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
			},

			/**
			 * 上传文件
			 * 
			 */
			uploadpic: function() {
				let that = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: function(res) {
						const tempFilePaths = res.tempFilePaths;
						//上传服务器将服务器;
						uni.uploadFile({
							url: apiurl('common/upload'),
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								accept: 'image',
								upload_type: 'ali-oss'
							},
							success: res2 => {
								let a = JSON.parse(res2.data);
								if (a.code == 0) {
									that.userinfo.avatar = a.data.path
									that.ifimg = true
								} else {
									uni.showToast({
										title: '上传图片失败',
										icon: 'none'
									})
									that.ifimg = false
								}
							}
						});
					}
				});
			},

			/**
			 * 提交修改
			 */
			async formSubmit(e) {
				let phoneReg = /^[1][3,4,5,7,8,9][0-9]{9}$/

				let reg = /^[A-Za-z\u4E00-\u9FA5]+$/


				let that = this,
					value = e.detail.value;

				// if (!that.ifimg && !that.userInfo.avatar) return that.$u.toast('保存失败，请上传头像');
				if (!value.nickname) return that.$u.toast(
					'保存失败，请填写昵称');

				if (value.nickname.length > 6) return that.$u.toast(
					'保存失败，昵称最多六个字符');

				if (!value.phone) return that.$u.toast(
					'保存失败，请填写手机号');

				if (!phoneReg.test(value.phone)) return that.$u.toast(
					'保存失败，填写的手机号不合法');
				// if (!value.password) return that.$u.toast(
				// 	'保存失败，请填写密码');

				if (!reg.test(value.name) && value.name != '') {
					return uni.showToast({
						title: '保存失败，姓名只能包含中文或英文',
						icon: 'none'
					})
				}
				// uni.showToast({
				// 	title: '保存中...',
				// 	duration: 3000,
				// 	icon: 'loading',
				// })
				uni.showLoading({
					title: '保存中...'
				})

				let res = await this.$http('ai.digitCheckText', {
					prompt: value.nickname
				})

				if (res.code == 0) {
					console.log('传递的用户信息参数:', {
						nickname: value.nickname,
						avatar: that.userinfo.avatar,

						name: value.name,
						phone: value.phone,
						password: value.password
					});
					// return
					// if (value.nickname == that.userinfo.nickname && !that.userInfo.nickname) return that.$u.toast(
					// 	'保存失败，请填写昵称');	

					// if (value.nickname == that.userinfo.nickname && !that.ifimg) return that.$u.toast('保存失败，您并没有修改');
					that.$http('user.profile', {
						nickname: value.nickname,
						avatar: that.userinfo.avatar,

						name: value.name,
						phone: value.phone,
						password: value.password
					}).then(res => {
						if (res.code == 0) {
							uni.hideLoading()
							that.$store.dispatch('getUserInfo')
							setTimeout(function() {
								if (value.password) {
									// uni.clearStorageSync()

									that.logout();
									// uni.clearStorage()
									uni.showToast({
										title: '登录密码已修改，请重新登录',
										duration: 1500,
									})
									setTimeout(function() {
										uni.reLaunch({
											url: '/pages/user/signin'
										})
									}, 2000);
								} else {
									uni.showToast({
										title: '保存成功',
										duration: 1000,
									})
									setTimeout(function() {
										uni.navigateBack()
									}, 1000);
								}

							}, 1000);
						} else {
							uni.hideLoading()
							that.$u.toast('保存失败，请重试');
						}
					}).catch((err) => {
						uni.hideLoading()
						that.$u.toast(err);
					})
				} else {
					uni.hideLoading()
					return uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
				console.log('昵称校验返回值：', res);
				// return
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #ededed;
	}

	.cartcolor {
		color: var(--view-theme);
		border: 1px solid var(--view-theme);
	}

	.personal-data .wrapper {
		margin: 10rpx 0;
		background-color: #fff;
		padding: 36rpx 30rpx 13rpx 30rpx;
	}

	.personal-data .wrapper .title {
		margin-bottom: 30rpx;
		font-size: 32rpx;
		color: #282828;
	}

	.personal-data .wrapper .wrapList .item {
		width: 690rpx;
		height: 160rpx;
		background-color: #f8f8f8;
		border-radius: 20rpx;
		margin-bottom: 22rpx;
		padding: 0 30rpx;
		position: relative;
		border: 2rpx solid #f8f8f8;
		box-sizing: border-box;
	}

	.personal-data .wrapper .wrapList .item.on {
		border-color: #e93323;
		border-radius: 20rpx;
		background-image: url("data:image/png;base64, ");
		background-size: 100% 100%;
		background-color: #fff9f9;
		background-repeat: no-repeat;
	}

	.personal-data .wrapper .wrapList .item .picTxt {
		width: 445rpx;
	}

	.personal-data .wrapper .wrapList .item .picTxt .pictrue {
		width: 96rpx;
		height: 96rpx;
		position: relative;
	}

	.personal-data .wrapper .wrapList .item .picTxt .pictrue image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}

	.personal-data .wrapper .wrapList .item .picTxt .pictrue .alter {
		width: 30rpx;
		height: 30rpx;
		border-radius: 50%;
		position: absolute;
		bottom: 0;
		right: 0;
	}

	.personal-data .wrapper .wrapList .item .picTxt .text {
		width: 325rpx;
	}

	.personal-data .wrapper .wrapList .item .picTxt .text .name {
		width: 100%;
		font-size: 30rpx;
		color: #282828;
	}

	.personal-data .wrapper .wrapList .item .picTxt .text .phone {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.personal-data .wrapper .wrapList .item .bnt {
		font-size: 24rpx;
		background-color: #fff;
		border-radius: 27rpx;
		width: 140rpx;
		height: 54rpx;
		border: 2rpx solid #e93323;
	}

	.personal-data .wrapper .wrapList .item .currentBnt {
		position: absolute;
		right: 0;
		top: 0;
		font-size: 26rpx;
		background-color: rgba(233, 51, 35, 0.1);
		width: 140rpx;
		height: 48rpx;
		border-radius: 0 20rpx 0 20rpx;
	}

	.personal-data .list {
		margin-top: 15rpx;
		background-color: #fff;
	}

	.personal-data .list .item {
		padding: 30rpx 30rpx 30rpx 0;
		border-bottom: 1rpx solid #f2f2f2;
		margin-left: 30rpx;
		font-size: 32rpx;
		color: #282828;
	}

	.personal-data .list .item .phone {
		width: 160rpx;
		height: 56rpx;
		font-size: 24rpx;
		color: #fff;
		line-height: 56rpx;
		border-radius: 32rpx
	}

	.personal-data .list .item .pictrue {
		width: 88rpx;
		height: 88rpx;
	}

	.personal-data .list .item .pictrue image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}

	.personal-data .list .item .input {
		width: 415rpx;
		text-align: right;
		color: #868686;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}

	.personal-data .list .item .input .id {
		width: 305rpx;
	}

	.personal-data .list .item .input .iconfont {
		font-size: 35rpx;
	}

	.personal-data .modifyBnt {
		font-size: 32rpx;
		color: #fff;
		width: 690rpx;
		height: 90rpx;
		border-radius: 50rpx;
		text-align: center;
		line-height: 90rpx;
		margin: 76rpx auto 0 auto;
		background: linear-gradient(to right, $tc, $tc2);
	}

	.personal-data .modifyBnt2 {
		font-size: 32rpx;
		width: 690rpx;
		height: 90rpx;
		border-radius: 50rpx;
		text-align: center;
		line-height: 90rpx;
		margin: 76rpx auto 0 auto;
		color: $tc;
		border: 1px solid $tc;

	}


	.personal-data .hoversubmit {
		background: #f7f7f7;
		color: #acacb3;
	}

	.personal-data .logOut {
		font-size: 32rpx;
		text-align: center;
		width: 690rpx;
		height: 90rpx;
		border-radius: 45rpx;
		margin: 30rpx auto 0 auto;
	}

	.avatar-box {
		width: 96rpx;
		height: 96rpx;

		image {
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}
	}

	.acea-row {
		display: flex;
		flex-wrap: wrap;
	}

	.acea-row.row-between-wrapper {
		align-items: center;
		justify-content: space-between;
	}

	.bg-color {
		background-color: #333;
	}

	.getbutton {
		position: absolute;
		width: 96rpx;
		height: 96rpx;
		opacity: 0;
		right: 30rpx;
		// margin-top: 180rpx;
	}
</style>