<template>
	<view>

		<uni-nav-bar id="nav-bar" status-bar="true" @clickLeft="onBack()" :title="pageTitle" color="#000000" fixed="true"
		 :border="false">
			<view slot="left">
				<view v-if="!bNewUser" class=" flex align-center margin-left">
					<image class="p-left-arrow" src="../../../static/p-left-arrow.png"></image>
				</view>
			</view>
			<view v-if="bNewUser" slot="right">
				<text class="text-df text-purple margin-right-sm" @tap="onNavUser">下一步</text>
			</view>
		</uni-nav-bar>

		<view class="card-view">
			<view class="avatar-group" @tap="ChooseImage">
				<view class="avatar-size ">
					<!-- 保持纵横比缩放图片 -->
					<image class="avatar-img round bg-black" mode="aspectFit" :src="changeData.avatarUrl"></image>
					<image class="avatar-tag " src="/static/camera.png"></image>
				</view>
				<view class="text-upload">
					<text>请上传头像</text>
				</view>
			</view>
			<view class="item-group flex align-center">
				<view class="text-grey padding-sm margin-name text-width ">
					昵称
				</view>

				<input maxlength="8" placeholder="输入名字" :value="changeData.userName" @input="onInput('name',$event)"></input>


			</view>
			<view class="item-group flex align-center" @tap="showModal" data-target="showPickerModal" data-type="gender">
				<view class="text-grey padding-sm margin-name text-width flex">性别
					<view v-if="bNewUser" style="position: relative; width: 4px;">
						<!-- <view class="cu-tag badge"></view> -->
					</view>
				</view>
				<view class="text-bold">{{changeData.gender==0?'男':'女'}}</view>
			</view>
			<view class="item-group flex align-center" @tap="showModal" data-target="showPickerModal" data-type="birthday">
				<view class="text-grey padding-sm margin-name text-width flex">生日
					<view v-if="bNewUser" style="position: relative; width: 4px;">
						<!-- <view class="cu-tag badge"></view> -->
					</view>
				</view>
				<view class="text-bold">{{changeData.sBirthday}}</view>
			</view>

			<view class="item-group flex align-center" @tap="showModal" data-target="showPickerModal" data-type="city">
				<view class="text-grey padding-sm margin-name text-width flex">城市
					<view v-if="bNewUser" style="position: relative; width: 4px;">
						<!-- <view class="cu-tag badge"></view> -->
					</view>
				</view>
				<view class="text-bold">{{changeData.city.label}}</view>
			</view>

			<view class="flex justify-start  ">
				<view class="text-grey padding-sm margin-name text-width flex-shrink">个性签名</view>
				<textarea class="sign-text text-bold" maxlength="50" placeholder="在这里留下你的签名吧!" :value="changeData.signature!=='null'?changeData.signature:''"
				 @input="onInput('signature',$event)"></textarea>
			</view>
		</view>
		<view class="card-view margin-top ">
			<view class="cu-item shadow padding-top padding-bottom">
				<view class="content">
					<view class="item-group" @tap="showModal" data-target="showPickerModal" data-type="height">
						<view class="text-grey padding-sm margin-name text-width flex">身高
							<view v-if="bNewUser" style="position: relative; width: 4px;">
								<!-- <view class="cu-tag badge"></view> -->
							</view>
						</view>
						<view class="text-bold">{{changeData.height}} cm</view>
					</view>
					<view class="item-group" @tap="showModal" data-target="showPickerModal" data-type="weight">
						<view class="text-grey padding-sm margin-name text-width flex">体重
							<view v-if="bNewUser" style="position: relative; width: 4px;">
								<!-- <view class="cu-tag badge"></view> -->
							</view>
						</view>
						<view class="text-bold">{{changeData.weight}} 公斤</view>
					</view>
				</view>
			</view>

		</view>

		<view class="card-view margin-top">
			<view class="cu-item shadow padding-top-sm padding-bottom-sm flex justify-between">
				<view class="content">
					<view class="item-group">
						<view class="text-grey padding-sm margin-name text-width flex">手机
						</view>
						<view class="text-bold">{{phoneNumber!==''?phoneNumber:'未绑定' }}</view>
					</view>

				</view>
				<view class="right-container" @tap="onBindPhone">
					<image style="width: 48rpx;height: 48rpx;" src="/static/bindPhone.png"></image>
					<text class="text-grey text-sm" style="margin: 0 24rpx;">{{phoneNumber!==''?'已绑定':'去绑定'}}</text>
					<view class="only-arrow"></view>
				</view>
			</view>

		</view>

		<view v-if="bInstallWechat&&!bHideWeixin" class="card-view margin-top ">
			<view class="cu-item  shadow padding-top-sm padding-bottom-sm flex justify-between">
				<view class="content">
					<view class="item-group">
						<view class="text-grey padding-sm margin-name text-width flex">微信

						</view>
						<view class="text-bold">{{openid!==''?'已关联微信':'未关联微信'}} </view>
					</view>

				</view>

				<view class="right-container" @tap="onBindWeixin">
					<image style="width: 48rpx;height: 48rpx;" src="/static/img/weixin_b.png"></image>
					<text class="text-grey text-sm" style="margin: 0 24rpx;">{{openid!==''?'已绑定':'去绑定'}}</text>
					<view class="only-arrow"></view>
				</view>
			</view>

		</view>

		<view v-if="!bNewUser" class="flex justify-center" style="margin: 32px 0 32px 0;">
			<view class="btn-confirm" @tap="onNavUser">保存</view>
		</view>

		<view class="cu-modal bottom-modal" :class="modalName=='showPickerModal'?'show':''" @touchmove.stop.prevent="moveHandle">
			<view class="cu-dialog" style="border-top-right-radius: 20rpx; border-top-left-radius: 20rpx;">
				<myPicker v-if="modalName == 'showPickerModal' ? true:false" :pickerObj="pickerObj" @confirmEvent="onConfirm"
				 @cancelEvent="hideModal">
				</myPicker>
			</view>
		</view>

		<view class="cu-modal" :class="modalName=='showBindModal'?'show':''" @touchmove.stop.prevent="moveHandle">
			<view class="cu-bind-modal">
				<view style="position: absolute; top: 0; left: 0; width: 100%; height:100%;">
					<image style="position: absolute;top: 0;left: 0; width: 100%;height: 100%;" src="../../../static/modelBg.png"></image>
				</view>
				<view class="flex flex-direction justify-between " style="position: relative; height: 100%;">
					<view class="flex justify-around justify-center align-center" style="margin: 170rpx 30rpx 0 30rpx;">
						<view style="width: 80rpx;height: 2rpx;border-radius: 2px; background-color: #cbcdcf;"></view>
						<view class="make-text-bPurple" style=" font-size: 20px;">{{bindModal.title}}</view>
						<view style="width: 80rpx;height: 2rpx;border-radius: 2px;background-color: #cbcdcf;"></view>
					</view>
					<view class="text-16px">{{bindModal.content}}</view>

					<view class="flex justify-around align-center" style=" border-top: 1rpx solid #EEEEEE; margin-bottom: 2px;">
						<view class="flex justify-center align-center  text-16px" style="width: 100%;height: 123rpx;" @tap="hideModal">稍后再说</view>
						<view style="height: 123rpx;width: 1px;background-color: #EEEEEE;"></view>
						<view class="flex justify-center align-center  text-16px" style="width: 100%;height: 123rpx;" @tap="hideBindModal">确定</view>
					</view>
				</view>


			</view>
		</view>
	</view>
