<template>
	<view class="confirm-order flex-1 position-relative" :class="[{'confirm-order-p-b': consumption}]">
		<view class="confirm-order-item flex align-center">
			<view class="flex-11">
				<view class="flex align-center">
					<view class="m-r-14">
						<u-icon size="40" name="map-fill" color="#01AEEA"></u-icon>
					</view>
					<view class="confirm-order-address font-30">
						{{ location.type === 'shop' ? `站点：${location.name}` : `${location.shippingAddress} ${location.addressDetail}` }}
					</view>
				</view>

				<view class="confirm-order-user m-t-20" v-if="location.type === 'user'">
					<text class="m-r-40">{{ location.name }}</text>
					<text>{{ location.phone }}</text>
				</view>
			</view>
			<!--  站点 -->
			<view class="shopIcon shopIcon-color" v-if="location.type === 'shop'" @click="selectAddress(0)">
				站点
				<u-icon size="30" name="arrow-right" color="#ccc"></u-icon>
			</view>
			<!-- 地址 -->
			<view class="shopIcon" @click="selectAddress(1)">
				<text v-if="location.type === 'shop'">地址</text>
				<u-icon size="30" name="arrow-right" color="#ccc"></u-icon>
			</view>
		</view>

		<view class="confirm-order-item">
			<view v-for="(item, index) in goodsProducts.list" :key="item.id">
				<view class="confirm-order-goods bg-white m-b-20"
					v-show="index < (!showItem ? 2 : goodsProducts.list.length - 1) ">
					<view class="flex-1 flex align-start">
						<view class="m-r-20">
							<image class="confirm-order-goods-image" :src="item.shopImage2" mode="aspectFill"></image>
						</view>
						<view class="confirm-order-goods-info flex-1 flex flex-column justify-between">
							<view class="confirm-order-goods-info-title ">{{ item.shopName }}</view>

							<view class="confirm-order-goods-info-specs">{{ item.shopSkuParam }}</view>

							<view class="flex align-center justify-between">
								<view class="font-24 text-red flex align-end">
									<text v-if="options.orderType != 2">￥</text>
									<text class="font-32">{{ item.price.toFixed(2)/item.shopNum }}</text>
									<!-- <text class="font-32">{{ item.payMoney.toFixed(2)/item.shopNum }}</text> -->
									
									
									
									<text v-if="options.orderType == 2">元兑购金</text>
								</view>

								<view class="confirm-order-goods-number">x{{ item.shopNum }}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="font-24 text-grey p-t-10 p-b-10 flex align-center justify-center"
				v-if="goodsProducts.list.length > 3" @click="showItem = !showItem">
				{{ !showItem ? `展开（共${goodsProducts.list.length}件）` : '收起' }}
				<u-icon :name="!showItem ? 'arrow-down' : 'arrow-up'"></u-icon>
			</view>
		</view>

		<view class="confirm-order-item">
			<view class="font-30 font-weight-bold m-b-10">价格明细</view>
			<view class="flex align-center justify-between m-b-20">
				<view class="">
					<text class="m-r-10 font-28">商品总价</text>
					<!-- <text class="font-24 text-grey">共{{ goodsProducts.list.length }}件商品</text> -->
				</view>
				<view class="flex align-end text-black">
					<text class="font-22" v-if="options.orderType != 2">￥</text>
					<text class="font-28">{{ goodsProducts.amount.toFixed(2) }}</text>
					<text class="font-28" v-if="options.orderType == 2">元兑购金</text>
				</view>
			</view>

			<view class="flex align-center justify-between m-t-40" v-if="options.orderType != 2"
				@click="handleRadio('weChat', 'consumption')">
				<view class="flex align-center">
					<image class="confirm-order-goods-price-img m-r-6" :src="IMG_URL+'wx.png'" />
					<text class="font-28">微信支付</text>
				</view>
				<view class="confirm-order-radio flex align-center justify-center" :class="{'is-active': weChat}">
					<u-icon name="checkbox-mark" color="#fff" v-if="weChat"></u-icon>
				</view>
			</view>

			<view class="flex align-center justify-between m-t-40"
				v-if="(options.orderType == 0 || options.orderType == 3) && options.isZone != 1"
				@click="handleRadio('consumption', 'weChat')">
				<view class="flex align-center">
					<image class="confirm-order-goods-price-img m-r-6" :src="IMG_URL+'xfj.png'" />
					<text class="font-28">消费金支付</text>
				</view>
				<view class="flex align-center">
					<view class="flex align-end text-red font-24 m-r-10">
						<text>消费金余额</text>
						<text class="font-20">￥</text>
						<text>{{ goodsProducts.deduction > 0 ? goodsProducts.deduction : 0 }}元</text>
					</view>

					<view class="confirm-order-radio flex align-center justify-center"
						:class="{'is-active': consumption}">
						<u-icon name="checkbox-mark" color="#fff" v-if="consumption"></u-icon>
					</view>
				</view>
			</view>

			<view class="flex align-center justify-between m-t-40"
				v-if="goodsProducts.coupon && (options.orderType == 0 || options.orderType == 3)" @click="toCoupon">
				<view class="flex align-center">
					<image class="confirm-order-goods-price-img m-r-6" :src="IMG_URL +'yhj.png'" />
					<text class="font-28 m-r-10">优惠券</text>
					<text class="font-24 text-grey" v-if="Object.keys(coupon).length">{{ coupon.name }}</text>
				</view>
				<view class="flex align-center">
					<view class="flex align-end text-red font-24 m-r-10" v-if="Object.keys(coupon).length">
						<text>减</text>
						<text class="font-20">￥</text>
						<text>{{ coupon.price }}</text>
					</view>
					<text class="font-28 m-r-10 text-grey" v-else>去使用</text>
					<u-icon name="arrow-right"></u-icon>
				</view>
			</view>
		</view>

		<view class="confirm-order-item align-center flex justify-between" v-if="options.orderType != 2">
			<view class="flex align-center">
				<text class="font-28 m-r-6">运费</text>
				<text class="font-24 text-grey">满{{ goodsProducts.FullMinusPrice }}元包邮</text>
			</view>

			<text class="font-28 text-red">{{ goodsProducts.freight }}元</text>
		</view>


		<view class="confirm-order-tips position-fixed left-0 text-red" v-if="consumption">
			微信支付，可返兑购金或消费金；
			消费金支付，不返兑购金与消费金；
		</view>

		<view class="confirm-order-footer position-fixed bottom-0 left-0 flex align-center justify-between">
			<view class="flex align-end font-32">
				<text>合计：</text>
				<view class="font-24 text-red flex align-end" v-if="options.orderType !== 2">
					<text>￥</text>
					<text class="font-42">{{ totalprice | numberFormat }}</text>
				</view>
				<!-- 兑购 -->
				<view class="font-24 text-red flex align-end" v-else>
					<text class="font-32">{{ goodsProducts.amount.toFixed(2) }} 元兑购金</text>
				</view>
			</view>

			<u-button type="primary" shape="circle" class="confirm-order-footer-button" v-if="options.orderType != 2" @click="onPayment">支付</u-button>
			<u-button type="primary" shape="circle" class="confirm-order-footer-button" v-if="options.orderType == 2" @click="onPayment">兑购</u-button>
		</view>
	</view>
