<template>
	<view class="app-page">
		<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"
			style="border: none;background: transparent;margin: 0;padding: 72rpx 0;">
				<view class="h-view">
					<u--image v-if="form.headimg" width='144rpx' height='144rpx' radius="100%" shape='circle'
						customStyle="margin: 0" :src="form.headimg" :fade="true" duration="450" mode='heightFix'>
					</u--image>
					<view class="v1" v-else>
						<u--image width='144rpx' height='144rpx' radius="100%" shape='circle'
							:src="`${$getImgBaseUrl()}nologin.png`" :fade="true" duration="450" mode='heightFix'>
						</u--image>
					</view>
			</view>
		</button>
    <view class="card-box">
      <view class="display-flex-between" >
        <text class="left-title">昵称</text>
        <view class="h-view">
          <u-input v-model="form.nickname" placeholder="请输入" type="nickname" border="none" :auto-height="true"
                   clearable inputAlign="right"  />
        </view>
      </view>
      <u-divider  ></u-divider>
      <view class="display-flex-between" >
        <text class="left-title">姓名</text>
        <view class="h-view">
          <u-input v-model="form.realname" placeholder="请输入" border="none" :auto-height="true" clearable
                   inputAlign="right"  />
        </view>
      </view>
      <u-divider  ></u-divider>
      <view class="display-flex-between"  @click="show2 = true">
        <text class="left-title">性别</text>
        <view class="h-view" >
              {{form.base_sex}}  <view class="ml8"><u-icon name="arrow-right" bold color="#333333" size="14"></u-icon></view>
        </view>
      </view>
      <u-divider  ></u-divider>
      <view class="display-flex-between" >
        <text class="left-title">所在地区</text>
        <view class="h-view">
          <picker mode="region" :value="form.region_area" @change="bindAreaChange">
            <view v-if="!form.region_province" class="color-9 display-flex-content-center">省市区县、乡镇等  <view class="ml8"><u-icon name="arrow-right" bold color="#333333" size="14"></u-icon></view></view>
            <view v-else class="color-23 display-flex-content-center">{{areaDisplay}}  <view class="ml8"><u-icon name="arrow-right" bold color="#333333" size="14"></u-icon></view></view>
          </picker>
        </view>
      </view>
      <u-divider  ></u-divider>
      <view class="display-flex-between" >
        <text class="left-title">手机号</text>
        <view class="h-view">
          <u-input v-model="form.phone" placeholder="请输入" type="number" border="none" :auto-height="true"
                   clearable :maxlength="11" customStyle="margin:0 20rpx;text-align: right;" />
          <button class="btn-c" open-type="getRealtimePhoneNumber"
                  @getrealtimephonenumber="getrealtimephonenumber" size="mini">获取手机号</button>
        </view>
      </view>
    </view>

		<view class="bottom-menu-box">
      <view class="agree-box">
        <view class="unchecked-tips" v-show="showUnchecked">请先阅读并同意协议</view>
        <u-checkbox-group @change="termsChange" v-model="termsChecked" style="margin-left: 30rpx;">
          <u-checkbox activeColor="#C29556" name="term" shape="circle" size="40rpx"></u-checkbox>
        </u-checkbox-group>
        <text class="item-text">
          已阅读并同意
          <text class="text-primary fs14 fw600" @click="checkPrimary('2')">《隐私保护协议》</text>
          与
          <text class="text-primary fs14 fw600" @click="checkPrimary('1')">《用户协议》</text>
        </text>
      </view>
			<view class="common-btn" @click="commit">提交</view>
		</view>
		<u-picker :show="show" keyName="label" confirmColor="#815BFF" :columns="[list]" @confirm="confirm"
			@cancel="show = false"></u-picker>
    <u-picker  :show="show2"  :columns="columns"  ref="uPicker" @confirm="sexConfirm" @cancel="sexCancel" ></u-picker>
	</view>
</template>

