<template>
	<view class="user" :class="$store.state.AppStyle" style="background-color: #f6f6f6;height: 100vh;">
		<view class="header" :style="[{height:CustomBar + 'px'}]">
			<view class="cu-bar bg-white" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px'}">
				<view class="action" @tap="back">
					<text class="cuIcon-back"></text>
				</view>
				<view class="content text-bold" :style="[{top:StatusBar + 'px'}]">
					<text v-if="type=='setInfo'">修改资料</text>
					<text v-if="type=='setSafe'">安全设置</text>
					<text v-if="type=='setPw'">修改密码</text>
				</view>
				<!--  #ifdef H5 || APP-PLUS -->
				<view class="action" @tap="userEdit">
					
				</view>
				<!--  #endif -->
			</view>
		</view>
		<view :style="[{padding:NavBar + 'px 10px 0px 10px'}]"></view>

		<form>
			<block v-if="type=='setInfo'">
			<view class="user-edit-header margin-top" style="background-size: cover;height: 450upx;display: flex;justify-content: center;align-items: center;" :style="{'background-image': 'url(' + userBg + ')'}">
				<view>
				<image :src="avatar"></image>
				<text class="cu-btn bg-gradual-blue radius" style="margin-right: 20upx;" @tap="toAvatar">更换头像</text>
				<text class="cu-btn bg-gradual-orange radius" @tap="toBg">更换背景</text>
				</view>
			</view>
			
			<view class="cu-form-group margin-top">
				<view class="title">性别</view>
				<radio-group class="block" @change="RadioChange">
					<label><text class="tn-margin-right-sm">不展示</text>
						<radio class="cyan tn-margin-right-lg" :class="url=='bm'?'checked':''"
							:checked="url=='bm'?true:false" value="bm"></radio>
					</label>
					<label><text class="tn-margin-right-sm">男</text>
						<radio class="cyan tn-margin-right-lg" :class="url=='man'?'checked':''"
							:checked="url=='man'?true:false" value="man"></radio>
					</label>
					<label><text class="tn-margin-right-sm">女</text>
						<radio class="cyan tn-margin-right-lg" :class="url=='woman'?'checked':''"
							:checked="url=='woman'?true:false" value="woman"></radio>
					</label>
				</radio-group>
			</view>
			<view class="cu-form-group">
				<view class="title">名称</view>
				<input placeholder="请输入名称" name="input" v-model="screenName"></input>
			</view>
			<view class="cu-form-group align-start">
				<view class="title">简介</view>
				<textarea v-model="introduce" placeholder="输入个人简介"></textarea>
			</view>
			
			</block>
			<block v-if="type=='setSafe'">
			<view class="cu-form-group margin-top">
				<view class="title">用户名</view>
				<input name="input" disabled="disabled" :value="name"></input>
			</view>
			<view class="cu-form-group" @tap="toEmail">
				<view class="title">邮箱</view>
				<input placeholder="未绑定" disabled="disabled" name="input" :value="mail"></input>
				<view class="action">
					<text class="cuIcon-right"></text>
				</view>
			</view>
			<view class="cu-form-group" @tap="toPhone">
				<view class="title">手机号</view>
				<input placeholder="未绑定" disabled="disabled" name="input" :value="phone"></input>
				<view class="action">
					<text class="cuIcon-right"></text>
				</view>
			</view>
			<view class="cu-form-group" @tap="toBind">
				<view class="title">第三方账号绑定</view>
				<view class="action">
					<text class="cuIcon-right"></text>
				</view>
			</view>
			</block>
			<block v-if="type=='setPw'">
			<view class="cu-form-group margin-top">
				<view class="title">密码</view>
				<input placeholder="请输入密码" v-model="password" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">确认密码</view>
				<input placeholder="请再次输入密码" v-model="repassword" name="input"></input>
			</view>
			</block>
			<view class="all-btn margin-top" v-if="type!='setSafe'">
				<view class="user-btn flex flex-direction">
					<button class="cu-btn bg-blue margin-tb-sm lg" @tap="userEdit">保存修改</button>
				</view>
			</view>
		</form>
		<!--  #ifdef H5 || APP-PLUS -->
		<!--<view class="cu-list menu">

			
			 <view class="cu-item" @tap="toPay">
				<view class="content">
					<text>收款码设置</text>
				</view>
				<view class="action">
					<text class="cuIcon-right"></text>
				</view>
			</view> 
		</view>-->
		<!--  #endif -->
		<view class="cu-modal" :class="modalName=='DialogModal1'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">设置头像</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl text-left">
					<view>小程序中只能把自己的账号绑定成QQ邮箱，平台会自动获取您的QQ头像。</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		localStorage
	} from '../../js_sdk/mp-storage/mp-storage/index.js'
	// #ifdef H5 || APP-PLUS 
	import {
		pathToBase64,
		base64ToPath
	} from '../../js_sdk/mmmm-image-tools/index.js'
	// #endif
	export default {
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar: this.StatusBar + this.CustomBar,
				AppStyle: this.$store.state.AppStyle,
				uid: 0,
				name: '',
				screenName: '',
				password: '',
				repassword: '',
				mail: '',
				phone: "",
				url: 'bm',
				avatar: "",
				isHuaWei: this.$API.isHuaWei(),
				isTy: false,
				userBg: '',
				type: "",
				avatarNew: "",
				introduce: "",
				backif: 0,
				modalName: null,
				token: '',
				styleIndex: "",
			}
		},
		onPullDownRefresh() {
			var that = this;

		},
		onShow() {
			var that = this;
			// #ifdef APP-PLUS
			//plus.navigator.setStatusBarStyle("dark")
			// #endif
			that.userStatus();
			if (localStorage.getItem('toAvatar')) {
				var toAvatar = JSON.parse(localStorage.getItem('toAvatar'));
				that.avatarUpload(toAvatar.dataUrl);
			} else {
				console.log("没有头像缓存")
			}

		},
		onLoad(res) {
			var that = this;
			that.backif = res.backif;
			that.type = res.type;
			// #ifdef APP-PLUS || MP
			that.NavBar = this.CustomBar;
			// #endif
			that.styleIndex = that.$API.GetStyleIndex();
		},
		methods: {
			back() {
				uni.navigateBack({
					delta: 1
				});
			},
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
			validatePassword(password) {
				const regex = /^(?=.*[A-Za-z])(?=.*\d).{6,}$/;
				return regex.test(password);
			},
			userStatus() {
				var that = this;
				var token = "";
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;
				}
				that.$Net.request({

					url: that.$API.userStatus(),
					data: {
						"token": token
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 1) {
							that.uid = res.data.data.uid;
							that.screenName = res.data.data.screenName;
							that.name = res.data.data.name;
							that.mail = res.data.data.mail;
							that.url = res.data.data.url;
							that.token = res.data.data.token;
							that.avatar = res.data.data.avatar;
							that.userBg = res.data.data.userBg;
							that.introduce = res.data.data.introduce;
							that.phone = res.data.data.phone;
							if (localStorage.getItem('userinfo')) {

								var userInfo = JSON.parse(localStorage.getItem('userinfo'));
								if (userInfo.screenName) {
									that.screenName = userInfo.screenName;
								} else {
									that.screenName = userInfo.name;
								}
								if (res.data.data.customize) {
									userInfo.customize = res.data.data.customize;
								}
								if (res.data.data.lv) {
									userInfo.lv = res.data.data.lv;
								}
								if (res.data.data.isvip) {
									userInfo.isvip = res.data.data.isvip;
								}
								if (res.data.data.vip) {
									userInfo.vip = res.data.data.vip;
								}
								if (res.data.data.experience) {
									userInfo.experience = res.data.data.experience;
								}
								localStorage.setItem('userinfo', JSON.stringify(userInfo));
								// if(res.data.data.avatar){
								// 	that.userInfo = res.data.data.avatar;
								// }

							}

						}
					},
					fail: function(res) {
						uni.showToast({
							title: "网络开小差了哦",
							icon: 'none'
						})
					}
				})
			},
			validateString(str) {
				// 判断是否包含空格或中文空格
				if (/\s|　/.test(str)) {
					return false;
				}
				// 判断是否只包含空格
				if (/^\s+$/.test(str)) {
					return false;
				}
				return true;
			},
			userEdit() {
				var that = this;
				var token = "";
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;
				}
				if (that.password != "") {
					if (!that.validatePassword(that.password)) {
						uni.showToast({
							title: "密码必须包含字母、数字，且长度必须大于6",
							icon: 'none',
							duration: 1000,
							position: 'bottom',
						});
						return false
					}
					if (that.password != that.repassword) {
						uni.showToast({
							title: "两次密码不一致",
							icon: 'none',
							duration: 1000,
							position: 'bottom',
						});
						return false
					}

				}
				if (that.screenName.length > 10) {
					uni.showToast({
						title: "昵称太长了",
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false;
				}
				if (that.isValidString(that.screenName)) {
					uni.showToast({
						title: "昵称不能包含空格",
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				var data = {
					uid: that.uid,
					name: that.name,
					screenName: that.screenName,
					password: that.password,
					introduce: that.introduce,
					url: that.url,
				}
				if (that.avatarNew != '') {
					data.avatar = that.avatarNew;
				}
				uni.showLoading({
					title: "加载中"
				});
				that.$Net.request({

					url: that.$API.userEdit(),
					data: {
						"params": JSON.stringify(that.$API.removeObjectEmptyKey(data)),
						"token": token
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						//console.log(JSON.stringify(res))
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						if (res.data.code == 1) {
							//保存用户信息
							if (that.password != "") {
								localStorage.removeItem('userinfo');
								localStorage.removeItem('token');
								
								var timer = setTimeout(function() {
									var styleIndex = that.styleIndex;
									uni.redirectTo({
										url: '/pages/home/' + styleIndex
									});
									clearTimeout('timer')
								}, 1000)
								
							} else {
								var userInfo = JSON.parse(localStorage.getItem('userinfo'));
								userInfo.screenName = that.screenName;
								userInfo.url = that.url;
								userInfo.introduce = that.introduce;
								if (that.avatarNew != '') {
									userInfo.avatar = that.avatarNew;
								}
								that.avatarNew = '';
								localStorage.setItem('userinfo', JSON.stringify(userInfo));
								if (that.backif == 1) {
									that.back();
								}
								//that.getCacheInfo();
							}

						}
					},
					fail: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: "网络开小差了哦",
							icon: 'none'
						})
						uni.stopPullDownRefresh()
					}
				})
			},
			toEmail() {
				var that = this;

				uni.navigateTo({
					url: '/pages/user/mailedit'
				});
			},
			toPhone() {
				var that = this;

				uni.navigateTo({
					url: '/pages/user/phoneedit'
				});
			},
			toAddress() {
				var that = this;

				uni.navigateTo({
					url: '/pages/user/address'
				});
			},
			toPay() {
				var that = this;

				uni.navigateTo({
					url: '/pages/user/pay'
				});
			},
			toBg() {
				var that = this;
				if(that.isTy==false&&that.isHuaWei==1){
									that.showTC()
								}
				uni.navigateTo({
					url: '/pages/user/userBg'
				});
			},
			toAvatar() {
				var that = this;
				if(that.isTy==false&&that.isHuaWei==1){
									that.showTC()
								}
				uni.navigateTo({
					url: '/pages/user/userAvatar'
				});
			},
			toBind() {
				var that = this;

				uni.navigateTo({
					url: '/pages/user/userbind'
				});
			},
			RadioChange(e) {
				this.url = e.detail.value
			},
			toGravatar() {
				var that = this;
				that.hideModal();
				var url = "https://cn.gravatar.com/";
				// #ifdef APP-PLUS
				plus.runtime.openURL(url)
				// #endif
				// #ifdef H5
				window.open(url)
				// #endif
			},
			
			// #ifdef APP-PLUS
						//权限检测
						showTC(){
							var that = this;
							var tc1 = false;
							let _permissionID = 'android.permission.WRITE_EXTERNAL_STORAGE';
							let _permissionID2 = 'android.permission.CAMERA';
							plus.android.checkPermission(_permissionID2,
								granted => {
									if (granted.checkResult == -1) {
										console.log('无相机权限');
										uni.showModal({
											title: '权限申请说明',
											content: '我们将申请获取相机权限和访问相册权限，便于您使用拍照上传您的照片/视频及用于更换头像、意见反馈、保存相册、发布动态等场景。',
											cancelText: "取消",
											confirmText: "同意",
											showCancel: true,
											confirmColor: '#000',
											cancelColor: '#666',
											success: (res) => {
												if (res.confirm) {
													console.log('弹窗同意');
													tc1 = true;
													that.requestPermissions();
												}else{
													console.log('弹窗取消');
													that.isTy = false
													tc1 = true;
												}
											}
										})
										//还未授权当前查询的权限，打开权限申请目的自定义弹框
										that.$nextTick(() => {
											setTimeout(() => {
												that.ani = 'uni-' + that.type
											},30)
										})
									}
								},
								error => {
									console.log(error.message);
								}
							);
							plus.android.checkPermission(_permissionID,
								granted => {
									if (granted.checkResult == -1) {
										console.log('无相册权限');
										if(!tc1){
											uni.showModal({
												title: '权限申请说明',
												content: '我们将申请获取相机权限和访问相册权限，便于您使用拍照上传您的照片/视频及用于更换头像、意见反馈、保存相册、发布动态等场景。',
												cancelText: "取消",
												confirmText: "同意",
												showCancel: true,
												confirmColor: '#000',
												cancelColor: '#666',
												success: (res) => {
													if (res.confirm) {
														console.log('弹窗同意');
														return that.requestPermissions();
													}else{
														console.log('弹窗取消');
														that.isTy = false
													}
												}
											})
										}
										
										//还未授权当前查询的权限，打开权限申请目的自定义弹框
										that.$nextTick(() => {
											setTimeout(() => {
												that.ani = 'uni-' + that.type
											},30)
										})
									}
								},
								error => {
									console.log(error.message);
								}
							);
							
						},
						requestPermissions() {
							let _this = this;
						
								let _permissionID = 'android.permission.WRITE_EXTERNAL_STORAGE';
								let _permissionID2 = 'android.permission.CAMERA';
								
								plus.android.checkPermission(_permissionID2,
									granted => {
										if (granted.checkResult == -1) {
											//还未授权当前查询的权限，打开权限申请目的自定义弹框
											
											_this.$nextTick(() => {
												setTimeout(() => {
													_this.ani = 'uni-' + _this.type
												},30)
											})
										}
									},
									error => {
										console.log(error.message);
									}
								);
								plus.android.requestPermissions([_permissionID2],
									(e) => {
										//关闭权限申请目的自定义弹框
										_this.ani = '';
										_this.$nextTick(() => {
											
										})
										console.log(e,'kkkkk')
										if (e.granted.length > 0) {
											//当前查询权限已授权
											console.log('1已同意');
											plus.android.checkPermission(_permissionID,
												granted => {
													if (granted.checkResult == -1) {
														//还未授权当前查询的权限，打开权限申请目的自定义弹框
														
														_this.$nextTick(() => {
															setTimeout(() => {
																_this.ani = 'uni-' + _this.type
															},30)
														})
													}
												},
												error => {
													console.log(error.message);
												}
											);
											plus.android.requestPermissions([_permissionID],
												(e) => {
													//关闭权限申请目的自定义弹框
													_this.ani = '';
													_this.$nextTick(() => {
														
													})
													console.log(e,'kkkkk')
													if (e.granted.length > 0) {
														//当前查询权限已授权
														console.log('2已同意');
														_this.isTy = true
													}
													if (e.deniedAlways.length > 0) {
														//当前查询权限已被永久禁用，此时需要引导用户跳转手机系统设置去开启
														uni.showModal({
															title: '温馨提示',
															content: '您没有给予访问相册权限，不给予权限将无法使用该功能，立即去设置开启？',
															cancelText: "取消",
															confirmText: "去设置",
															showCancel: true,
															confirmColor: '#000',
															cancelColor: '#666',
															success: (res) => {
																if (res.confirm) {
																	_this.goSetting();
																}else{
																	_this.isTy = false
																}
															}
														})
													}
												})
										}
										if (e.deniedAlways.length > 0) {
											//当前查询权限已被永久禁用，此时需要引导用户跳转手机系统设置去开启
											uni.showModal({
												title: '温馨提示',
												content: '您没有给予使用相机权限，不给予权限将无法使用该功能，立即去设置开启？',
												cancelText: "取消",
												confirmText: "去设置",
												showCancel: true,
												confirmColor: '#000',
												cancelColor: '#666',
												success: (res) => {
													if (res.confirm) {
														_this.goSetting();
													}else{
														_this.isTy = false
													}
												}
											})
										}
									})
							
						},
						//跳转手机系统设置
						goSetting() {
								var Intent = plus.android.importClass("android.content.Intent");
								var Settings = plus.android.importClass("android.provider.Settings");
								var Uri = plus.android.importClass("android.net.Uri");
								var mainActivity = plus.android.runtimeMainActivity();
								var intent = new Intent();
								intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
								var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
								intent.setData(uri);
								mainActivity.startActivity(intent);
						},
						// #endif
			
			avatarUpload(base64) {

				var that = this;
				var token = "";
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;
				}
				base64ToPath(base64)
					.then(path => {
						var file = path;
						const uploadTask = uni.uploadFile({
							url: that.$API.upload(),
							filePath: file,
							//  header: {
							// "Content-Type": "multipart/form-data",
							// },
							name: 'file',
							formData: {
								'token': token
							},
							success: function(uploadFileRes) {
								setTimeout(function() {
									uni.hideLoading();
								}, 1000);

								var data = JSON.parse(uploadFileRes.data);
								//var data = uploadFileRes.data;


								if (data.code == 1) {
									// uni.showToast({
									// 	title: data.msg,
									// 	icon: 'none'
									// })
									that.avatar = data.data.url;
									that.avatarNew = data.data.url;
									localStorage.removeItem('toAvatar');
									that.userEdit();
									//console.log(that.avatar)

								} else {
									uni.showToast({
										title: "头像上传失败，请检查接口",
										icon: 'none'
									})
								}
							},
							fail: function() {
								setTimeout(function() {
									uni.hideLoading();
								}, 1000);
							}


						});
					})
					.catch(error => {
						console.error("失败" + error)
					})
			},
			isValidString(str) {
				return /\s/g.test(str);
			}
		}
	}
</script>

<style>
	.radius{
		border-radius: 100upx;
	}
</style>