<template>
	<view class="edit">
		<navbar ref="navbar" backColor="#666" :config="config"></navbar>
		<form @submit="formSubmit">
			<view class="middle">
				<view class="item">
					<view class="left">
						头像
					</view>
					<view class="right">
						<image v-if="unserInfo.head_photo" :src="unserInfo.head_photo" @click="uploadImg" mode="aspectFill">
						</image>
						<image v-else :src="imgUrl+'/head-on.png'" mode="aspectFill" @click="uploadImg"></image>
						<text class="iconfont">&#xe6c7;</text>
					</view>
				</view>
				<view class="name-item">
					<view class="name-left">
						姓名
					</view>
					<view class="name-right">
						<input type="text" :value="unserInfo.real_name" maxlength="32" @input="onName"
							class="my-name" />
						<text class="iconfont">&#xe6c7;</text>
					</view>
				</view>
				<view class="item">
					<view class="left">
						手机号
					</view>
					<view class="right">
						<view class="phone">
							{{unserInfo.mobile}}
						</view>
					</view>
				</view>
				<view class="item">
					<view class="left">
						性别
					</view>
					<view class="right" v-if="platform.length>0">
						<picker class="choice" @change="bindPickerChange" :value="unserInfo.gender" :range="platform"
							range-key="name">
							<view class="uni-input">{{platform[index].name}}<text class="iconfont">&#xe6c7;</text>
							</view>
						</picker>
					</view>
				</view>
				<view class="item">
					<view class="left">
						生日
					</view>
					<view class="right" style="flex: 1;">
						<picker style="flex: 1;height: 38rpx;text-align: right;" mode="date" :value="date"
							:start="startDate" :end="endDate" @change="bindDateChange">
							<view class="uni-input">{{date ? date : '未知'}}</view>
						</picker>
						<text class="iconfont">&#xe6c7;</text>
					</view>
				</view>
				<!-- <view class="item">
					<view class="left">
						等级
					</view>
					<view class="right">
						<view class="name">
							{{unserInfo.role_name}}
						</view>
					</view>
				</view> -->

			</view>

			<view class="submit-top">
				<button class="submit" form-type="submit">
					修改资料
				</button>
			</view>
		</form>
	</view>
</template>

