<template>
	<view class="main" style="padding-bottom: 136rpx;" v-if="ifLoading">
		<!-- 头部 -->
		<status-nav navBarTitle="确认订单"></status-nav>
		<!-- 内容区 -->
		<view class="content">
			<!-- 订单地址 -->
			<view v-if="drawType == 1">
				<view class="section-other order-addr" style="margin-top: 0;" @tap="ifAddress = true">
					<view class="txt" v-if="addressIndex >= 0">
						<view class="address">
							<view class="type" v-if="addrList[addressIndex].is_default==1">默认</view>
							<view>
								{{addrList[addressIndex].province_str}}{{addrList[addressIndex].city_str}}{{addrList[addressIndex].county_str}}
							</view>
						</view>
						<view class="street">{{addrList[addressIndex].address}}</view>
						<view class="name">
							<text>{{addrList[addressIndex].name}}</text>
							<text>{{addrList[addressIndex].phone}}</text>
						</view>
					</view>
					<view class="txt" v-else>请添加地址</view>
					<image src="/static/icon/icon-arrow-right.png" mode="heightFix" style="height: 24rpx;">
					</image>
				</view>
			</view>

			<!-- 自提点 -->
			<view v-else>
				<view class="section-other order-addr" style="margin-top: 0;" @tap="ifDraw = true">
					<view class="txt" v-if="drawIndex >= 0">
						<view class="address">
							<text>{{drawList[drawIndex].name}}</text>
						</view>
						<view class="street">{{drawList[drawIndex].address}}</view>
						<view class="name">
							<view class="fs12" style="color: #f72e2e;">距您：{{drawList[drawIndex].distance.toFixed(2)}}
								m</view>
						</view>
					</view>
					<view class="txt" v-else>请选择自提点</view>
					<image src="/static/icon/icon-arrow-right.png" mode="heightFix" style="width: 16rpx;height: 28rpx;">
					</image>
				</view>
			</view>
			<view class="prepare-info">
				<!-- 订单列表 -->
				<view class="section-other order-list">
					<view class="item" v-for="(item,index) in prepareInfo" :key="index">
						<view class="img">
							<image :src="baseHttps+item.goods_cover" mode="aspectFit"></image>
						</view>
						<view class="txt">
							<view class="tit">{{item.goods_name}}</view>
							<view class="sting">{{item.title}}</view>
							<view class="price-box">
								<view class="price-bg">
									<view class="price">
										<text>￥</text>
										<text>{{item.price.substr(0,item.price.indexOf('.'))}}</text>
										<text>{{item.price.substr(item.price.indexOf('.'),item.price.length)}}</text>
									</view>
								</view>
								<view class="number">x{{item.num}}</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 订单概况 -->
				<view class="section-other order-info">
					<view class="item">
						<text>商品数量</text>
						<text>{{prepareInfo.length}}件</text>
					</view>
					<view class="item">
						<text>商品金额</text>
						<text>￥{{payAmount}}</text>
					</view>


					<view class="item" v-if="drawType == 2">
						<text>预留姓名<text class="import">*</text></text>
						<input type="text" class="input" placeholder="请输入您的姓名" v-model="orderName">
					</view>

					<view class="item" v-if="drawType == 2">
						<text>预留手机号<text class="import">*</text></text>
						<input type="number" class="input" placeholder="请输入您的手机号" v-model="orderPhone">
					</view>
					<view class="item">
						<text>订单备注</text>
						<text>(建议留言前先与商家沟通确认)</text>
						<div class="mt10" style="width: 100%;">
							<textarea v-model="remarks" style="height: 200rpx;width: 100%;"
								placeholder="请填写留言"></textarea>
						</div>
					</view>
				</view>
			</view>
		</view>
		<!-- 尾部 -->
		<view class="confirm-foot">
			<view class="actual-pay">
				<text>实付：</text>
				<view class="price">
					<text>￥</text>
					<text>{{payAmount}}</text>
				</view>
			</view>
			<view class="submit-btn" @tap="submitEv">提交订单</view>
		</view>


		<!-- 提示框 -->
		<view class="pull-pop-bg pull-pop-center" v-if="ifTips">
			<view class="pull-pop">
				<view class="title">{{tips.title}}</view>
				<view class="msg">{{tips.msg}}</view>
				<view class="btns">
					<view class="btn" @tap="goPage(tips.url)">{{tips.btnMsg}}</view>
				</view>
				<view class="close-btn" @tap="ifTips=false">
					<image src="/static/icon/icon-close.png" mode="widthFix"></image>
				</view>
			</view>
		</view>

		<!-- 收货地址弹窗 -->
		<u-popup :show="ifAddress" mode="bottom" :closeable="true" @close="ifAddress = false">
			<view class="address-pop">
				<view class="title">请选择收货地址</view>
				<scroll-view class="addr-list" scroll-y="true">
					<view class="item" :class="addressIndex == index ? 'on' : ''" v-for="(item,index) in addrList"
						:key="index" @tap.stop="choseAddr(index)">
						<view class="txt">
							<view class="address">
								<view class="type" v-if="item.is_default==1">默认</view>
								<text>{{item.province_str}} {{item.city_str}} {{item.county_str}}</text>
							</view>
							<view class="street">{{item.address}}</view>
							<view class="name">
								<text>{{item.name}}</text>
								<text>{{item.phone}}</text>
							</view>
						</view>
						<image class="btn" src="/static/icon/icon-edit.png" mode="heightFix"
							@tap.stop="toEdit(item.id)"></image>
					</view>
				</scroll-view>
				<view class="add-address-btn" @tap="toAdd">新增收货地址</view>
			</view>
		</u-popup>


		<!-- 自提点弹窗 -->
		<u-popup :show="ifDraw" mode="bottom" :closeable="true" @close="ifDraw = false">
			<view class="address-pop">
				<view class="title">请选择自提点</view>
				<scroll-view class="addr-list" scroll-y="true">
					<view class="item" :class="drawIndex == index ? 'on' : ''" v-for="(item,index) in drawList"
						:key="index" @tap.stop="choseDraw(index)">
						<view class="txt">
							<view class="address row-between">
								<view class="flex">
									<u-icon name="map" color="#999" size="16"></u-icon><text
										class="ml5">{{item.name}}</text>
								</view>
								<view class="flex">
									距您：<text style="color: #f72e2e;">{{item.distance.toFixed(2)}} m</text></text>
								</view>
							</view>
							<view class="street flex"><text>{{item.address}}</text></view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import {
		getAddress,
		postPrepare,
		getNearestPoint,
		postOrderCreate,
		postOrderCheck
	} from "@/api/index";
	export default {
		data() {
			return {
				statusHeight: uni.getSystemInfoSync().statusBarHeight, //状态栏高度
				baseHttps: `${getApp().globalData.hostapi}`, //接口链接
				ifAddress: false, //是否显示地址弹框
				prepareInfo: [], //订单准备信息
				ifLoading: false,
				addrList: [], //地址列表
				addressIndex: -1, //默认地址第几个
				payAmount: '', //实际支付
				remarks: '', //备注
				tips: {
					title: '',
					msg: '',
					url: '',
					btnMsg: ''
				}, //提示框内容
				ifTips: false, //是否显示提示框
				flag: true, //是否可提交


				userInfo: uni.getStorageSync("userInfo"),
				sku_list: [], //商品传参信息
				drawType: 0, // 提取类型 1 邮寄，2自提
				ifDraw: false, //是否显示自提点弹框
				drawList: [], //自提点列表
				drawIndex: -1,

				orderName: '', //预留姓名
				orderPhone: '', //预留电话
			};
		},
		onLoad(op) {
			if (op.data) {
				let obj = JSON.parse(decodeURIComponent(op.data));
				this.sku_list.push(obj.sku_list);
				this.drawType = obj.type;
				console.log(obj)
			}
			this.orderPhone = this.userInfo.mobile;
			// 获取订单准备信息
			this.getPrepareInfo();
		},
		onShow() {
			// 获取地址列表
			if (this.drawType == 1) {
				this.getAddrList();
			} else {
				this.getDrawList();
			}

		},
		computed: {},
		methods: {
			// 获取地址列表
			getAddrList() {
				getAddress().then(res => {
					if (res.code == 0) {
						console.log(res, '地址列表');
						this.addrList = res.data;
						if (res.data.length > 0) {
							const index = res.data.findIndex(item => item.is_default === 1);
							if (index !== -1) {
								this.addressIndex = index;
							}
						}
					}
				})
			},


			// 获取自提点列表
			getDrawList() {
				let params = {
					lng: uni.getStorageSync("locationList").lng,
					lat: uni.getStorageSync("locationList").lat,
					limit: 20,
				}
				getNearestPoint(params).then(res => {
					if (res.code == 0) {
						this.drawList = res.data;
					}
				})
			},

			// 选择地址
			choseAddr(index) {
				this.addressIndex = index;
				this.ifAddress = false;
			},

			// 选择自提点
			choseDraw(index) {
				this.drawIndex = index;
				this.ifDraw = false;
			},
			// 获取订单准备信息
			getPrepareInfo() {
				let pargams = {
					sku_list: this.sku_list
				}
				postPrepare(JSON.stringify(pargams)).then(res => {
					if (res.code == 0) {
						res.data.forEach(item => {
							let item1 = this.sku_list.find(item1 => item1.sku_id === item.id);
							item.num = item1.num;
						})
						this.prepareInfo = res.data;

						this.payAmountEv();
					}
				})
			},

			// 计算实付金额
			payAmountEv() {
				let payAmount = 0;
				this.prepareInfo.forEach(item => {
					let price = Number(item.price) * Number(item.num);
					payAmount = price++
				})
				console.log(payAmount, this.prepareInfo)
				this.payAmount = payAmount;
				this.ifLoading = true;
			},

			// 去新增
			toAdd() {
				uni.navigateTo({
					url: '/pagesA/address/addAddress?type=add'
				})
			},

			// 去编辑
			toEdit(id) {
				uni.navigateTo({
					url: `/pagesA/address/addAddress?type=edit&id=${id}`
				})
			},

			// 跳转
			goPage(url) {
				uni.navigateTo({
					url: url
				})
			},

			// 提交订单
			submitEv() {
				let shipping_method,
					params,
					that = this;
				if (this.drawType == 1) { //邮寄
					if (this.addressIndex < 0) return this.$toolAll.tools.showToast('请选择地址！');
					shipping_method = 'delivery';
					params = {
						sku_list: this.sku_list,
						address_id: this.addrList[this.addressIndex].id,
						remarks: this.remarks,
						shipping_method: shipping_method
					}
				} else { //自提
					if (this.drawIndex < 0) return this.$toolAll.tools.showToast('请选择自提点！');
					if (this.orderName == '') return this.$toolAll.tools.showToast('请填写预留姓名！');
					if (this.orderPhone == '') return this.$toolAll.tools.showToast('请填写预留电话！');
					shipping_method = 'self';
					params = {
						sku_list: this.sku_list,
						self_name: this.orderName,
						self_phone: this.orderPhone,
						remarks: this.remarks,
						shipping_method: shipping_method,
						self_id:this.drawList[this.drawIndex].id,
					}
				}

				if (this.flag) {
					this.flag = false;
					postOrderCreate(params).then(res => {
						if (res.code == 0) {
							console.log(res, '提交成功');
							// 发起支付
							this.callPayMent(res.data.pay_params.jsapi, res.data.coding);
						} else {
							this.$toolAll.tools.showToast(res.msg);
						}
						setTimeout(() => {
							that.flag = true;
						}, 3000)
					})
				} else {
					this.$toolAll.tools.showToast('请不要重复提交！');
				}
			},


			// 发起支付
			callPayMent(data, coding) {
				//调起微信支付
				wx.requestPayment({
					'timeStamp': data.timeStamp,
					'nonceStr': data.nonceStr,
					'package': data.package,
					"signType": data.signType,
					'paySign': data.paySign,
					'success': (res) => { // 接口调用成功的回调函数
						console.log('支付成功:', res);
						// 成功状态
						this.successEv(coding);
					},
					'fail': (res) => { // 接口调用失败的回调函数
						this.$toolAll.tools.showToast('您已取消支付');
						setTimeout(() => {
							// 页面跳转
							uni.navigateTo({
								url: `/pagesA/order/order?index=0`
							})
						}, 1000)
					}
				})
			},

			// 成功状态
			successEv(coding) {
				let params = {
					coding:coding
				}
				postOrderCheck(params).then(res => {
					if (res.code == 0) {

						this.$toolAll.tools.showToast('支付成功');
						setTimeout(() => {
							uni.navigateTo({
								url: '/pagesA/order/order?index=2'
							})
						}, 1000)
					} else {
						this.$toolAll.tools.showToast(res.msg);
					}
				})
			}
		}
	}
</script>
<style scoped>

</style>