</template>

<script>
	import myPicker from '@/components/slambb-picker/slambb-picker.vue';
	import pickerData from '@/components/slambb-picker/picker.js';
	import config from '@/common/config.js';
	import reqUtil from "@/util/util-js/requstUtil.js";
	import date from "@/util/util-js/date.js";

	import {
		mapState,
		mapMutations
	} from 'vuex'
	export default {
		computed: mapState(['bNewUser', 'height', 'weight', 'userName', 'avatarUrl', 'days', 'signature', "gender",
			'birthday', 'city', 'phoneNumber', 'openid','bInstallWechat','bHideWeixin'
		]),
		components: {
			myPicker
		},
		data() {
			let pickerObj = {
				pickerLeftList: pickerData.getWeightList().leftList,
				pickerRightList: pickerData.getWeightList().rightList,
				pickerType: "doubleItem",
				pickerUnit: "斤",
				pickerTitle: "记体重",
				defaultValue: 0
			};

			return {
				modalName: null,
				//选择器对象
				pickerObj,
				bChoose: false,
				// oldData: null,
				changeData:null,
				//是否可以更新
				bCanUpdate: false,

				pageTitle: "完善资料",

				bLoading: false,

				bindModal: {
					title: '解绑',
					content: '绑定账号可以快速登录'
				}
			}
		},
		onLoad() {
			let s = this.birthday.replace(/-/g, "/");
			var dateTemp = new Date(s);
			// this.oldData = {
			// 	'height': this.height,
			// 	'weight': this.weight,
			// 	'userName': this.userName,
			// 	'avatarUrl': this.avatarUrl,
			// 	'signature': this.signature,
			// 	"gender": this.gender,
			// 	"cityCode": this.city.cityCode,
			// 	'birthday': this.birthday,
			// 	"city":this.city,
			// 	"sBirthday": date.formatDate(dateTemp)
			// };
			
			this.changeData = {
				'height': this.height,
				'weight': this.weight,
				'userName': this.userName,
				'avatarUrl': this.avatarUrl,
				'signature': this.signature,
				"gender": this.gender,
				"cityCode": this.city.cityCode,
				'birthday': this.birthday,
				"city":this.city,
				"sBirthday": date.formatDate(dateTemp)
			};

			if (this.bNewUser) {
				this.pageTitle = "基础资料";
				this.$store.state.bNewGuide = true;
			}
		},
		methods: {
			...mapMutations(['login']),
			ChooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						this.bChoose = true;
						let size = res.tempFiles[0].size;
						console.log('res:',res);
						if(size<=10000000){
							this.changeData.avatarUrl = res.tempFiles[0].path;
						}else{
							uni.showToast({
								title:'上传的图片不能超过10M',
								icon:'none',
							})
						}
					}
				});
			},
			onInput(type, event) {
				// console.log(type, "==", event.detail.value);
				if (type == "name") {
					this.changeData.userName = event.detail.value;
					this.bCanUpdate = true;
				} else if (type == "signature") {
					this.changeData.signature = event.detail.value;
					this.bCanUpdate = true;
				}
			},
			/**
			 * 由于性别和生日是有默认值，所以不用检测
			 */
			onCheck() {
				if (this.height == 0) {
					uni.showToast({
						title: "请选择身高",
						icon: "none"
					})
					return false;
				} else
				if (this.weight == 0) {
					uni.showToast({
						title: "请选择体重",
						icon: "none"
					})
					return false;
				}
				return true;
			},
			//上传用户数据
			onNavUser() {
				let that = this;
				
				uni.showToast({
					title: "",
					icon: "loading",
					mask: true,
					duration: 10000
				})
				if (that.bLoading) return;
				that.bLoading = true;
				let data = {
					"filePath": this.changeData.avatarUrl,
					"username": this.changeData.userName,
					"birthday": this.changeData.birthday,
					"signature": this.changeData.signature,
					"gender": this.changeData.gender,
					"cityCode": this.changeData.city.cityCode,
					"weight": this.changeData.weight,
					"height": this.changeData.height,
				}
				console.log("更新时候的 data信息：",data);
				//如果选择了图片，用图片接口更新数据
				if (that.bChoose) {
					reqUtil.reqUpload(config.URL.USERINFOADDAVATAR, data, that.changeData.avatarUrl).then(res => {
							console.log('reqUpload USERINFOADDAVATAR =====', res);
							uni.hideToast();
							that.bLoading = false;
							if (res.code == 0) {
								uni.showToast({
									title: "更新成功",
									mask: true,
									duration: 1000
								})
								that.bChoose = false;
								// that.$store.state.avatarUrl = res.data.avatarUrl;
								that.login(res.data);
								// 如果是新用户，跳转首页

								setTimeout(() => {
									if (that.bNewUser) {
										that.$store.state.bNewUser = false;
										// uni.redirectTo({
										// 	url: "../../personal-page/personal/personal"
										// })
										uni.redirectTo({
											url:'../firstPlan/firstPlan'
										})
									} else {
										uni.navigateBack({
											delta: 1
										})
									}
								}, 1000);

							}

						},
						e => {
							console.log(e);
							that.bLoading = false;
							uni.showModal({
								title: '错误',
								content: '更新头像失败，是否重新更新?',
								confirmText: '是的',
								success: (res) => {
									if (res.confirm) {
										that.onNavUser();
									}
								}
							})
						});
				} else {
					//如果只修改数据，走数据接口
					if (!that.bNewUser && !that.bCanUpdate) {
						uni.showToast({
							title: "数据无改动",
							icon: "none",
							mask: true,
							duration: 1000
						})
						that.bLoading = false;
						return;
					}
					reqUtil.requestData(config.URL.USERINFOADD, data, "POST").then(res => {
							console.log('requestData USERINFOADD =====', res);
							uni.hideToast();
							that.bLoading = false;
							if (res.code == 0) {
								uni.showToast({
									title: "更新成功",
									mask: true,
									duration: 1000
								})
								that.bCanUpdate = false;
								that.login(res.data);
								setTimeout(() => {
									if (that.bNewUser) {
										that.$store.state.bNewUser = false;
										// uni.redirectTo({
										// 	url: "../../personal-page/personal/personal"
										// })
										uni.redirectTo({
											url:'../firstPlan/firstPlan'
										})
									} else {
										uni.navigateBack({
											delta: 1
										})
									}
								}, 1000);
							}
						},
						e => {
							console.log(e);
							that.bLoading = false;
							uni.showModal({
								title: '错误',
								content: '更新数据失败，是否重新更新?',
								confirmText: '是的',
								success: (res) => {
									if (res.confirm) {
										that.onNavUser();
									}
								}
							})
						});
				}




			},

			onBack() {
				uni.navigateBack({
					delta: 1
				})
			},

			showModal(e) {
				this.pikerType = e.currentTarget.dataset.type
				switch (this.pikerType) {
					case "weight":
						this.$set(this.pickerObj, 'pickerLeftList', pickerData.getWeightList().leftList);
						this.$set(this.pickerObj, 'pickerRightList', pickerData.getWeightList().rightList);
						this.$set(this.pickerObj, 'pickerType', "doubleItem");
						this.$set(this.pickerObj, 'pickerUnit', "公斤");
						this.$set(this.pickerObj, 'pickerTitle', "记体重");
						this.$set(this.pickerObj, 'defaultValue', this.weight);
						this.$set(this.pickerObj, 'showInput', true);
						break;
					case "height":
						this.pickerObj = {};
						this.$set(this.pickerObj, 'pickerLeftList', pickerData.getHeightList().leftList);
						// pickerData.getHeightList().rightList
						this.$set(this.pickerObj, 'pickerRightList', []);
						this.$set(this.pickerObj, 'pickerType', "singleItem");
						this.$set(this.pickerObj, 'pickerUnit', "厘米");
						this.$set(this.pickerObj, 'pickerTitle', "记身高");
						this.$set(this.pickerObj, 'defaultValue', this.height);
						this.$set(this.pickerObj, 'showInput', true);
						break;
					case "birthday":
						this.pickerObj = {};
						this.$set(this.pickerObj, 'pickerType', "dateItem");
						this.$set(this.pickerObj, 'pickerTitle', "记生日");
						this.$set(this.pickerObj, 'showInput', false);
						break;
					case "gender":
						this.pickerObj = {};
						this.$set(this.pickerObj, 'pickerLeftList', pickerData.getGenderList().genderList);
						this.$set(this.pickerObj, 'pickerRightList', []);
						this.$set(this.pickerObj, 'pickerType', "singleItem");
						this.$set(this.pickerObj, 'pickerTitle', "性别");
						this.$set(this.pickerObj, 'defaultValue', "男");
						this.$set(this.pickerObj, 'showInput', false);
						break;
					case "city":
						this.pickerObj = {};
						this.$set(this.pickerObj, 'pickerType', "city");
						this.$set(this.pickerObj, 'pickerTitle', "省市区");
						this.$set(this.pickerObj, 'defaultValue', this.city.value);
						this.$set(this.pickerObj, 'showInput', false);
						break;

				}
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
			moveHandle() {
				return;
			},
			onConfirm(data) {
				console.log(data);
				// let data = e.detail.__args__[0];
				switch (this.pikerType) {
					case "weight":
						if (data.value != this.weight) {
							this.bCanUpdate = true;
							this.changeData.weight = data.value;
						}
						break;
					case "height":
						if (data.value != this.height) {
							this.bCanUpdate = true;
							this.changeData.height = data.value;
						}
						break;
					case "birthday":
						this.bCanUpdate = true;
						let nDate = new Date();
						nDate.setFullYear(data.value[0], data.value[1] - 1, data.value[2]);
						this.changeData.sBirthday = date.formatDate(nDate);
						this.changeData.birthday = date.formatTime(nDate);
						break;
					case "gender":
						if (data.value != this.gender) {
							this.bCanUpdate = true;
							this.changeData.gender = data.index;
						}
						break;
					case "city":
						if (data.value.cityCode != this.cityCode) {
							this.bCanUpdate = true;
							this.changeData.city = data.value;
						}
						break;
				}

				this.hideModal();
			},


			onBindPhone() {
				// //TODO 弹出解绑提示
				// this.bindModal = {
				// 	title: '解绑',
				// 	content: '你确定要解绑手机吗?',
				// 	type: "deletePhoneNumber"
				// };
				// this.modalName = "showBindModal";
				if (!this.phoneNumber) {
					uni.navigateTo({
						url: "../../login-page/bindPhone/bindPhone"
					})
				} else {
					uni.showToast({
						title: '已绑定手机',
						icon: 'none',
					})
				}

			},
			onBindWeixin() {
				if (this.openid) {
					uni.showToast({
						title: '已绑定微信',
						icon: 'none'
					})
				} else {
					this.bindModal = {
						title: '微信绑定',
						content: '“哔蹦”想打开“微信”',
						type: 'bindWxInfo'
					};
					this.modalName = "showBindModal";
				}
			},
			hideBindModal() {
				this.modalName = null;
				console.log(this.bindModal);
				let _self = this;
				if (this.bindModal.type == 'bindWxInfo') {
					// 绑定微信
					// #ifdef APP-PLUS
					this.oauth("weixin");
					// #endif

					// #ifndef APP-PLUS
					uni.showToast({
						title: "只支持app端",
						icon: "none"
					})

					// #endif
				} else if (this.bindModal.type == 'deletePhoneNumber') {
					//弹框解绑手机
					reqUtil.requestData(config.URL.DELETEPHONE, {}).then(res => {
							console.log('DELETEPHONE请求返回：', res);
							if (res.code == 0) {
								uni.showToast({
									title: "解绑手机号成功",
									mask: true,
									duration: 1000
								})
								_self.$store.state.phoneNumber = '';

							} else {
								uni.showToast({
									title: "解绑手机号失败",
									mask: true,
									icon: 'none',
									duration: 1000
								})
							}


						},
						e => {
							console.log(e)
						});
				}
			},
			oauth(value) {
				let _self = this;
				uni.showToast({
					title: "",
					icon: "loading",
					duration: 10000
				})
				uni.login({
					provider: value,
					success: (res) => {
						console.log('code11:', res);
						// android 端绑定微信信息
						let wxInfo = {
							openid: res.authResult.openid,
							unionid: res.authResult.unionid
						};

						reqUtil.requestData(config.URL.BINDWXINFO, {
							openid: res.authResult.openid,
							unionid: res.authResult.unionid
						}).then(res => {
								console.log('BINDWXINFO请求返回：', res);
								uni.hideToast();
								if (res.code == 0) {
									uni.showToast({
										title: "绑定微信成功",
										mask: true,
										duration: 1000
									})
									_self.$store.state.openid = wxInfo.openid;
								} else if (res.code == 212) {
									uni.showToast({
										title: "此微信已被绑定,请使用其他微信",
										mask: true,
										icon: 'none',
										duration: 3000
									})
									// // 微信授权登录对象
									// let aweixin = null;
									// // 当前环境支持的所有授权登录对象
									// let auths = {};
									// plus.oauth.getServices(function(services) {
									// 	for (var i in services) {
									// 		auths[services[i].id] = services[i];
									// 	}
									// 	aweixin = auths['weixin'];
									// 	aweixin.logout(function(e) {
									// 		// plus.nativeUI.alert("注销登录认证成功!");
									// 		console.log("注销登录认证成功");
									// 	}, function(e) {
									// 		// plus.nativeUI.alert("注销登录认证失败: " + JSON.stringify(e));
									// 		console.log("注销登录认证失败: " + JSON.stringify(e));
									// 	});
									// }, function(e) {
									// 	plus.nativeUI.alert("获取登录授权服务列表失败：" + JSON.stringify(e));
									// });

								} else {
									uni.showToast({
										title: "绑定微信失败",
										mask: true,
										icon: 'none',
										duration: 1000
									})
								}


							},
							e => {
								console.log(e);
								uni.hideToast();
							});

					},
					fail: (err) => {
						console.error('授权登录失败：' + JSON.stringify(err));
					}
				});
			},
		}
	}