<script>
	function getDate(type) {
		const date = new Date();
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();
		if (type === 'start') {
			year = year - 150;
		} else if (type === 'end') {
			year = year + 150;
		}
		month = month > 9 ? month : '0' + month;;
		day = day > 9 ? day : '0' + day;
		return `${year}-${month}-${day}`;
	}
	import {
		appTheeLbs
	} from "@/api/basic.js"
	import {
		myInfo,
		updateInfo
	} from "@/api/login.js"
	export default {
		data() {
			return {
				config: {
					back: true, //false是tolbar页面 是则不写
					title: '修改资料',
					color: '#1A1A1A',
					//背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
					backgroundColor: [1, "#fff"],
					statusBarFontColor: '#1A1A1A',
				},
				platform: [{
						name: '女'
					},
					{
						name: '男'
					},
					{
						name: "保密"
					},
				],
				imgSize: 4,
				index: 0, //性别
				date: getDate({
					format: true
				}),
				// date: '',
				startDate: getDate('start'),
				endDate: getDate('end'),
				time: '12:01',
				newProvinceDataList: [
					[],
					[],
					[]
				],
				unserInfo: {},
				ossData: null,
				imgType: ['jpeg', 'png', 'jpg'],
				imgUrl: this.$mConfig.staticUrl
			}
		},
		//组件


		//获得省市区
		onShow() {
			this.$http.get(appTheeLbs).then(res => {
				let provincesList = res.tree.children
				for (let i = 0; i < provincesList.length; i++) {
					this.newProvinceDataList[0].push(provincesList[i]);

				}
			})
			//取shop的值
			let shop = uni.getStorageSync("shop")

		},
		onLoad() {
			this.getUserInfo();
			// this.formDataGet();
		},
		methods: {

			//上传凭证
			formDataGet() {
				let that = this
				uni.request({
					//url: 'https://pm.lidashine.com/get-oss-sign', //oss获取参数接口地址。
					// url: this.$mConfig.baseUrl + '/fileMgr/v1/oss/getOssSign',
					url: 'http://192.168.0.101:9020/fileMgr/v1/oss/getOssSign',
					complete: (result) => {
						console.log(result, 'result')
						let res = JSON.parse(result.data.data);
						console.log('res===>', res)
						that.ossData = res
					}
				})
			},
			//获取登录的用户信息
			getUserInfo() {
				this.$http.get(myInfo).then(res => {
					this.index = res.data.gender //男女
					this.date = res.data.birthday;
					this.unserInfo = res.data;

				})
			},



			//修改个人信息
			formSubmit(e) {
				let target = e.detail.value
				let mobile = this.unserInfo.mobile
				let gender = this.index.toString()
				let param = {
					real_name: this.unserInfo.real_name,
					head_photo: this.unserInfo.head_photo, //this.unserInfo.head_photo, //图像
					gender: gender, //性别
					birthday: this.date, //生日
				}
				this.$http.put(updateInfo, param)
					.then(res => {

						if (res.code == 200) {
							this.$mUtil.toast("修改成功")
							let aa = uni.getStorageSync("personal", res.data)

						} else {
							this.$mUtil.toast("修改失败")
						}
					})


			},
			//更换图片
			updataImg(filePath, nameStr) {
				console.log(filePath, nameStr)
				let date = new Date();
				let that = this
				let allData = date.getFullYear() + '-' + date.getMonth() + 1 + '-' + date.getDate()
				let shopid = uni.getStorageSync('shop')
				let id = 0
				if (!shopid) {
					id = 0
				} else {
					id = shopid.id
				}
				let key = 'img/' + id + '/' + this.type + '/' + allData + '/' + nameStr
				uni.uploadFile({
					// url:  this.$mConfig.baseUrl+ '/minio/upload',
					url:  this.$mConfig.baseUrl+ '/sys/oss/upload',
					filePath: filePath,
					fileType: 'image',
					name: 'file',
					success: (res) => {
						uni.hideLoading();
						if (res.statusCode != 200) {
							return;
						}
						let resObj = JSON.parse(res.data);
						let imgurl = resObj.data.url;

						uni.showToast({
							title: '上传成功',
							icon: 'success',
							duration: 1000
						})
						that.unserInfo.head_photo = imgurl
						// alert(ossRes.host+"/"+encodeURIComponent(fileName));

					},
					fail: (err) => {
						uni.hideLoading();

						uni.showModal({
							content: err.errMsg,
							showCancel: false
						});
					}
				});
			},

			//更换图片
			uploadImg() {
				let that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						let that = this
						if (res) {
							let filePath = res.tempFilePaths[0]

							let nameStr = that.random_string(8) + '.' + res.tempFilePaths[0].split('.').pop();
							if (res.tempFiles) {
								for (let item of res.tempFiles) {
									if (item.size > (that.imgSize * 1024 * 1024)) {
										uni.showToast({
											title: `图片不能大于${that.imgSize}M`,
											icon: 'none'
										})
										return false;
									}
									if (item.type) {
										let r = that.imgType.some(v => {
											let type = item.type.split('/');
											if (type.length)
												return (v === type[1]);
										});
										if (!r) {
											uni.showToast({
												title: `只允许上传${that.imgType}的类型`,
												icon: 'none'
											})
											return false;
										}
									}
								}
							}


							that.updataImg(filePath, nameStr)
						}

					}
				});
			},
			random_string(len) {
				len = len || 32;
				var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
				var maxPos = chars.length;
				var pwd = '';
				for (let i = 0; i < len; i++) {
					pwd += chars.charAt(Math.floor(Math.random() * maxPos));
				}
				return pwd;
			},

			//修改昵称
			onName(e) {
				this.unserInfo.real_name = e.detail.value
			},
			bindPickerChange: function(e) {

				this.index = e.detail.value
			},
			bindDateChange: function(e) {
				this.date = e.detail.value
			},
		}

	}
</script>

<style scoped lang="scss">
	.name-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1rpx solid #E6E6E6;
		padding: 34rpx 0 30rpx 0;

		.name-right {
			flex: 1;
			padding-left: 30rpx;
			text-align: right;
			display: flex;
			align-items: center;

			.my-name {
				width: 100%;
			}
		}
	}

	.submit-top {
		width: 100%;
		padding: 0 30rpx;
		position: fixed;
		bottom: 60rpx;
	}

	.submit {
		text-align: center;
		border-radius: 43rpx;
		margin-top: 350rpx;
		font-size: 36rpx;
		color: #ffffff;
		font-weight: 400;
		background-color: #3D93FC;
	}

	.distance {
		height: 10rpx;
		background-color: #F5F5F5;
	}

	.middle {
		padding: 0 30rpx;

		.item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-bottom: 1rpx solid #E6E6E6;
			padding: 34rpx 0 30rpx 0;

			.left {
				font-size: 28rpx;
				color: #1A1A1A;
				font-weight: 400;
			}

			.right {

				display: flex;
				align-items: center;

				.my-phone {
					text-align: right;
				}

				.my-name {
					text-align: right;
				}

				.name {
					font-size: 28rpx;
					color: #1A1A1A;
					font-weight: 400;

				}

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

				.iconfont {
					margin-left: 15rpx;
				}
			}
		}
	}
</style>
