<template>
	<view class="uni-container">
		<u-navbar :autoBack="true" :placeholder="true" :bgColor="bgColor">
			<view slot='center' style="font-size: 36rpx; font-weight: bold;">
				我的资料
			</view>
		</u-navbar>
		<view class="form-box">
			<button class="img-box" style="borderColor: rgba(0,0,0,0)"  open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
				<image class="userImg" :src="headImg" mode=""></image>
			</button>
			<view class="form-item">
				<view class="label">昵称</view>
				<view class="line"></view>
				<input type="nickname" v-model="detData.nickname" class="weui-input" placeholder-class="input-placeholder" @change="getNickname" placeholder="请输入昵称" />
			</view>
			<view class="form-item">
				<view class="label">性别</view>
				<view class="line"></view>
				<view class="code-box">
					<view class="uni-list-cell-db">
						<picker class="picker" @change="bindPickerChange" :value="sexIndex" :range="sexList">
							<view class="uni-input" v-if="detData.sex">{{detData.sex}}</view>
							<view class="input-placeholder" v-if="!detData.sex">请选择您的性别</view>
							<uni-icons class="icon" type="right"></uni-icons>
						</picker>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="label">手机号</view>
				<view class="line"></view>
				<view class="code-box">
					<input type="number" v-model="detData.mobile" class="weui-input" placeholder-class="input-placeholder" placeholder="请输入手机号" />
					<button class="gain" plain="true" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">一键获取</button>
				</view>
			</view>
			<view class="form-item">
				<view class="label">身份证号</view>
				<view class="line"></view>
				<input type="idcard" v-model="detData.idCard" class="weui-input" placeholder-class="input-placeholder" placeholder="请输入身份证号" />
			</view>
			<view class="form-item">
				<view class="label">真实姓名</view>
				<view class="line"></view>
				<input type="text" v-model="detData.name" class="weui-input" placeholder-class="input-placeholder" placeholder="请输入真实姓名" />
			</view>
			<view class="form-item">
				<view class="label">出生日期</view>
				<view class="line"></view>
				<view class="code-box">
					<view class="uni-list-cell-db">
						<picker mode="date" class="picker" :value="detData.birthday" :start="startDate" :end="endDate" @change="bindDateChange">
							<view class="uni-input" v-if="detData.birthday">{{detData.birthday}}</view>
							<view class="input-placeholder" v-if="!detData.birthday">请选择您的出生日期</view>
							<uni-icons class="icon" type="right"></uni-icons>
						</picker>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="label">所在地区</view>
				<view class="line"></view>
				<view class="code-box">
					<view class="uni-list-cell-db">
						<picker class="picker" mode="multiSelector" @change="bindMultiPickerChange" @columnchange="bindMultiPickerColumnChange"
							:value="multiIndex" :range="communityListArray" range-key="name">
							<text class="uni-input" v-if="addressByPcrs">{{addressByPcrs}}</text>
							<text class="input-placeholder" v-if="!addressByPcrs">请选择所在地区</text>
							<uni-icons class="icon" type="right"></uni-icons>
						</picker>
					</view>
				</view>
			</view>
		</view>
		<view class="btn" @click="save">保存</view>
	</view>
