<template>
	<view id="user-setting">
		<view class="head_box">
			<view class="head_message">
				个人头像
			</view>
			<view class="head_right">
				<view class="headImg" @tap="changeImage">
					<image :src="detail.avatar" alt></image>
				</view>
				<view class="iconfont icon-jiantou head_under"></view>
			</view>
		</view>
		<view class="user_setting">
			<view class="code">
				<view class="detail">昵称</view>
				<input type="text" placeholder="填写您的昵称" @input="changeName" :value="detail.nick_name"></input>
			</view>
			<view class="code">
				<view class="detail">性别</view>
				<picker :value="selectedIndex" :range="list" @change="change">
					<!--<view class="picker">{{list[selectedIndex]}}</view>-->
					<input type="text" placeholder="选择你的性别" disabled :value="list[selectedIndex]"></input>
				</picker>
				<view class="iconfont icon-jiantou under"></view>
				<!--<input type="text" placeholder="选择你的性别"/>-->
			</view>
			<view class="code" v-if="isChangeB">
				<view class="detail">出生日期</view>
				<picker mode="date" :end="end" @change="changeDate">
					<input type="text" placeholder="请输入出生日期" disabled :value="birthdaydate"></input>
				</picker>
				<view class="iconfont icon-jiantou under"></view>
			</view>
			<view class="code" v-if="!isChangeB" @tap="changeB">
				<view class="detail">出生日期</view>
				<view style="position: relative; flex: 1">
					<input type="text" placeholder="请输入出生日期" disabled :value="birthdaydate"></input>
					<!--<view class="iconfont icon-jiantou under"></view>-->
				</view>

			</view>
			<!-- <view class="code">
            <view class="detail">QQ</view>
            <input type="text" placeholder="请输入QQ号码" :value="QQnum" @input="changeQQ"></input>
        </view> -->
			<view class="code">
				<view class="detail">手机号码</view>
				<input type="text" placeholder="请输入手机号码" :value="mobileNum" disabled></input>
				<view @tap="changeMobile" class="iconfont icon-jiantou phone_under"></view>
			</view>
			<!-- <view class="code">
            <view class="detail">邮箱</view>
            <input type="text" placeholder="请输入邮箱" :value="emailSet" @input="changeEmail"></input>
        </view> -->
		</view>
		<view class="submit" @tap="updateUserInfo">
			<button type="primary" :style="'background: ' + config.mainColor">确定</button>
		</view>
	</view>
	