<script>
	import {
		uploadBase64File,
	} from "@/common/api/common.js";

	import {
		updateUserInfo,
		userRegister,
		getUserInfo
	} from "@/common/api/user.js";

	import {
		getUserPhone
	} from "@/common/api/common.js";
	export default {
		data() {
			return {
				form: {
					region_province: '',
					region_city: '',
					region_area: '',
					nickname: undefined,
					realname: undefined,
					headimg: undefined,
					avatarUrl: undefined,
					phone: undefined,
					base_sex: undefined,
				},
        columns: [
          ['男', '女']
        ],
				showUnchecked: false,
				termsChecked: false,
				show: false,
        show2: false,
				isNeedUpLoad: false,
				userInfo: {},
				selectItem: {},
			}
		},
		computed: {
			areaDisplay() {
				const {
					region_province = '', region_city = '', region_area = ''
				} = this.form
				return region_province +' '+ region_city +' ' + region_area
			},
		},
		onLoad(options) {},

		onShow() {
			this.reUserInfo();
			this.getUserInfo();
		},
		methods: {
			getrealtimephonenumber(e) {
				console.log("getrealtimephonenumber=>", e)
				if (e.detail?.code) {
					this.getUserPhone(e.detail?.code)
				}
			},
			async getUserPhone(code) {
				const data = {
					code: code
				}
				await getUserPhone(data)
					.then(res => {
						if (res.data) {
							this.form.phone = res.data.purePhoneNumber
						}
					})
					.catch(() => {
						uni.hideLoading();
					});
			},
			bindAreaChange(data) {
				const {
					code,
					value
				} = data.detail
				this.form.region_province = value[0]
				this.form.region_city = value[1]
				this.form.region_area = value[2]
				// this.areaDisplay = value.join('.')
				console.log(8999, data, this.form)
			},

      // 回调参数为包含columnIndex、value、values
      sexConfirm(e) {

        const {
          value,
        } = e

        console.log(e)
        this.form.base_sex = value[0]
        this.show2 = false
      },
      sexCancel(e) {
        this.show2 = false
      },


			checkPrimary(name) {
				uni.navigateTo({
					url: '/pages/singlePage/index?name=' + name
				});
			},
			termsChange(value) {
				if (value.length) {
					this.showUnchecked = false;
				} else {
					this.showUnchecked = true;
				}
			},
			toAuthenticationList() {
				uni.navigateTo({
					url: '/subPages/authenticationList/index'
				})
			},
			commit() {
				if (this.isNeedUpLoad) {
					this.getImageInfo()
					return
				}
				if (!this.termsChecked.length) {
					this.showUnchecked = true;
					return;
				}
				if (!this.form.region_province) {
					uni.$u.toast('请选择所在地区')
					return
				}
				if (!this.form.phone) {
					uni.$u.toast('请输入手机号')
					return
				}
        if (this.form.phone.length!==11) {
          uni.$u.toast('请输入11位手机号')
          return
        }

				this.userRegister();
			},
			reUserInfo() {
				const userInfo = uni.getStorageSync('userInfo');
				if (userInfo && JSON.parse(userInfo).nickname != '' && JSON.parse(userInfo).headimg != '') {
					this.userInfo = JSON.parse(userInfo);
					const {
						headimg,
						nickname,
						base_sex,
						realname,
						region_area,
						region_city,
						region_province,
						phone
					} =
					this.userInfo
					this.avatarUrl = headimg
					this.form = Object.assign({}, this.form, {
						headimg,
						nickname,
						base_sex,
						realname,
						region_area,
						region_city,
						region_province,
						phone
					})
				}
				console.log("reUserInfo==>", this.form);
			},
			async getUserInfo() {
				const data = {}
				await getUserInfo(data)
					.then(res => {
						if (res.data) {
							uni.setStorageSync('token', res.data.token.token)
							uni.setStorageSync('userInfo', JSON.stringify(res.data))
							this.userInfo = res.data;
							console.log("getUserInfo==>", this.userInfo)
						}
					})
					.catch(() => {
						uni.hideLoading();
					});
				await this.reUserInfo();
			},
			onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail
				console.log('成功授权', avatarUrl)
				this.form.headimg = avatarUrl
				this.isNeedUpLoad = true;
			},
			getImageInfo() {
				// 获取当前图片信息
				uni.getImageInfo({
					src: this.form.headimg,
					success: (image) => {
						// 做png/jpeg的类型判断————对不同类型的图像添加不同的转换头信息
						if (image.type == 'png' || image.type == 'jpeg') {
							// 对符合类型的图片转换为base64类型
							uni.getFileSystemManager().readFile({ // 【重点来啦】人家自提供的转码API
								filePath: image.path, // 所需转码图像路径
								encoding: "base64", // 转码类型
								success: (res) => {
									// 生成base64
									let imageBase64 = 'data:image/' + image.type + ';base64,' + res
										.data;
									console.log('转base64后：', imageBase64);
									this.uploadBase64File(imageBase64)
								}
							})
						} else { // 友好一点，不是以上类型做出提醒
							uni.showToast({
								title: '当前只支持png/jpeg格式',
								duration: 2500,
								icon: 'none'
							})
						}
					}
				});
			},
			uploadBase64File(imageBase64) {
				uploadBase64File({
						base64: imageBase64
					}, {
						'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
					})
					.then((res) => {
						console.log("uploadFile==>", res.data.url)
						this.avatarUrl = res.data.url
						this.form.headimg = res.data.url
						this.userRegister();
					})
					.catch(() => {
						uni.hideLoading();
					});
			},
			confirm(e) {
				this.selectItem = e.value[0];
				console.log(e.value[0].label);
				this.show = false;
			},
			userRegister() {
				this.isNeedUpLoad = false;
				const data = this.form;
				updateUserInfo(data)
					.then((res) => {
						console.log("updateUserInfo==>", res.data)
						if (res.data) {
							if (res.data.token) {
								uni.setStorageSync('token', res.data.token.token)
							}
							uni.setStorageSync('userInfo', JSON.stringify(res.data))
							uni.$u.toast('更新成功')
							setTimeout(() => {
								uni.navigateBack()
							}, 800);
						}
					});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.app-page {
		width: 100%;
		display: flex;
		align-items: center;
		flex-direction: column;
	}

	.card-box {
		width: 650rpx;
		background: #FFFFFF;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
		margin: 0 auto 20rpx auto;
		padding: 30rpx;
	}

	.h-view {
		flex: 1;
		display: flex;
		flex-direction: row;
		justify-content: flex-end;
		align-items: center;
	}

	.left-title {
		font-size: 28rpx;
	}


	button::after {
		border: none;
	}

	.avatar-wrapper button::before {
		padding: 0;
		margin: 0;
		border-radius: 20rpx;
		background: transparent;
		border: none;
		line-height: 1;
	}

	.avatar-wrapper button::after {
		padding: 0;
		margin: 0;
		border-radius: 20rpx;
		background: transparent;
		border: none;
		line-height: 1;
	}

	.agree-box {
		display: flex;
		color: $gray-1;
		position: relative;
		align-items: center;
		margin: 0 auto;

		.unchecked-tips {
			position: absolute;
			height: 50rpx;
			color: #fff;
			background-color: rgba($color: #27282a, $alpha: 1);
			top: -60rpx;
			left: 0;
			border-radius: 8rpx;
			line-height: 50rpx;
			font-size: 24rpx;
			padding: 0 16rpx;

			&::after {
				display: "block";
				content: "";
				position: absolute;
				width: 20rpx;
				height: 20rpx;
				// background: rgba($color: #27282a, $alpha: 1);
				bottom: -6rpx;
				left: 10rpx;
				transform: rotate(45deg);
				border-radius: 4rpx;
			}
		}

		.u-checkbox {
			flex-shrink: 0;
			align-items: flex-start;
			margin-top: 6rpx;
		}

		.item-text {
			font-size: 24rpx;
		}
	}

	.bottom-view {
		margin-bottom: var(--window-bottom);
		padding-bottom: calc(260rpx);
	}

	.bottom-menu-box {
		height: calc(260rpx);
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: flex-start;
		position: fixed;
		z-index: 9;
		background: white;
		bottom: var(--window-bottom);
		left: 0;
		right: 0;
		width: 100vw;

		.primary-btn {
			width: 713rpx;
			margin-top: 50rpx;
			height: 78rpx;
			line-height: 78rpx;
			background: #815BFF;
			border-radius: 40rpx;
			font-size: 32rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
		}

		.common-btn {
			// width: 713rpx;
			width: calc(100% - 80rpx);
			box-sizing: border-box;
      margin: 0 auto;
      margin-top: 50rpx;
      background: linear-gradient( 315deg, #CA9359 0%, #E2B98E 100%);
      border-radius: 292rpx 292rpx 292rpx 292rpx;
      border:0;
		}

		button::after {
			height: 78rpx;
			line-height: 78rpx;
		}

		.primary-btn:active {
			opacity: 0.7;
		}
	}
  .btn-c{
    width: 180rpx;
    height: 56rpx;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    border: 2rpx solid #C29556;
    padding: 0 10px;
  }

</style>