</template>
<script>
	import _config from '../../common/http/config.js'
	export default {
		data() {
			return {
				bgColor: '#F6F9FF',
				headImg: '',
				sexList: ['男','女'],
				sexIndex: 0,
				detData: {
					avatar: '',
					nickname: '',
					sex: '',
					mobile: '',
					idCard: '',
					name: '',
					birthday: '',
					province: '',
					city: '',
					area: '',
				},
				siteData: {
					provinceName: '',
					cityName: '',
					areaName: '',
					provinceId: '',
					cityId: '',
					areaId: ''
				},
				addressByPcrs:"",
				communityListArray : [],
				multiIndex : [0, 0, 0],
				communityListData: []
			};
		},
		onLoad(options) {
			this.detData.avatar = uni.getStorageSync('user_avatar')
			this.headImg = this.detData.avatar ? (_config.url + this.detData.avatar) : require('../../static/image/common/user.png')
		},
		onReady() {},
		onShow() {
			this.getUserInfo()
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		methods: {
			async getUserInfo() {
				let info = await this.$http.getUserInfo()
				if (info.code === 200) {
					this.detData = info.data
					this.sexIndex = this.detData.sex ? this.sexList.indexOf(this.detData.sex) : 0
					if (this.detData.province && this.detData.city && this.detData.area) {
						this.siteData.provinceId = this.detData.province
						this.siteData.cityId = this.detData.city
						this.siteData.areaId = this.detData.area
						let arr1 = [0, this.siteData.provinceId, this.siteData.cityId]
						let arr2 = [this.siteData.provinceId, this.siteData.cityId, this.siteData.areaId]
						this.editData(arr1, arr2)
					} else {
						this.getCodeAll(0, 0)
					}
				} else {
					uni.$u.toast(info.msg);
				}
			},
			onChooseAvatar(e) {
				const { avatarUrl } = e.detail
				
				uni.uploadFile({
					url: _config.url + '/app/common/upload',
					filePath: avatarUrl,
                    header: { "token": uni.getStorageSync("ztc_token") },
					name: 'file',
					success: (res) => {
						var data = JSON.parse(res.data);
						console.log('data', data.fileName)
						this.detData.avatar = data.fileName
						this.headImg = _config.url + this.detData.avatar
						wx.showToast({
							title: '上传成功',
							icon: 'success',
							duration: 2000 //持续的时间
						})
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			getNickname(e) {
				console.log("getNickname", e.detail.value)
				this.detData.nickname = e.detail.value
			},
			async getPhoneNumber (e) {
				const params = {
					code: e.detail.code
				}
				let info = await this.$http.getPhoneNumber(params)
				if (info.code === 200) {
					this.detData.mobile = info.data
				} else {
					uni.$u.toast(info.msg);
				}
			},
			bindPickerChange(e) {
				this.sexIndex = e.detail.value
				this.detData.sex = this.sexList[this.sexIndex]
			},
			bindDateChange(e) {
				this.detData.birthday = e.detail.value
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
	
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			async save() {
				this.detData.province = this.siteData.provinceId
				this.detData.city = this.siteData.cityId
				this.detData.area = this.siteData.areaId
				const params = this.detData
                if (!params.nickname) {
                    uni.showToast({ mask: true, title: '请输入昵称', icon: 'none' })
                    return false;
                }
                if (!this.$utils.checkStr(params.mobile, 'mobile')) {
                    uni.showToast({ mask: true, title: '请输入正确的手机号', icon: 'none' })
                    return false;
                }
                if (!this.$utils.checkStr(params.idCard, 'card')) {
                    uni.showToast({ mask: true, title: '请输入正确的证件号', icon: 'none' })
                    return false;
                }
                if (!params.name) {
                    uni.showToast({ mask: true, title: '请输入姓名', icon: 'none' })
                    return false;
                }
				let info = await this.$http.updateUser(params)
				if (info.code === 200) {
					uni.setStorageSync('user_avatar', this.detData.avatar)
					uni.setStorageSync('user_nickname', this.detData.nickname)
					uni.showToast({
						title: '保存成功',
						mask: true
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 500)
				} else {
					uni.$u.toast(info.msg);
				}
			},
			async getCodeAll(params, index) {
				let info = await this.$http.listAll(params)
				this.communityListData = info.data;
				if (index === 0) {
					this.communityListArray[0] = info.data
					this.getCodeAll(this.communityListData[0].areaCode, 1)
				} else if (index === 1) {
					this.communityListArray[1] = info.data
					this.getCodeAll(this.communityListData[0].areaCode, 2)
				} else {
					this.communityListArray[2] = info.data
				}
			},
			// value 改变时触发 change 事件
			bindMultiPickerChange(e) {
				this.multiIndex = e.detail.value
				this.addressByPcrs = ''
				this.multiIndex.forEach((m, i) => {
					this.addressByPcrs += this.communityListArray[i][m].name
					if (i == 0) {
						this.siteData.provinceName = this.communityListArray[i][m].name
						this.siteData.provinceId = this.communityListArray[i][m].areaCode
					} else if (i == 1) {
						this.siteData.cityName = this.communityListArray[i][m].name
						this.siteData.cityId = this.communityListArray[i][m].areaCode
					} else {
						this.siteData.areaName = this.communityListArray[i][m].name
						this.siteData.areaId = this.communityListArray[i][m].areaCode
					}
				})
			},
			// 某一列的值改变时触发 columnchange 事件
			async bindMultiPickerColumnChange(e) {
				if(!this.multiIndex || !this.multiIndex.length){
					this.multiIndex = [0,0,0]
				}
				// 第几列
				let column = e.detail.column;
				// 索引
				let value = e.detail.value;
				let multiIndex = this.multiIndex;
				multiIndex[column] = value;
				if(column == 0){
					multiIndex[1] = 0;
					multiIndex[2] = 0;
				}
				if(column == 1){
					multiIndex[2] = 0;
				}
				this.multiIndex = multiIndex;
				let communityListArray = [];
				let info;
				if (column === 0) {
					communityListArray[0] = this.communityListArray[0]
					info = await this.$http.listAll(communityListArray[0][multiIndex[0]].areaCode)
					communityListArray[1] = info.data
					info = await this.$http.listAll(communityListArray[1][multiIndex[1]].areaCode)
					communityListArray[2] = info.data
					this.communityListArray = communityListArray;
				} else if (column === 1) {
					communityListArray[0] = this.communityListArray[0]
					communityListArray[1] = this.communityListArray[1]
					info = await this.$http.listAll(communityListArray[1][multiIndex[1]].areaCode)
					communityListArray[2] = info.data
					this.communityListArray = communityListArray;
				}
			},
			async editData(arr1, arr2) {
				var communityListArray = []
				var multiIndex = []
				this.addressByPcrs = ''
				for (var i = 0; i < arr1.length; i ++) {
					let info = await this.$http.listAll(arr1[i])
					communityListArray[i] = info.data
					info.data.map((m, n) => {
						if (m.areaCode == arr2[i]) {
							multiIndex[i] = n
							this.addressByPcrs += communityListArray[i][n].name
						}
					})
				}
				this.communityListArray = communityListArray
				this.multiIndex = multiIndex
			},
		}
	}
</script>

<style lang="scss" scoped>
	.uni-container {
		width: 100%;
        padding-bottom: 48rpx;
		min-height: 100vh;
		box-sizing: border-box;
		background: #F6F9FF;
		.form-box {
			background: #FFFFFF;
			border-radius: 10rpx;
			padding: 64rpx 32rpx 0;
			margin: 0 32rpx;
			.img-box {
				width: 148rpx;
				height: 148rpx;
				border-radius: 50%;
				overflow: hidden;
				margin: 0 auto 16rpx;
				position: relative;
				padding: 0;
				background-color: #fff;
				.userImg {
					width: 148rpx;
					height: 148rpx;
					filter: grayscale(60%);
				}
                &::after{ border: none; }
			}
			.form-item {
				display: flex;
				align-items: center;
				flex-direction: row;
				height: 109rpx;
				border-bottom: 1rpx solid #E8E8E8;
				&:last-child {
					border: none;
				}
				.label {
					width: 152rpx;
					font-weight: bold;
					font-size: 28rpx;
					color: #333333;
				}
				.line {
					width: 1rpx;
					height: 26rpx;
					background-color: #E8E8E8;
					margin-right: 20rpx;
				}
				.code-box {
					flex: 1;
					display: flex;
					align-items: center;
					flex-direction: row;
					justify-content: space-between;
					.uni-list-cell-db {
						width: 100%;
						.picker {
							width: 100%;
							position: relative;
							.uni-input {
								flex: 1;
								display: inline-block;
							}
							.input-placeholder {
								flex: 1;
								display: inline-block;
							}
							.icon {
								position: absolute;
								right: 0;
								top: 50%;
								transform: translateY(-50%);
								/deep/.uniui-right {
									font-size: 34rpx !important;
									color: #999999 !important;
								}
							}
						}
					}
					.gain {
						font-size: 28rpx;
						color: #03AE80;
						padding: 0;
						margin: 0;
						border: none;
						width: 120rpx;
						text-align: right;
					}
				}
				/deep/.input-placeholder {
					font-weight: 400;
					font-size: 28rpx;
					color: #999999!important;
				}
				/deep/.weui-input {
					font-weight: 500;
					font-size: 28rpx;
					color: #333333;
				}
				.uni-input {
					font-weight: 500;
					font-size: 28rpx;
					color: #333333;
				}
			}
		}
		.btn {
			margin: 71rpx auto 0;
			width: 630rpx;
			height: 90rpx;
			background: #03AE80;
			border-radius: 61rpx;
			line-height: 90rpx;
			text-align: center;
			font-weight: 800;
			font-size: 32rpx;
			color: #FFFFFF;
		}
	}
</style>