<template>
	<view>
		<u-navbar title="提交订单" :border="true" :placeholder="true" :autoBack="true" bgColor="#fff" />
		<view class="settlement">
			<view class="settlement-address">
				<view class="flex settlement-address-top" v-if="info.addr !== null">
					<view class="settlement-address-top__left">配送地址</view>
					<view class="flex settlement-address-top__right" @click="toAddress">
						<view class="">更改地址</view>
						<u-icon name="arrow-right" size="18" color="#237ED4 100%"></u-icon>
					</view>
				</view>
				<view class="flex settlement-address-top" v-else>
					<view class="settlement-address-top__left">配送地址</view>
					<view class="flex settlement-address-top__right" @click="toWeixinAddress">
						<view class="">微信地址</view>
						<u-icon name="arrow-right" size="18" color="#237ED4 100%"></u-icon>
					</view>
				</view>
				<view class="settlement-address-desc" v-if="info.addr !== null">
					<view class="settlement-address-desc__item">
						{{ `${ addr.province || '-' }-${ addr.city || '-' }-${ addr.area || '-' }` }}
						{{ addr.addr || '-' }}
					</view>
					<view class="settlement-address-desc__item">{{ addr.receiver || '-' }} {{ addr.mobile || '-' }}
					</view>
				</view>
				<view class="settlement-address-form" v-else>
					<view class="address-add">
						<u--form labelPosition="left" ref="form" labelWidth="90">
							<u-form-item label="收货人:" borderBottom required>
								<u--input v-model="form.receiver" border="none" placeholder="请输入收货人"></u--input>
							</u-form-item>
							<u-form-item label="手机号码:" borderBottom required>
								<u--input v-model="form.mobile" border="none" placeholder="请输入手机号码"></u--input>
							</u-form-item>
							<u-form-item label="所在地区:" borderBottom required @click="selectArea">
								<u--input v-model="form.cityShow" border="none" disabled disabledColor="#ffffff"
									placeholder="请选择地区">
								</u--input>
								<u-icon slot="right" name="arrow-right"></u-icon>
							</u-form-item>
							<u-form-item label="详细地址:" :borderBottom="false" required>
								<u--textarea v-model="form.addr" placeholder="请输入详细地址"></u--textarea>
							</u-form-item>
						</u--form>
					</view>
					<!-- 操作按钮 -->
					<view class="save-btn">
						<button :loading="loading" type="default" @click="saveAddress">保存并使用</button>
					</view>
				</view>
			</view>
			<view class="settlement-goods">
				<view class="flex settlement-goods__detail" v-for="(item, index) in list" :key="index">
					<view class="settlement-goods__detail__left">
						<view class="img">
							<image class="img" :src="item.picUrl" mode="aspectFill">
							</image>
						</view>
					</view>
					<view class="settlement-goods__detail__right">
						<view class="ells title">{{ item.title }}</view>
						<view class="sku" v-if="item.properties">规格：{{ item.properties }}</view>
						<view class="">数量：{{ item.goodsNum }}</view>
					</view>
				</view>
			</view>

			<view class="flex settlement-freight">
				<text>运费</text>
				<text>￥{{ $numberFormat(info.freightAmt) }}</text>
			</view>
		</view>
		<view class="footer-fixed">
			<view class="flex btn">
				<view class="btn-left">
					<view class="money">
						<text>合计：</text>
						<text class="value">￥{{ $numberFormat(info.payAmt) }}</text>
					</view>
				</view>
				<view class="btn-right">
					<text class="save" @click="save">提交</text>
				</view>
			</view>
		</view>

		<area-picker :area-show="areaShow" @cancel="cancel" @confirmArea="confirmArea" />
	</view>
</template>

