<template>
	<view class="bg" v-if="info">
		<view class="address box" @click="changeAddressPopup('open', '', key)" v-if="!contacts && info[0].is_post == 1">
			<!-- <image src="https://kunshan.xmainc.com/uploads/20230105/870e4ce1d5a661986d8a54e9f3c2b0b3.png" mode="aspectFill"></image> -->
			<view class="text">+ 添加邮寄地址</view>
		</view>
		<view class="contacts box" v-if="contacts && info[0].is_post == 1">
			<view class="contacts-left">
				<view class="name-phone">
					<view class="name">{{ contacts.name }}</view>
					<view class="phone">{{ contacts.tel }}</view>
				</view>
				<view class="adds text-overflowRows">{{ contacts.province_text + contacts.city_text + contacts.district_text + contacts.detail_addr }}</view>
			</view>
			<image @click="changeAddressPopup('open', '', key)" src="https://static.ticket.sz-trip.com/taizhou/images/detail/edit.png" mode="aspectFill"></image>
		</view>
		<view class="commodity box">
			<view class="merchant-name">
				{{info[0].merchant_name}}
			</view>
			<view style="margin-top: 20rpx;" class="" v-for="(item,index) in info" :key="item.id">
				<view class="goods">
					<image class="img" :src="showImg(item.specifications_image)" mode=""></image>
					<view class="" style="display: flex;flex-direction: column;justify-content: space-between;">
						<view class="">
							{{item.good_name}}
						</view>
						<!-- <view>
							<span class="info-tags" v-for="(itemT,indexT) in item.goods_new_tag.split(',').splice(0,2)" :key="indexT">{{itemT}}</span>
						</view> -->
					</view>
				</view>
				<view class="sku-info">
					<view class="title">
						<view class="text-overflowRows" style="font-size: 31rpx;font-weight: 500;color: #000;">{{ item.specifications_name }}</view>
						<view class="price-list">
							<view class="price-r">￥{{ item.Specifications_money / 100 }}</view>
							<!-- <view class="price-g">¥{{ info.skuInfo.price / 100 }}</view> -->
							<view class="price-g" v-if="item.post_money">￥{{ item.post_money / 100 }}</view>
						</view>
					</view>
					<view class="num-box">
						<view class="ctrl" @click="reduce(item)">-</view>
						<view class="num">{{item.num}}</view>
						<!-- <input class="num" :disabled="true" type="text" v-model="item.num" @input="rge($event)" @blur="setV()" /> -->
						<view class="ctrl" @click="plus(item)">+</view>
					</view>
				</view>
			</view>
		</view>
		<view class="person-info box" v-if="info[0].is_post == 0 && info[0].is_card == 1">
			<view class="person-title">购买信息</view>
			<view class="p_name line flex">
				<view class="left">用户姓名：</view>
				<input class="input" type="text" placeholder="请输入姓名" v-model="reserve_name" />
			</view>
			<view class="p_id line flex">
				<view class="left">身份证号：</view>
				<input class="input" type="text" placeholder="请输入身份证号" v-model="reserve_idcard" />
			</view>
			<view class="p_tel flex">
				<view class="left">手机号码：</view>
				<input class="input" type="text" placeholder="接受预定信息的号码" v-model="reserve_phone" />
			</view>
		</view>
		
		<!-- 优惠 -->
		<view class="youhui">
			<view class="" style="font-size: 32rpx;font-weight: bold;color: #000;">优惠</view>
			<view class="youhui-price">
				<view class="" style="color: #4D526C;font-weight: 500;">
					活动促销：
				</view>
				<view class="" style="color: #FC5109;font-weight: bold;">
					-￥{{delPrice}}
				</view>
			</view>
		</view>
		
		<!-- <view class="remark">
			<view class="">备注:</view>
			<input type="text" placeholder="订单备注" v-model="remark" maxlength="50"/>
		</view> -->
		<!-- <view class="" style="font-size: 24rpx;font-weight: 500;color: #FC5109;margin-left: 26.7rpx;margin-top: 27.33rpx;">
			*温馨提示：本商品不支持退换货
		</view> -->
		<view class="btn-list">
			<view class="price-box">
				<view class="text">合计:</view>
				<view class="price">{{ (allPrice + post)/100}}</view>
				<!-- <view class="price">{{ getAllPrice() - disPrice + (post / 100) }}</view> -->
				<view class="post" v-if="post">含邮费:¥{{ post / 100 }}</view>
			</view>
			<view class="btn" @click="order()">立即购买</view>
		</view>

		<!-- 选择收货地址弹窗 -->
		<uni-popup ref="addressPopup" type="bottom" backgroundColor="#F4F4F4">
			<view class="people-popup">
				<view class="top-box">
					<view class="top flex-between">
						<text class="text-overflow" @click="changeAddressPopup('close')">取消</text>
						<text class="confirm" @click="changeAddressPopup('close', 'confirm')">确定</text>
					</view>
				</view>
				<navigator url="/subPackages/user/myAddressAdd" class="button">添加收货地址</navigator>
				<view class="popup-list" v-if="addressList.length > 0">
					<view class="popup-item" v-for="(item, index) in addressList" :key="index" @click="seldThisAddress(item)">
						<view class="item-top flex-between">
							<view>
								<view class="name flex-start">
									{{ item.name }}
									<text>{{ item.tel }}</text>
									<text class="tag" v-if="item.is_default == 1">默认</text>
								</view>
								<view class="subtitle">{{ item.address }}</view>
							</view>
							<navigator :url="`/subPackages/user/myAddressAdd?id=${item.id}`">
								<img src="https://static.ticket.sz-trip.com/taizhou/images/detail/edit.png" alt="" />
							</navigator>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			contacts: null,
			info: null,
			num: 1,
			post: 0,
			flag: true,
			addressList: [],
			reserve_name: '',
			reserve_idcard: '',
			reserve_phone: '',
			remark: '',
			allPrice: 0, // 折扣后总价
			discounts:null,
			disPrice: {}, // 折扣对象
			delPrice:0
			// disPrice: 0
		};
	},
	onLoad() {
		this.info = this.$store.state.user.sshoppingCart
		this.info.forEach(item => {
			this.getDiscount(item)
		})
		if (!this.info) {
			uni.navigateBack();
		}
	},
	onShow() {
		this.getContacts();
		this.getAllAddressList();
		// this.getAllPrice()
		// this.getTotal()
	},
	methods: {
		// 获取总价
		getAllPrice() {
			this.info.forEach(item => {
				if ((item.Specifications_money * item.num) - (this.disPrice[item.specifications_id]*100) <= 0) {
					item.price1 = this.disPrice[item.specifications_id]
					item.price = 0
				} else{
					item.price1 = this.disPrice[item.specifications_id]
					let price = (item.Specifications_money * item.num) - (this.disPrice[item.specifications_id]*100)
					item.price  = +price.toFixed(2)
				}
			})
			let allPrice = 0
			let delPrice = 0
			this.info.forEach(item => {
				delPrice += item.price1
				allPrice += item.price
			})
			this.delPrice =  delPrice
			console.log('delPrice',this.delPrice);
			this.allPrice =  allPrice
		},
		
		getContacts() {
			if (this.info[0].is_post == 0) {
				return;
			}
			this.Post({}, '/api/user/getDefaultConsignee').then(res => {
				if (res) {
					this.contacts = res.data;
					this.getPost();
				}
			});
		},
		getPost() {
			if (this.info[0].is_post == 0 || !this.contacts) {
				return;
			}
			console.log(this.info,55555555,this.contacts);
			this.flag = false;
			let data = this.info.map((item) => {
				return { specifications_id:item.specifications_id, num: item.num, consignee_id: this.contacts.id }
			})
			// let data = [{ specifications_id: this.info.skuInfo.id, num: this.num, consignee_id: this.contacts.id }];
			console.log(data);
			this.Post({ data:JSON.stringify(data)}, '/api/order/getNewPost').then(res => {
				if (res) {
					this.post = 0
					res.data.forEach((item)=> {
						this.post += item.post_money
						const postItem = this.info.find(i => i.specifications_id == item.specifications_id)
						if(postItem) postItem.post_money = item.post_money
					})
					this.flag = true;
				}
			});
		},
		rge(val) {
			this.$nextTick(() => {
				this.num = val.detail.value.replace(/^(0+)|[^\d]+/g, '');
			});
		},
		setV() {
			if (!this.num) {
				this.$nextTick(() => {
					this.num = 1;
					if (this.flag) {
						this.getPost();
					}
				});
			} else {
				if (this.flag) {
					this.getPost();
				}
			}
		},
		plus(item) {
			// this.num = Number(this.num);
			this.$nextTick(() => {
				item.num += 1;
				this.getDiscount(item)
				// this.disPrice = this.calculateTotalPrice(this.discounts,this.num)
				// console.log(this.disPrice);
				if (this.flag) {
					this.getPost();
				}
			});
		},
		reduce(item) {
			if (item.num > 1) {
				this.$nextTick(() => {
					item.num -= 1;
					this.getDiscount(item)
					// this.disPrice =  this.calculateTotalPrice(item.discounts,item.num)
					console.log(this.disPrice);
					if (this.flag) {
						this.getPost();
					}
				});
			}
			// this.num = Number(this.num);
			// if (this.num > 1) {
			// 	this.$nextTick(() => {
			// 		this.num -= 1;
			// 		this.disPrice =  this.calculateTotalPrice(this.discounts,this.num)
			// 		console.log(this.disPrice);
			// 		if (this.flag) {
			// 			this.getPost();
			// 		}
			// 	});
			// }
		},
		//获取数量折扣
		getDiscount(item) { 
			this.Post({ specifications_id: item.specifications_id }, '/api/goods/getSpeNumDiscount').then(res => {
				this.discounts = res.data.discount_rule;
				if (this.discounts) {
					let disPrice_item = this.calculateTotalPrice(this.discounts,item.num)
					this.disPrice[item.specifications_id] = +disPrice_item
				} else {
					this.disPrice[item.specifications_id] = 0
				} 
				this.getAllPrice()
			});
		},
		//计算折扣价
		calculateTotalPrice(discounts, selectedQuantity) {
			if (discounts) {
				let totalPrice = 0;
				for (const discount of discounts) {
					if (selectedQuantity >= discount.num) {
						totalPrice = discount.money;
					}
				}
				return totalPrice;
			} else {
				return 0;
			}
		},
		// 选择收货地址弹窗
		changeAddressPopup(type, confirm, index) {
			if (type == 'open') {
				this.$refs.addressPopup.open('bottom');
			}
			else this.$refs.addressPopup.close();
			this.$forceUpdate();
		},
		// 获取收货地址列表
		getAllAddressList() {
			this.Post({}, '/api/user/consigneeList').then(res => {
				if (res.code === 200) this.addressList = res.data;
			});
		},
		// 选择收货地址
		seldThisAddress(item) {
			if (!this.contacts) this.contacts = {};
			Object.assign(this.contacts, item);
			if (this.flag) {
				this.getPost();
			}
			this.$refs.addressPopup.close();
			this.$forceUpdate();
		},
		// 预定
		order() {
			if (this.info[0].is_post == 1 && !this.contacts) {
				uni.showToast({
					title: '请选择收货地址',
					icon: 'none'
				});
				return;
			}
			if (this.info[0].is_post == 0 && this.info[0].is_card == 1) {
				if (!this.reserve_name) {
					uni.showToast({
						title: '请输入姓名',
						icon: 'none'
					});
					return;
				}
				if (!this.reserve_phone) {
					uni.showToast({
						title: '请输入电话',
						icon: 'none'
					});
					return;
				}
				if (!this.reserve_idcard) {
					uni.showToast({
						title: '请输入身份证',
						icon: 'none'
					});
					return;
				}
			}
			// let goods = [];
			let goods = this.info.map((item) => {
				return { specifications_id:item.specifications_id, num: item.num, consignee_id: item.is_post == 1 ? this.contacts.id : null }
			})
			// let goodsItem = {
			// 	specifications_id: this.info.skuInfo.id,
			// 	num: this.num,
			// 	consignee_id: this.info.skuInfo.is_post == 1 ? this.contacts.id : null
			// };
			// goods.push(goodsItem);
			let data = {
				goods: goods,
				coupon: null,
				remark: this.remark,
				is_post: this.info[0].is_post,
				reserve_name: this.reserve_name,
				reserve_phone: this.reserve_phone,
				reserve_idcard: this.reserve_idcard
			};
			this.Post(
				{
					method: 'POST',
					data: JSON.stringify(data)
				},
				'/api/order/place'
			).then(resT => {
				if (resT.code == 200) {
					this.Post(
						{
							order_id: resT.data.order_id,
							type: "miniprogram",
							// #ifdef MP-WEIXIN
							platform: 'miniprogram',
							// #endif
							// #ifdef H5
							platform: 'JSAPI',
							// #endif
						},
						'/api/pay/unify'
					).then(res => {
						if (res.data) {
							// #ifdef MP-WEIXIN
							uni.requestPayment({
								nonceStr: res.data.nonceStr,
								package: res.data.package,
								paySign: res.data.paySign,
								signType: res.data.signType,
								timeStamp: res.data.timeStamp,
								complete() {

								},
								success(){
									uni.showLoading({
										title:'加载中...'
									})
									setTimeout(()=>{
										uni.hideLoading()
										uni.navigateTo({
											url: '/subPackages/order/detail?id='+resT.data.order_id
										});
									},2000)
								}
							});
							// #endif
							// #ifdef H5
							WeixinJSBridge.invoke('getBrandWCPayRequest', {
								appId: res.data.appId,
								timeStamp: res.data.timeStamp,
								nonceStr: res.data.nonceStr,
								package: res.data.package,
								signType: res.data.signType,
								paySign: res.data.paySign
							}, function(Twores) {
								if (Twores.err_msg === 'get_brand_wcpay_request:ok') {
									uni.showLoading({
										title:'加载中...'
									})
									setTimeout(()=>{
										uni.hideLoading()
										uni.navigateTo({
											url: '/subPackages/order/detail?id='+resT.data.order_id
										});
									},2000)
								} else {
							
								}
							});
							// #endif
						}
					});
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.bg {
	min-height: 100vh;
	overflow-x: hidden;
	background: #f2f4f7;
	padding-bottom: 200rpx;
}
view {
	box-sizing: border-box;
}
.box {
	width: 710rpx;
	min-height: 100rpx;
	padding: 30rpx;
	background: #ffffff;
	border-radius: 16rpx;
	margin: 0 auto;
	margin-top: 20rpx;
}
.address {
	display: flex;
	align-items: center;
	justify-content: center;
	image {
		width: 32rpx;
		height: 32rpx;
	}
	.text {
		font-size: 28rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #6c7a94;
		margin-left: 18rpx;
	}
}
.commodity {
	// display: flex;
	// align-items: center;
	.img {
		width: 140rpx;
		height: 140rpx;
		background: #f2f4f7;
		border-radius: 10rpx;
		margin-right: 18rpx;
	}
	.title {
		width: 300rpx;
		margin-left: 20rpx;
		font-size: 30rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #000000;

		.price-list {
			width: 600rpx;
			display: flex;
			justify-content: space-between;
			margin-top: 18rpx;
			align-items: center;
			.price-r {
				font-size: 32rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 500;
				color: #FC5109;
				&:before {
					content: '小计：';
					display: inline-block;
					color: #000;
					font-size: 24rpx;
				}
			}
			.price-g {
				font-size: 32rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 500;
				color: #FC5109;
				&:before {
					content: '运费：';
					display: inline-block;
					color: #000;
					font-size: 24rpx;
				}
			}
		}
	}
	.num-box {
		display: flex;
		align-items: center;
		margin-left: 20rpx;
		width: 200rpx;
		justify-content: space-between;
		.num {
			text-align: center;
			width: 50rpx;
		}
		.ctrl {
			width: 70rpx;
			height: 60rpx;
			line-height: 60rpx;
			text-align: center;
			font-weight: bold;
			font-size: 36rpx;
		}
	}
}
.btn-list {
	width: 750rpx;
	height: 166rpx;
	background: #ffffff;
	box-shadow: 0rpx -3rpx 9rpx 1rpx rgba(227, 229, 232, 0.5);
	display: flex;
	position: fixed;
	bottom: 0;
	padding: 20rpx 50rpx;
	align-items: center;
	justify-content: space-between;
	.btn {
		width: 250rpx;
		height: 80rpx;
		background: #60989E;
		border-radius: 44rpx;
		text-align: center;
		line-height: 80rpx;
		font-size: 32rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #ffffff;
	}
	.price-box {
		display: flex;
		align-items: baseline;
		.text {
			font-size: 28rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #393b3e;
		}
		.price {
			margin-left: 15rpx;
			font-size: 48rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #FC5109;
			&:before {
				content: '¥';
				display: inline-block;
				color: #FC5109;
				font-size: 24rpx;
			}
		}
		.post {
			margin-left: 15rpx;
			color: #FC5109;
			font-size: 24rpx;
		}
	}
}
.contacts {
	display: flex;
	align-items: center;
	justify-content: space-between;
	image {
		width: 36rpx;
		height: 36rpx;
	}
	.contacts-left {
		.name-phone {
			display: flex;
			align-items: center;
			.name {
				font-size: 32rpx;
				font-family: PingFangSC-Medium, PingFang SC;
				font-weight: 500;
				color: #222222;
			}
			.phone {
				margin-left: 27rpx;
				font-size: 28rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #303030;
			}
		}
		.adds {
			font-size: 28rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #6c7a94;
			margin-top: 20rpx;
			max-width: 500rpx;
		}
	}
}
.people-popup {
	padding: 26rpx;
	min-height: 800rpx;

	.top-box {
		height: 80rpx;

		.top {
			position: fixed;
			left: 0;
			right: 0;
			color: #000;
			height: 80rpx;
			font-size: 0;
			overflow: hidden;
			padding: 0 26rpx;

			text {
				text-align: left;
				font-size: 30rpx;
				font-weight: 400;
				color: #000000;
			}

			.confirm {
				font-weight: 400;
				color: #000000;
			}
		}
	}

	.popup-list {
		height: 666rpx;
		overflow: scroll;

		.popup-item {
			border-radius: 12rpx;
			padding: 0 20rpx;
			margin-top: 24rpx;
			font-size: 24rpx;
			color: #333333;
			font-weight: 400;
			background-color: #ffffff;

			.item-top {
				padding: 32rpx;

				img {
					color: #666666;
					width: 40rpx;
					height: 40rpx;
				}

				.name {
					font-size: 30rpx;
					color: #000000;
					overflow: hidden;

					text {
						color: #999999;
					}

					.tag {
						width: 70rpx;
						height: 32rpx;
						background: #00d7ed;
						border-radius: 7rpx;
						line-height: 32rpx;
						text-align: center;
						font-size: 21rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #ffffff;
					}
				}

				.com-flex-start {
					margin: 0 0 30rpx;
				}

				.subtitle {
					font-weight: 400;
					flex: 1;
					text-align: left;
					margin-top: 33rpx;

					.mobile {
						margin-bottom: 36rpx;
					}
				}

				.status {
					width: 40rpx;
					height: 40rpx;
					line-height: 40rpx;
					border-radius: 50%;
					text-align: center;
					box-sizing: border-box;

					img {
						width: 27rpx;
						height: 21rpx;
					}
				}
				.statuss {
					background: linear-gradient(90deg, #fa2b66, #ff9834);
					border: none;
				}
				.noSelect {
					border: 1rpx solid #999999;
				}
			}

			// .item-site {
			// 	color: #666666;
			// 	display: flex;
			// 	align-items: center;
			// 	padding: 36rpx 0;

			// 	view {
			// 		width: 23rpx;
			// 		height: 23rpx;
			// 		margin-right: 10rpx;
			// 		border: 1rpx solid #999999;
			// 		border-radius: 50%;

			// 		view {
			// 			width: 8rpx;
			// 			height: 8rpx;
			// 			background: #000000;
			// 			border-radius: 50%;
			// 			margin: auto;
			// 		}
			// 	}
			// }
		}
	}

	.button {
		font-size: 30rpx;
		font-weight: 400;
		color: #000000;
		text-align: center;
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #ffffff;
		border-radius: 60rpx;
	}
}

.person-info {
	padding: 30rpx 30rpx 15rpx 30rpx;
	background: #fff;
	margin-top: 30rpx;
	border-radius: 16rpx;
}
.person-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #000;
}
.line {
	border-bottom: 1px solid #e3e5e8;
}
.flex {
	display: flex;
	align-items: center;
}
.left {
	width: 140rpx;
	font-size: 28rpx;
	font-weight: 500;
	color: #4d526c;
	height: 104rpx;
	line-height: 104rpx;
}
.input {
	font-size: 28rpx;
	font-weight: 400;
}
.remark {
	padding: 30rpx;
	display: flex;
	align-items: center;
	width: 710rpx;
	min-height: 150rpx;
	background: #ffffff;
	border-radius: 16rpx;
	margin: 0 auto;
	margin-top: 30rpx;
	view {
		color: #4d526c;
		font-size: 28rpx;
	}
	input {
		margin-left: 64rpx;
		width: 500rpx;
		font-size: 28rpx;
	}
}

.info-tags {
	padding: 8rpx 7rpx;
	text-align: center;
	line-height: 35rpx;
	font-size: 20rpx;
	font-weight: 500;
}

.info-tags:first-child {
	background: rgba(252,81,9,.08);
	color: #FC5109;
}

.info-tags:last-child {
	background: rgba(73,143,239,.1);
	color: #498FEF;
}

.merchant-name {
	margin-bottom: 24rpx;
}

.goods {
	display: flex;
}

.sku-info {
	display: flex;
	margin-top: 26rpx;
	align-items: baseline;
	justify-content: space-between;
	border-bottom: 1rpx solid #ccc;
	padding-bottom: 25.3rpx;
}

.sku-info:last-child {
	border:none !important;
}

.youhui {
	width: 710rpx;
	margin: 0 auto;
	margin-top: 22rpx;
	padding: 32.67rpx 19.33rpx 32.67rpx 24rpx;
	background: #FFFFFF;
	border-radius: 13rpx;
}

.youhui-price {
	margin-top: 52.67rpx;
	display: flex;
	justify-content: space-between;
	margin-left: .67rpx;
	font-size: 27rpx;
}

</style>
