<!--
 * @Author: euzhi
 * @Description: 新增地址
-->
<template>
	<view class="appCotent">
		<div class="addAddress">
			<u-gap bgColor="transparent" height="20"></u-gap>

			<div class="car_info">
				<u--form labelPosition="left" :model="model1" ref="form1" labelWidth="100">
					<u-form-item label="收货人:" prop="addressInfo.userName" borderBottom ref="item1">
						<u--input v-model="model1.addressInfo.userName" placeholder="请填写收货人姓名" border="none"></u--input>
					</u-form-item>
					<u-form-item label="手机号码:" prop="addressInfo.telNumber" borderBottom ref="item1">
						<u--input v-model="model1.addressInfo.telNumber" placeholder="请填写收货人手机号码" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="收货地址:" prop="addressInfo.address" borderBottom ref="item1">
						<u--input v-model="model1.addressInfo.address" placeholder="点击选择收货地址" border="none"></u--input>
						<span @click.stop="getAuthorize">
							<span class="app__gps">
								<image src="@/static/my/gps.png">
							</span>
							<span class="app__right">
								<image src="@/static/my/my6.png">
							</span>
						</span>
					</u-form-item>
					<u-form-item label="楼号门牌:" prop="addressInfo.detailInfo" borderBottom ref="item1">
						<u--input v-model="model1.addressInfo.detailInfo" placeholder="例如  2栋3单元101室" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="设置默认地址:" prop="addressInfo.name" ref="item1">
						<u-switch class="del__address" v-model="model1.value" activeColor="#5ac725"></u-switch>
					</u-form-item>

				</u--form>
			</div>
			<div class="add__tips">为保证您的商品准确送达，请填写正确的地址！</div>
			<div class="love__btn" @click="addAddress">
				<image src="@/static/move-car/love-car5.png">
					保存地址
			</div>
		</div>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				carNumber: "",
				model1: {
					addressInfo: {
						address: ''
					},
					value: false,
				},
				rules: {
					"addressInfo.userName": {
						type: "string",
						required: true,
						message: "收货人不能为空",
						trigger: ["blur", "change"],
					},
					"addressInfo.telNumber": [{
							type: "string",
							required: true,
							message: "手机号不能为空",
							trigger: ["blur", "change"],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机格式错误，请输入11位手机号',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],

					"addressInfo.address": {
						type: "string",
						required: true,
						message: "收货地址不能为空",
						trigger: ["blur", "change"],
					},
					"addressInfo.detailInfo": {
						type: "string",
						required: true,
						message: "门牌号不能为空",
						trigger: ["blur", "change"],
					},
				},
				type: null
			};
		},
		onLoad(e) {
			this.type = e.type
		},
		methods: {
			goBack() {
				if (this.type == "myAddress") {
					let pages = getCurrentPages();
					let prevPage = pages[pages.length - 3]
					prevPage.$vm.addressId = -1;
					uni.navigateBack({
						delta: 2
					})
					return;
				}
				uni.navigateBack({
					delta: 1
				})
			},
			addAddress() {
				this.$refs.form1.validate().then(res => {
					this.model1.addressInfo.defaultFlag = false
					if (this.model1.value) {
						this.model1.addressInfo.defaultFlag = true
					}
					let opts = {
						url: '/app/user/address',
						method: 'post'
					};
					this.http.httpTokenRequest(opts, this.model1.addressInfo).then(res => {
						if (res.data.code == 200) {
							//添加成功
							uni.$u.toast('新增成功')
							this.goBack()
						}
					})
				}).catch(errors => {
					uni.$u.toast('请正确填写信息')
				})
			},
			// 用户授权
			getAuthorize() {
				const _this = this
				uni.authorize({
					scope: 'scope.userLocation', // 获取地理信息必填的参数，其它参数见文档
					success(res) {
						_this.getLocation()
					},
					// 授权失败
					fail(err) {
						uni.showModal({
							title: '温馨提示',
							content: '无法获取当前位置，请手动开启授权',
							success: function(res) {
								if (res.confirm) {
									//console.log('用户点击确定')
									uni.openSetting({
										success(res) {
											if (res.authSetting['scope.userLocation']) {
												//console.log('打开授权设置定位')
												_this.getLocation()
											}
										},
									})
								} else if (res.cancel) {
									//console.log('用户点击取消')
								}
							},
						})
					},
				})
			},
			// 获取用户的地理位置，
			getLocation() {
				const _this = this
				uni.getLocation({
					type: 'wgs84',
					altitude: true,
					success(res) {
						//小程序只能获取到位置经纬度，需要借助高德地图的逆解析地址，显示出中文具体城市名字
						_this.loadCity(res.longitude, res.latitude)
					},
					fail() {
						//console.log('拒绝获取地理位置')
					}
				})
			},
			// 经纬度转具体城市
			// 1）需要用到高德地图的逆地理编码
			// 2）需要当前地理位置的经纬度
			// 3）小程序的key值
			loadCity(longitude, latitude) {
				const that = this
				uni.request({
					header: {
						'Content-Type': 'application/text',
					},
					//注意:这里的key值需要高德地图的 web服务生成的key  只有web服务才有逆地理编码
					url: 'https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=' +
						longitude +
						',' +
						latitude +
						'&key=1bba2ab2de600f8b5fafe167e09cd2af&radius=1000&extensions=all',
					success(res) {
						//console.log(res);
						if (res.statusCode === 200) {
							if (res.data.status === '1') {
								let addressInfo = res.data
								//详细地址
								let detailInfo = addressInfo.regeocode.formatted_address
								that.model1.addressInfo.address = detailInfo
							}
						} else {
							//console.log('获取信息失败，请重试！')
						}
					},
				})
			},
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form1.setRules(this.rules)
		},
	};
</script>

<style lang="scss" scoped>
	.addAddress {
		.app__gps {
			padding-left: 20rpx;

			image {
				width: 34rpx;
				height: 36rpx;
			}
		}

		.app__right {
			padding-left: 20rpx;
			padding-bottom: 10rpx;

			image {
				width: 11rpx;
				height: 18rpx;
			}
		}

		.love__btn {
			height: 76rpx;
			background: url('@/static/move-car/love-car4.png') no-repeat;
			background-size: contain;
			font-size: 32rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
			line-height: 76rpx;
			text-align: center;
			width: 670rpx;
			margin: 0 auto;
			margin-top: 40rpx;

			image {
				width: 30rpx;
				height: 30rpx;
				margin-right: 20rpx;
				position: relative;
				top: 4rpx;
			}
		}

		.add__tips {
			padding-left: 40rpx;
			font-size: 24rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #E1251B;
			line-height: 42px;
		}

		width: 100%;
		height: 100%;

		.car_info {
			padding: 20rpx 40rpx;
			background: #fff;
			background: #FFFFFF;
			box-shadow: 0rpx 0rpx 28rpx 1rpx rgba(232, 232, 232, 0.16);
			border-radius: 20rpx;

			/deep/ .u-form-item__body__right__content__slot {
				justify-content: flex-end;
				flex-direction: row !important;
			}
		}

	}
</style>
