<template>
	<view>
		<u-navbar title="结算" :border="true" :placeholder="true" :autoBack="true" leftIconColor="#fff"
			bgColor="#E96737" />
		<view class="settlement">
			<view class="settlement-address">
				<view class="flex settlement-address-top">
					<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="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 class="info">
							<text>{{ item.title }}</text>
							<text>面值：{{ $numberFormat(item.facePrice) }}元</text>
							<text>规格：{{ item.pkgUnit }}张/包 </text>
						</view>
					</view>
					<view class="settlement-goods__detail__right">
						<text>￥{{ $numberFormat(item.pkgSalePrice) }}</text>
						<text>x {{ item.orderNum }}</text>
					</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">共计 {{ info.pkgNum }} 包</view>
				<view class="btn-right">
					<view class="money">
						<text>共计：</text>
						<text>￥{{ $numberFormat(info.payAmt) }}</text>
					</view>
					<text class="save" @click="save">提交</text>
				</view>
			</view>
		</view>

		<u-picker ref="uPicker" :show="show" :columns="columns" @change="changeHandler" @confirm="confirm"
			@cancel="cancel" keyName="areaName"></u-picker>
	</view>
</template>

<script>
	import env from '../../config/env.js'
	import $http from '@/utils/request.js'
	export default {
		data() {
			return {
				ids: [],
				info: {},
				addr: {},
				list: [],
				loading: false,
				addrId: '',
				form: {
					receiver: '',
					mobile: '',
					name: '',
					cityShow: '',
					addr: '',
					provinceId: '', // 省ID/编码
					province: '', // 省
					cityId: '', // 市ID/编码
					city: '', // 市
					areaId: '', // 区ID/编码
					area: '', // 区
				},
				show: false,
				columns: [
					[],
					[],
					[]
				],
				toAddressShow: false,
			}
		},
		onLoad(opthios) {
			if (opthios.ids) {
				this.ids = JSON.parse(opthios.ids)
				this.getDetail()
			}
			if(opthios.boxId) {
				this.boxId = opthios.boxId
				this.getDetail()
			}
		},
		onShow() {
			if (this.toAddressShow) {
				this.getDetail()
			}
		},
		methods: {
			save() {
				$http.post('/api/v1/mp/channel/mall/order/submit', {
					memo: ""
				}).then(res => {
					console.log(res);
					if (res.code == 0) {
						uni.navigateTo({
							url:`/pages/order/index?back=1`
						})
						// $http.post('/api/v1/mp/channel/mall/order/pay', {
						// 	orderId: res.msg,
						// 	payType: 2
						// }).then(res => {
						// 	console.log(res);
						// }).catch(err => {
						// 	console.log(err);
						// })
					}
					if (res.code == 1016) {
						uni.showModal({
							title: '提示',
							content: '您还未通过经销商认证，请先提交认证。',
							success(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: "/pages/attestation/index"
									})
								}
							}
						})
					}
				})
			},

			getDetail() {
				let data = this.ids.length ? {
					cartIds: this.ids
				} : {
					boxId: this.boxId,
					orderNum: 1
				}
				
				$http.post('/api/v1/mp/channel/mall/order/settle', data).then(res => {
					console.log(res);
					if (res.code == 0) {
						this.info = res.data
						this.addr = res.data.addr
						res.data.items.forEach(item => {
							let picUrlArr = item.picUrl.split(',')
							item.picUrl = env.filePublic + picUrlArr[0]
						})
						this.list = res.data.items
					}
					console.log(this.info);
				})
			},

			getAddrDetail() {
				$http.post('/api/v1/mp/channel/mall/addr/query', {
					addrId: this.addrId
				}).then(res => {
					console.log(res);
					if (res.code == 0) {
						let item = res.data
						this.form = {
							...item,
							cityShow: `${ item.province }-${ item.city }-${ item.area }`
						}
					}
				})
			},

			async getArea() {
				const picker = this.$refs.uPicker

				let provinceRes = await $http.post('/api/v1/mp/area/listByPid', {
					pid: 0
				})
				console.log(`省`, provinceRes);

				let cityRes = await $http.post('/api/v1/mp/area/listByPid', {
					pid: provinceRes && provinceRes.data && provinceRes.data[0].areaId
				})
				console.log(`市`, cityRes);
				let areaRes = await $http.post('/api/v1/mp/area/listByPid', {
					pid: cityRes && cityRes.data && cityRes.data[0].areaId
				})
				console.log(`区`, areaRes);
				picker.setColumnValues(0, provinceRes.data)
				picker.setColumnValues(1, cityRes.data)
				picker.setColumnValues(2, areaRes.data)

			},
			selectArea() {
				console.log(this.$refs.uPicker);
				this.getArea()
				this.show = true
			},

			async changeHandler(e) {
				const {
					columnIndex,
					index,
					value,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				console.log(columnIndex, value);
				if (columnIndex === 0) {
					let cityRes = await $http.post('/api/v1/mp/area/listByPid', {
						pid: value && value[0].areaId
					})
					console.log(`市`, cityRes);
					let areaRes = await $http.post('/api/v1/mp/area/listByPid', {
						pid: cityRes && cityRes.data && cityRes.data[0].areaId
					})
					console.log(`区`, areaRes);
					picker.setColumnValues(1, cityRes.data)
					picker.setColumnValues(2, areaRes.data)
				}
				if (columnIndex === 1) {
					let areaRes = await $http.post('/api/v1/mp/area/listByPid', {
						pid: value && value[1].areaId
					})
					console.log(`区`, areaRes);
					picker.setColumnValues(2, areaRes.data)
				}


			},
			// 回调参数为包含columnIndex、value、values
			confirm(e) {
				const picker = this.$refs.uPicker
				const {
					value
				} = e
				this.form.province = value[0].areaName
				this.form.provinceId = value[0].areaId
				this.form.city = value[1].areaName
				this.form.cityId = value[1].areaId
				this.form.area = value[2].areaName
				this.form.areaId = value[2].areaId
				this.form.cityShow = value.map(item => item.areaName).join('-')
				this.show = false
				picker.setColumnValues(0, [])
				picker.setColumnValues(1, [])
				picker.setColumnValues(2, [])
			},
			cancel() {
				this.show = false
			},

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

			saveAddress() {
				// receiver: '',
				// mobile: '',
				// city: '',
				// addr: '',
				// privinceId: '', // 省ID/编码
				// privince: '', // 省
				// cityId: '', // 市ID/编码
				// city: '', // 市
				// areaId: '', // 区ID/编码
				// area: '', // 区
				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/channel/mall/addr/create'
				$http.post(url, this.form).then(res => {
					console.log(res);
					if (res.code == 0) {
						uni.$u.toast('保存成功');
						this.getDetail()
					}
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	/deep/ .u-navbar__content__title.u-navbar__content__title {
		color: #FFFFFF;
	}
</style>
<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 16rpx;
			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: 134rpx;
							height: 170rpx;
							margin-right: 20rpx;
						}
					}

					.info {
						display: flex;
						flex-direction: column;
						justify-content: space-between;

						text {
							font-size: 24rpx;
							color: #9D9D9D;
						}

						text:first-child {
							color: rgba(16, 16, 16, 100);
							font-size: 28rpx;
						}
					}
				}

				&__right {
					display: flex;
					height: 170rpx;
					flex-direction: column;
					justify-content: space-between;
					align-items: flex-end;

					text:first-child {
						font-size: 32rpx;
						color: $uni-text-color;
					}
				}

			}

			&__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: 10rpx 40rpx;

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

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

				.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>