</script>

<style>
	.flex-shrink {
		flex-shrink: 0;
	}

	.avatar-group {
		margin-top: 30px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.avatar-size {
		position: relative;
		width: 187.33rpx;
		height: 186.67rpx;
	}

	.avatar-img {
		width: 187.33rpx;
		height: 186.67rpx;
		border: 3px solid #9997fc;
	}


	.avatar-tag {
		position: absolute;
		right: 0;
		bottom: 0;

		width: 46rpx;
		height: 46rpx;
	}

	.text-upload {
		font-size: 13px;
		color: rgba(166, 166, 166, 1);
		padding: 10px 0 45px 0;
	}

	.text-width {
		width: 160rpx;
		/* background: #007AFF; */
	}

	.margin-name {
		margin: 0 0 0 66rpx;
	}

	.item-group {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}

	.item-group input {
		font-weight: bold;

	}

	.sign-text {
		margin: 20rpx 30rpx 30rpx 0;
		height: 4.6em;
		width: 100%;
		line-height: 1.2em;
		flex: 1;
		font-size: 28rpx;
		/* padding: 1rpx; */
		/* border: 1rpx solid #007AFF; */
	}

	/* 	.btn-confirm {
		width: 636rpx;
		height: 102rpx;
		background-color: rgba(151, 151, 255, 1);
		border-radius: 10px;
	} */

	.btn-confirm {
		width: 636rpx;
		height: 102rpx;
		background-color: rgba(151, 151, 255, 1);
		border-radius: 10px;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 17px;
		color: #FFFFFF;
	}

	.right-container {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}
</style>