<script>
	import env from '../../config/env.js'
	import $http from '@/utils/request.js'
	import AreaPicker from '../../components/area-picker/area-picker.vue'
	export default {
		components: {
			AreaPicker
		},
		data() {
			return {
				ids: [],
				info: {},
				addr: {},
				list: [],
				loading: false,
				addrId: '',
				form: {
					receiver: '',
					mobile: '',
					name: '',
					cityShow: '',
					addr: '',
					provinceId: '', // 省ID/编码
					province: '', // 省
					cityId: '', // 市ID/编码
					city: '', // 市
					areaId: '', // 区ID/编码
					area: '', // 区
				},
				areaShow: false,
				toAddressShow: false,
				
				wxAddress: {}
			}
		},
		onLoad(opthios) {
			if (opthios.ids) {
				this.ids = JSON.parse(opthios.ids)
				this.getDetail()
			}
		},
		onShow() {
			if (this.toAddressShow) {
				this.getDetail()
			}
		},
		methods: {
			save() {
				if (this.info.addr == null) {
					uni.$u.toast('请先保存配送地址');
					return
				}
				let _this = this
				let payIng = false
				if (payIng) return
				uni.showLoading({
					title: '加载中'
				});
				$http.post('/api/v1/mp/user/deliver/order/submit', {}).then(res => {
					payIng = true
					uni.hideLoading();
					if (res.code == 0) {
						if (res.data.needPay == 1) {
							$http.post('/api/v1/mp/user/deliver/order/pay', {
								orderId: res.data.orderId,
								payType: 2
							}).then(ele => {
								if (ele.code == 0) {
									uni.requestPayment({
										timeStamp: ele.data.timeStamp,
										nonceStr: ele.data.nonceStr,
										package: ele.data.package,
										signType: ele.data.signType,
										paySign: ele.data.paySign,
										success() {
											uni.showToast({
												title: '支付成功',
												icon: 'success',
												duration: 2000
											})
											setTimeout(() => {
												uni.redirectTo({
													url: `/pages/order/index`
												})
											}, 500)
										},
										fail() {
											payIng = false
											setTimeout(() => {
												uni.redirectTo({
													url: `/pages/order/index`
												})
											}, 500)
										}
									})
								} else {
									payIng = false
									uni.$u.toast('支付失败!');
								}
							}).catch(() => {
								payIng = false
								uni.$u.toast('支付失败!');
							})
						} else {
							uni.showToast({
								title: '提交成功',
								icon: 'success',
								duration: 2000
							})
							setTimeout(() => {
								uni.redirectTo({
									url: `/pages/order/index`
								})
							}, 500)
						}
					} else {
						payIng = false
						uni.$u.toast('提交失败!');
					}
				}).catch(() => {
					payIng = false
					uni.$u.toast('提交失败!');
					uni.hideLoading();
				})
			},

			getDetail() {
				uni.showLoading({
					title: '加载中'
				});
				$http.post('/api/v1/mp/user/deliver/order/settle', {
					ids: this.ids
				}).then(res => {
					uni.hideLoading();
					if (res.code == 0) {
						this.info = res.data
						this.addr = res.data.addr
						res.data.prizeList.forEach(item => {
							let picUrlArr = item.picUrl.split(',')
							item.picUrl = env.filePublic + picUrlArr[0]
						})
						this.list = res.data.prizeList
					}
				}).catch(() => {
					uni.hideLoading();
				})
			},

			selectArea() {
				this.areaShow = true
			},

			confirmArea(obj) {
				this.form.province = obj.province
				this.form.provinceId = obj.provinceId
				this.form.city = obj.city
				this.form.cityId = obj.cityId
				this.form.area = obj.area
				this.form.areaId = obj.areaId
				this.form.cityShow = obj.cityShow
				this.areaShow = false
			},

			cancel() {
				this.areaShow = false
			},

			toAddress() {
				this.toAddressShow = true
				uni.navigateTo({
					url: "/pages/address/index"
				})
			},

			toWeixinAddress() {
				let _this = this
				uni.chooseAddress({
					success(res) {
						console.log(res);
						_this.wxAddress = res
						_this.getArea()
					}
				})
			},
			
			// 回显微信地址
			async getArea() {
				// 获取省
				let provinceRes = await $http.post('/api/v1/mp/area/listByPid', {
					pid: 0
				})
				let provinceItem = provinceRes && provinceRes.data.find((item=> item.areaName == this.wxAddress.provinceName))
				// 获取市
				let cityRes = await $http.post('/api/v1/mp/area/listByPid', {
					pid: provinceItem && provinceItem.areaId
				})
				let cityItem = cityRes && cityRes.data.find((item=> item.areaName == this.wxAddress.cityName))
				// 获取区
				let areaRes = await $http.post('/api/v1/mp/area/listByPid', {
					pid: cityItem && cityItem.areaId
				})
				let areaItem = areaRes && areaRes.data.find((item=> item.areaName == this.wxAddress.countyName))
				// 赋值
				this.form.province = provinceItem.areaName
				this.form.provinceId = provinceItem.areaId
				this.form.city = cityItem.areaName
				this.form.cityId = cityItem.areaId
				this.form.area = areaItem.areaName
				this.form.areaId = areaItem.areaId
				this.form.cityShow = `${ provinceItem.areaName }-${ cityItem.areaName }-${ areaItem.areaName }`
				this.form.addr = this.wxAddress.detailInfo
				this.form.receiver = this.wxAddress.userName
				this.form.mobile = this.wxAddress.telNumber
			},

			saveAddress() {
				let _this = this
				if (!_this.form.receiver) {
					uni.$u.toast('请输入收货人');
					return
				}
				if (!_this.form.mobile) {
					uni.$u.toast('请输入手机号码');
					return
				}
				const rule = /^[1][0-9][0-9]{9}$/
				if (!rule.test(_this.form.mobile)) {
					uni.$u.toast('请输入正确的手机号');
					return
				}
				if (!_this.form.cityShow) {
					uni.$u.toast('请选择所在地区');
					return
				}
				if (!_this.form.addr) {
					uni.$u.toast('请输入详细地址');
					return
				}
				let url = '/api/v1/mp/user/addr/create'
				$http.post(url, this.form).then(res => {
					if (res.code == 0) {
						uni.$u.toast('保存成功');
						this.getDetail()
					}
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	.settlement {
		margin: 10rpx;
		padding-bottom: 100rpx;

		&-address {
			background-color: #fff;
			padding: 0 16rpx 24rpx;
			margin-bottom: 20rpx;

			&-top {
				justify-content: space-between;
				padding: 24rpx 0;
				border-bottom: 1px solid rgba(236, 236, 236, 100);

				&__left {
					line-height: 40rpx;
				}

				&__right {
					line-height: 40rpx;
					color: rgba(35, 126, 212, 100);
				}
			}

			&-desc {
				&__item {
					line-height: 40rpx;
					margin-top: 16rpx;
				}
			}

			&-form {
				.save-btn {
					padding: 10rpx 20rpx;

					/deep/ button {
						line-height: 76rpx;
						font-size: 28rpx;
						height: 76rpx;
						color: #fff;
						background-color: $uni-bg-color;
						border: none;
						border-radius: 100rpx;
					}
				}
			}
		}

		&-goods {
			background-color: #fff;
			padding: 0 40rpx;
			margin-bottom: 20rpx;

			&__detail {
				padding: 20rpx 0;
				justify-content: space-between;
				border-bottom: 1px solid rgba(236, 236, 236, 100);

				&__left {
					display: flex;
					height: 170rpx;

					.img {

						image {
							width: 170rpx;
							height: 170rpx;
							margin-right: 20rpx;
						}
					}
				}

				&__right {
					flex: 1;
					display: flex;
					height: 170rpx;
					flex-direction: column;
					justify-content: space-between;
					align-items: flex-start;
					font-size: 30rpx;

					.title {
						font-weight: bold;
					}

					.sku {
						color: #848484;
					}
				}

			}

			&__detail:last-child {
				border: none;
			}
		}

		&-freight {
			background-color: #fff;
			justify-content: space-between;
			padding: 20rpx 16rpx;
		}
	}

	.footer-fixed {
		position: fixed;
		bottom: var(--window-bottom);
		left: 0;
		right: 0;
		// min-height: 120rpx;
		z-index: 11;
		box-shadow: 0 -4rpx 40rpx 0 rgba(151, 151, 151, 0.24);
		background: #fff;
		// margin-bottom: 40rpx;

		// 设置ios刘海屏底部横线安全区域
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		.btn {
			justify-content: space-between;
			padding: 20rpx 40rpx;

			&-left {
				.value {
					color: $uni-text-color;
				}
			}

			&-right {
				display: flex;
				align-items: center;
				justify-content: flex-end;

				.save {
					width: 190rpx;
					height: 60rpx;
					line-height: 60rpx;
					border-radius: 8rpx;
					text-align: center;
					margin-left: 40rpx;
					background-color: rgba(236, 112, 9, 100);
					color: rgba(255, 255, 255, 100);
				}
			}
		}
	}
</style>