</template>

<script>
	import {
		IMG_URL
	} from '@/env.js'
	export default {
		data() {
			return {
				IMG_URL,
				showItem: false,
				consumption: '',
				weChat: true,
				goodsProducts: [],
				options: {},
				coupon: {},
				allMoney: '' ,// 合计多少钱
			};
		},
		onLoad(options) {
			this.options = options
			this.getConfirmOrderGoodsInfo()

			// uni.$on('SELECT_ADDRESS', obj => {
			// 	this.goodsProducts.address = { ...this.goodsProducts.address, ...obj}
			// 	console.log(obj)
			// })
			uni.$on('coupon', obj => {
				console.log(obj)
				this.coupon = obj
			})
		},
		onUnload() {
			// uni.$off('SELECT_ADDRESS')
			uni.$off('coupon')
		},
		computed: {
			totalprice() {
				let consumption = this.consumption ? this.goodsProducts.deduction : 0 // 消费金
				let coupon = Object.keys(this.coupon).length ? this.coupon.price : 0 // 优惠券
				// 不要减去消费金  - consumption
				let payPrice = this.goodsProducts.amount - coupon
				// 包邮  满多少包邮问题 goodsProducts.FullMinusPrice  goodsProducts.freight
				payPrice = this.goodsProducts.amount >= this.goodsProducts.FullMinusPrice ? payPrice : payPrice + this
					.goodsProducts.freight
					this.allMoney = payPrice
				return payPrice > 0 ? payPrice : 0
			},
			location() {
				return this.$store.state.location
			},
			shopId() {
				return this.location.type === 'shop' ? this.location.id : ''
				// return this.location.id
			}
		},
		methods: {
			handleRadio(key1, key2) {
				if (this[key1]) return
				this[key1] = true
				this[key2] = false

			},
			selectAddress(index) {
				// index 为 1 地址 为 0 站点
				if(index == 1){
					this.$tools.navigateTo({
						url: '/pages/my/address/address?type=select'
					})
				}else{
					this.$tools.navigateTo({
						url: '/pagesC/receiving/receiving?type=select'
					})
				}
				// 
				// if (this.location.type === 'shop') {
				// 	this.$tools.navigateTo({
				// 		url: '/pagesC/receiving/receiving?type=select'
				// 	})
				// } else {
				// 	this.$tools.navigateTo({
				// 		url: '/pages/my/address/address?type=select'
				// 	})
				// }
			},
			getConfirmOrderGoodsInfo() {
				console.log('this.options.orderType', this.options.orderType)
				uni.showLoading()
				let type = this.options.orderType === 3 ? 2 : this.options.orderType
				let params = {
					ids: this.options.ids,
					type,
				}
				console.log(this.options)
				params = this.shopId ? {
					...params,
					shopId: this.shopId
				} : params
				this.$api('getConfirmOrderGoodsInfo', params)
					.then(res => {
						uni.hideLoading()
						if (res.code === 200) {
							res.result.list.forEach(item => item.shopImage2 = item.shopImage.split(',')[0])
							this.goodsProducts = res.result
						} else {
							this.$Toast(res.message)
						}
					})
					.catch(err => {
						this.$Toast(err.message)
						uni.hideLoading()
					})
			},
			// getaddress_lo() {
			// 	// 获取用户的经纬度
			// 		wx.chooseLocation({
			// 			success: (data) => {
			// 				// 获取经纬度
			// 				console.log(data);
			// 				let {latitude, longitude } = data
			// 				this.longitude = longitude;
			// 				this.latitude = latitude;
			// 				// 调取站长列表
			// 				this.getStationmasterList(longitude,latitude);
			// 			},
			// 			fail: () => {
			// 				wx.getSetting({
			// 					success: function(res) {
			// 						var statu = res.authSetting;
			// 						console.log(statu);
			// 						if (!statu['scope.userLocation']) {
			// 							console.log(123);
			// 							wx.showModal({
			// 								title: '是否授权当前位置',
			// 								content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
			// 								success(tip) {
			// 									if (tip.confirm) {
			// 										wx.openSetting({
			// 											success: function(data) {
			// 												if (data.authSetting["scope.userLocation"] === true) {
			// 													this.$Toast('授权成功');
			// 													//授权成功之后，再调用chooseLocation选择地方
			// 													setTimeout(function(){
			// 														wx.chooseLocation({
			// 															success: (data) => {
			// 																// 获取经纬度
			// 																let {latitude, longitude } = data
			// 																this.longitude = longitude;
			// 																this.latitude = latitude;
			// 																// 调取站长列表
			// 																this.getStationmasterList(longitude,latitude);
			// 															}
			// 														})
			// 													},1000)
			// 												}
			// 											}
			// 										})
			// 									} else {
			// 										this.$Toast('授权失败');
			// 									}
			// 								}
			// 							})
			// 						}
			// 					}
			// 				})
			// 			}
			// 		});
			// },
			getStationmasterList(longitude, latitude) {
				const params = {
					longitude,
					latitude
				}
				this.$api('getStationmasterList', params).then(res => {
					let {
						code,
						result,
						message
					} = res;
					if (code == 200) {
						result.forEach(item => {
							item.distance = this.GetDistance(item.latitude, item.longitude);
						})
						if (result.length == 0) {
							// 没有 站长就不用做什么

						}
						// 有站长 用户选择一个
						console.log(this.addressData)
					} else {
						this.$Toast(message)
					}
				}).catch(err => {
					this.$Toast(err.message)
				})
			},
			onPayment() {
				// 查找附近有没有站长
				const that = this
				// this.getaddress_lo()
				if (this.options.orderType == 0) {
					// couponId: this.coupon?.couponId || '',
					let params = {
						addressId: this.location.id,
						ids: this.options.ids,
						type: this.consumption ? 1 : 0,
						shopId: this.shopId
					}
					// 1 消费金支付 提示
					if (params.type == 1) {
						uni.showModal({
							title: `确定使用${this.allMoney}元消费金抵购`,
							success(res) {
								if (res.confirm) {
									// 确定
									that.$api('createOrder', params).then(res => {
											let {
												code,
												result,
												message
											} = res
											if (res.code === 200) {
												!that.consumption && that.weChatPay(result)
												if (that.consumption) {
													that.$Toast(message)
													setTimeout(() => {
														uni.redirectTo({
															url: '/pages/my/order/index?status=1'
														})
													}, 1000)
												}
												uni.$emit('updateShoppingCartList')
											} else {
												
												that.$Toast(message)
												if(message == '地址信息错误'){
													that.$tools.navigateTo({
														url: '/pages/my/address/address?type=select'
													})
												}else{
													setTimeout(() => {
														uni.redirectTo({
															url: '/pages/my/order/index?status=0'
														})
													}, 1000)
												}
												
											}
											console.log(res)
										})
								} else {
									// 取消
								}
							}
						})
					} else {
						this.$api('createOrder', params)
							.then(res => {
								let {
									code,
									result,
									message
								} = res
								if (res.code === 200) {
									!this.consumption && this.weChatPay(result)
									if (this.consumption) {
										this.$Toast(message)
										setTimeout(() => {
											uni.redirectTo({
												url: '/pages/my/order/index?status=1'
											})
										}, 1000)
									}
									uni.$emit('updateShoppingCartList')
								} else {
									this.$Toast(message)
									// setTimeout(() => {
									// 	uni.redirectTo({
									// 		url: '/pages/my/order/index?status=0'
									// 	})
									// }, 1000)
									if(message == '消费余额不足,请选择微信支付'){
										console.log(123123)
										uni.showModal({
											title: `您的消费金不足, 请使用微信进行支付！`,
											success(res) {
												}
											});
									} else if(message == '地址信息错误'){
										this.$tools.navigateTo({
											url: '/pages/my/address/address?type=select'
										})
									}else{
										setTimeout(() => {
											uni.redirectTo({
												url: '/pages/my/order/index?status=0'
											})
										}, 1000)
									}
								}
								console.log(res)
							})
					}

				} else { // 拼团 1 && 消费金 2
					console.log(this.options.orderType)
					let type = this.options.orderType == 1 || this.options.orderType == 3 ? this.consumption ? 1 : 0 : 2
					let params = {
						addressId: this.location.id,
						id: this.options.ids,
						type,
						shopId: this.shopId
					}
					const that = this;
					if (this.options.orderType == 3 && this.consumption) {
						uni.showModal({
							title: `确定使用${this.allMoney}元消费金抵购`,
							success(res) {
								if(res.confirm){
									// 确定
									that.$api('teamCreateOrderPay', params)
										.then(res => {
											let {
												code,
												result,
												message
											} = res
											if (res.code === 200) {
												uni.$emit('updateShoppingCartList')
												if (type == 0) {
													that.weChatPay(result)
												} else {
													that.$Toast(message)
													setTimeout(() => {
														uni.redirectTo({
															url: '/pages/my/order/index?status=1'
														})
													}, 1000)
												}
											} else {
												// that.$Toast(message+12)
												// setTimeout(() => {
												// 	uni.redirectTo({
												// 		url: '/pages/my/order/index?status=0'
												// 	})
												// }, 1000)
												if(message == '消费余额不足,请选择微信支付'){
													console.log(123123)
													uni.showModal({
														title: `您的消费金不足, 请使用微信进行支付！`,
														success(res) {
															}
														});
												}else if(message == '地址信息错误'){
													that.$tools.navigateTo({
														url: '/pages/my/address/address?type=select'
													})
												}else {
													setTimeout(() => {
														uni.redirectTo({
															url: '/pages/my/order/index?status=0'
														})
													}, 1000)
												}
											}
									
											console.log(res)
										})
								}else {
									// 取消
								}
							}
						})
					}else if(this.options.orderType == 3 && this.weChat) {
						that.$api('teamCreateOrderPay', params)
								.then(res => {
									let {
										code,
										result,
										message
									} = res
									if (res.code === 200) {
										uni.$emit('updateShoppingCartList')
										if (type == 0) {
											that.weChatPay(result)
										} else {
											that.$Toast(message)
											setTimeout(() => {
												uni.redirectTo({
													url: '/pages/my/order/index?status=1'
												})
											}, 1000)
										}
									} else {
										that.$Toast(message)
										// setTimeout(() => {
										// 	uni.redirectTo({
										// 		url: '/pages/my/order/index?status=0'
										// 	})
										// }, 1000)
										if(message == '地址信息错误'){
											that.$tools.navigateTo({
												url: '/pages/my/address/address?type=select'
											})
										}else{
											setTimeout(() => {
												uni.redirectTo({
													url: '/pages/my/order/index?status=0'
												})
											}, 1000)
										}
									}
							
									console.log(res)
								})
							
					} else {
						this.$api('teamCreateOrderPay', params)
							.then(res => {
								let {
									code,
									result,
									message
								} = res
								if (res.code === 200) {
									uni.$emit('updateShoppingCartList')
									if (type == 0) {
										this.weChatPay(result)
									} else {
										this.$Toast(message)
										setTimeout(() => {
											uni.redirectTo({
												url: '/pages/my/order/index?status=1'
											})
										}, 1000)
									}
								} else {
									this.$Toast(message)
									if(message == '地址信息错误'){
										this.$tools.navigateTo({
											url: '/pages/my/address/address?type=select'
										})
									}else{
										setTimeout(() => {
											uni.redirectTo({
												url: '/pages/my/order/index?status=0'
											})
										}, 1000)
									}
									// setTimeout(() => {
									// 	uni.redirectTo({
									// 		url: '/pages/my/order/index?status=0'
									// 	})
									// }, 1000)
								}
						
								console.log(res)
							})
					}
					
				}
			},
			weChatPay(params) {
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: params.timeStamp,
					nonceStr: params.nonceStr,
					package: params.packageValue,
					signType: params.signType,
					paySign: params.paySign,
					success: res => {
						this.$Toast('支付成功');
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/my/order/index?status=1'
							})
						}, 1000)
					},
					fail: error => {
						this.$Toast('已取消支付')
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/my/order/index?status=0'
							})
						}, 1000)
					}
				})
			},
			toCoupon() {
				this.$tools.navigateTo({
					url: '/pages/my/coupon/coupon?id=' + this.options.ids
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	.confirm-order {
		background: #f5f5f5;
		padding: 20rpx 32rpx 120rpx;
		box-sizing: border-box;

		&-p-b {
			padding-bottom: 220rpx;
		}

		&-item {
			padding: 20rpx;
			background: #ffffff;
			border-radius: 14rpx;
			box-shadow: 0 6rpx 12rpx 0 rgba(0, 0, 0, 0.16);
			margin-bottom: 40rpx;
		}

		&-address {
			font-size: 24rpx;
			font-family: Microsoft YaHei, Microsoft YaHei-Regular;
			color: #707070;
			padding-right: 10rpx;
		}

		&-user {
			font-size: 28rpx;
			font-family: Microsoft YaHei, Microsoft YaHei-Regular;
			color: #333;
		}

		&-radio {
			width: 34rpx;
			height: 34rpx;
			border: 1px solid #c8c9cc;
			border-radius: 50%;

			&.is-active {
				background: #01AEEA;
				border: 0;
			}
		}

		&-item {
			border-radius: 20rpx;
			padding: 30rpx;


		}

		&-goods {
			&-image {
				width: 200rpx;
				height: 200rpx;
				border-radius: 12rpx;
			}

			&-number {
				font-size: 24rpx;
				color: #ccc
			}

			&-info {
				min-height: 200rpx;

				&-specs {
					font-size: 30rpx;
					font-family: Microsoft YaHei, Microsoft YaHei-Regular;
					color: #6c6c6c;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					/*设置对齐模式：垂直对齐*/
					-webkit-line-clamp: 2;
					/*设置多行的行数*/
				}

				&-title {
					font-size: 32rpx;
					font-family: Microsoft YaHei, Microsoft YaHei-Regular;
					color: #000000;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					/*设置对齐模式：垂直对齐*/
					-webkit-line-clamp: 2;
					/*设置多行的行数*/
				}
			}

			&-price {
				&-img {
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
				}
			}

		}


		&-footer {
			width: 100%;
			height: 120rpx;
			background-color: #fff;
			padding: 0 32rpx;
			box-sizing: border-box;

			&-button {
				
				/deep/.u-btn {
					width: 260rpx;
					height: 70rpx;
					font-size: 36rpx;
				}
			}
		}

		&-tips {
			bottom: 120rpx;
			padding: 20rpx;
			box-sizing: border-box;
			height: 100rpx;
			background: #D8F5FF;
			line-height: 32rpx;
		}

		::v-deep .u-checkbox {
			display: block;
		}

		::v-deep .u-radio {
			display: block;
		}


	}
	
	.shopIcon{
		text-align: center;
		width: 120rpx;
		height: 100%;
	}
	.shopIcon-color{
		::v-deep .uicon-arrow-right{
			color: #01AEEA !important;
		}
	}
</style>