</template>
<script>
	import {
		pageLogin,
		getUrl,
		config,
		is
	} from '@/common/js/utils.js';

	export default {
		data() {
			return {
				list: ['男', '女'],
				selectedIndex:-1,
				detail: "",
				birthdaydate: '',
				QQnum: '',
				mobileNum: "",
				emailSet: "",
				config: '',
				isChangeB: '',
				newImage:''
			};
		},

		onShow() {
			pageLogin(getUrl(), () => {
				this.gitUserInfo();
			});
		},

		onLoad() {
			// 第三方平台配置颜色
			var bgConfig = this.$cookieStorage.get('globalConfig') || '';
			var initData = this.$cookieStorage.get('init');

			this.config = bgConfig;
			this.initData = initData;

			Date.prototype.format = function(fmt) {
				var o = {
					"M+": this.getMonth() + 1,
					//月份
					"d+": this.getDate(),
					//日
					"h+": this.getHours(),
					//小时
					"m+": this.getMinutes(),
					//分
					"s+": this.getSeconds(),
					//秒
					"q+": Math.floor((this.getMonth() + 3) / 3),
					//季度
					"S": this.getMilliseconds() //毫秒

				};

				if (/(y+)/.test(fmt)) {
					fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
				}

				for (var k in o) {
					if (new RegExp("(" + k + ")").test(fmt)) {
						fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
					}
				}

				return fmt;
			};

			var time = new Date().format("yyyy-MM-dd");
			this.end = time;
		},
		methods: {
			change: function(e) {
				// console.log(e);
				// 修改选中项文案
				this.setData({
					selectedIndex: e.detail.value
				});
			},

			changeName(e) {
				this.setData({
					'detail.nick_name': e.detail.value
				});
			},

			changeDate(e) {
				this.setData({
					birthdaydate: e.detail.value
				});
			},

			changeQQ(e) {
				this.setData({
					QQnum: e.detail.value
				});
			},

			changeB() {
				wx.showModal({
					content: '暂时无法修改',
					showCancel: false
				});
			},

			changeMobile() {
				wx.navigateTo({
					url: '/pages/user/bindingphone/bindingphone'
				});
			},

			changeEmail(e) {
				this.setData({
					emailSet: e.detail.value
				});
			},

			gitUserInfo() {
				this.$http.get({
					api: 'api/me',
					header: {
						Authorization: this.$cookieStorage.get('user_token')
					}
				}).then(res => {
					if (res.data.status) {
						var sex = res.data.data.sex;
						var index = this.list.findIndex(val => {
							return val == sex;
						});
						if (index == -1) index = "";
						var isChangeB = true;

						if (this.initData && this.initData.vip_plan_status == 1 && res.data.data.birthday != '') {
							isChangeB = false;
						}

						// this.setData({
						//   detail: res.data.data,
						//   selectedIndex: index,
						//   birthdaydate: res.data.data.birthday,
						//   QQnum: res.data.data.qq,
						//   mobileNum: res.data.data.mobile,
						//   emailSet: res.data.data.email,
						//   isChangeB: isChangeB
						// });
					
						this.detail = res.data.data;
						this.selectedIndex = index;
						this.birthdaydate = res.data.data.birthday;
						this.QQnum = res.data.data.qq;
						this.mobileNum = res.data.data.mobile;
						this.emailSet = res.data.data.email;
						this.isChangeB = isChangeB;

					}
				});
			},

			changeImage: function() {
				uni.chooseImage({
					count: 1,
					 sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					 sourceType: ['album'], //从相册选择
					success: res => {
						var tempFilePaths = res.tempFilePaths;
						this.newImage = tempFilePaths[0];
						var token = this.$cookieStorage.get('user_token');
						/* this.$http.uploadFile({
						  header: {
						    'content-type': 'multipart/form-data',
						    Authorization: token
						  },
						  api: 'api/users/upload/avatar',
						  //仅为示例，非真实的接口地址
						  filePath: tempFilePaths[0],
						  name: 'avatar_file'
						}).then(res => { 
						  console.log(result);
						  this.setData({
						    'detail.avatar': result.data.url
						  });
						}); */
						uni.uploadFile({
							header: {
								Authorization: token
							},
							url: config.GLOBAL.baseUrl + 'api/users/upload/avatar',
							filePath: tempFilePaths[0],
							fileType: 'image',
							name: 'avatar_file',
							success: res => {
								var result = JSON.parse(res.data); 
								this.setData({
									'detail.avatar': result.data.url
								});
							}
						})
					}
				});
			},

			updateUserInfo() {
				var message = null;

				if (!this.detail.nick_name) {
					message = "请填写用户昵称";
				} 
				/* else if (this.emailSet != "" && !is.email(this.emailSet)) {
					message = "请填写正确的邮箱";
				} */
				// else if (!this.birthdaydate) {
				//      message = "请选择出生日期";
				//    }

				if (message) {
					wx.showModal({
						content: message,
						showCancel: false
					});
					return;
				} // this.updateBirthday();

				var token = this.$cookieStorage.get('user_token');
				this.$http.post({
					api: 'api/users/update/info',
					header: {
						Authorization:token
					},
					data: {
						nick_name: this.detail.nick_name,
						sex: this.list[this.selectedIndex],
						avatar: this.detail.avatar,
						birthday: this.birthdaydate,
						/* qq: this.QQnum, */
						/* email: this.emailSet */
					}
				}).then(res => {
			
					if (res.statusCode == 200) {
						res = res.data;
						if(res.status){
							wx.showToast({
								title:"修改成功",
								duration: 1500,
								success: () => {
									setTimeout(() => {
										wx.switchTab({
											url: '/pages/user/personal/personal'
										});
									}, 1500);
								}
							});
						}
					} else {
						wx.showModal({
							title: "提示",
							content: "修改失败"
						});
					}
				});
			},

			updateBirthday() {
				this.$http.post({
					api: 'api/uto/update/birthday',
					header: {
						Authorization: this.$cookieStorage.get('user_token')
					},
					data: {
						birthday: this.birthdaydate
					}
				}).then(res => {
					console.log(res);
				});
			},

			setData: function(obj) {
				let that = this;
				let keys = [];
				let val, data;
				Object.keys(obj).forEach(function(key) {
					keys = key.split('.');
					val = obj[key];
					data = that.$data;
					keys.forEach(function(key2, index) {
						if (index + 1 == keys.length) {
							that.$set(data, key2, val);
						} else {
							if (!data[key2]) {
								that.$set(data, key2, {});
							}
						}

						data = data[key2];
					});
				});
			}
		}
	};
</script>
<style rel="stylesheet/less" lang="less">
	@import "usersetting";
</style>
