<template>
	<view class="content">
		<view class="">
			<u-navbar :isBack="isBack" :title="title"></u-navbar>
		</view>
		<view class="" v-show="!payShow">
			<view class="">
				<view>
					<!-- 地址栏 -->
					<view v-if="takeType==tykeTypeGloabl.delivery" class="bg-white"
						@click="$jump('/pagesD/pages/address/address')">
						<view class="add-address-box u-flex u-flex-1" v-if="$isEmpty(address)">
							<view class="box-bg u-p-30 u-flex-1 u-flex u-row-between">
								<text class="select-notice">请选择收货地址</text>
								<text class="cuIcon-right" style="color: #bfbfbf;"></text>
							</view>
						</view>
						<view class="add-address-box u-p-20" v-else>
							<view class="flex">
								<view class="center  margin-right-20">
									<view class="cuIcon cu-btn round bg-base xl " style="width: 80rpx;height: 80rpx;">
										<text>{{ address.consignee.substring(0,1)}}</text>
									</view>
								</view>

								<view class="" style="width: 90%;">
									<view class="top u-flex">
										<text class="name">{{ address.consignee }}</text>
										<text class="phone">{{ address.phone }}</text>
										<text class="tag" v-show="address.isDefault == 1">默认</text>
									</view>
									<view class="detail u-flex u-row-between" style="width: 100%;">
										<view class="address text-cut-1" style="width: 90%;">
											{{ address.provinceName }}{{ address.cityName }}{{ address.areaName }}{{ address.address }}
										</view>
										<text class="cuIcon-right margin-left-20" style="color: #bfbfbf;"></text>
									</view>
								</view>
							</view>

						</view>
					</view>

					<view class="card" style="justify-content: flex-start;">
						<text class="cuIcon-shop center text-base" style="font-size: 34rpx;"></text>
						<text class="text-lg margin-left-10">{{vuex_orderInfo.store.shopName}}</text>
					</view>
					<view class="card text-df" @click="takeTypeShow=true">
						<text class="text-gray">取餐方式</text>
						<view class="">
							<text>{{takeType}}</text>
							<text class="cuIcon-right"></text>
						</view>
					</view>
					<view v-if="takeType==tykeTypeGloabl.dine_in" class="card text-df">
						<text class="text-gray">取餐时间</text>
						<view class="">
							<text>立即用餐</text>
							<text class="cuIcon-right"></text>
						</view>
					</view>
					<view v-if="takeType==tykeTypeGloabl.package" class="card text-df" @click="timeShow=true">
						<view class="">
							<text class="text-gray">自取时间</text>
							<view class='cu-tag light sm round margin-left-10 bg-orange'>可预约</view>
						</view>
						<view class="">
							<text>{{takeTime?takeTime:'请选择自取时间'}}</text>
							<text class="cuIcon-right"></text>
						</view>
					</view>
					<view v-if="takeType==tykeTypeGloabl.dine_in" class="card text-df center"
						style="padding-top: 15rpx;padding-bottom: 15rpx;">
						<text class="text-gray">取餐座位</text>
						<view class="flex justify-end" style="width: 50%;">
							<text>{{seatNum}}</text>
							<text class="cuIcon-right center"></text>
						</view>
					</view>
					<view v-if="takeType==tykeTypeGloabl.package" class="card text-df" style="border: none;">
						<text class="text-gray">联系电话</text>
						<view class="">
							<text>{{vuex_phone}}</text>
							<text class="cuIcon-right"></text>
						</view>
					</view>
				</view>

				<view style="margin-top: 20rpx;">
					<u-read-more ref="uReadMore" close-text="展开更多" show-height="500" color="#999">
						<view v-for="(item,index) in cart" :key="index" class="cart">
							<view class="flex" style="width: 70%;">
								<image :src="item.image" mode=""></image>
								<view class="item-content">
									<text class="text-cut-1">{{item.name}}</text>
									<text class="text-cut-1">{{item.propertyStr ? item.propertyStr : item.name}}</text>
								</view>
							</view>
							<view class="item-data">
								<view class="">
									<text class="text-sm">x</text>
									<text class="text-lg" style="margin-left: 6rpx;">{{item.number}}</text>
								</view>
								<text class="text-price text-lg">{{item.realPrice / 100}}</text>
							</view>
						</view>
					</u-read-more>
					<!-- 商家配送 -->
					<block v-if="takeType==tykeTypeGloabl.delivery">
						<view class="card text-df">
							<text class="text-gray">包装费</text>
							<text class="text-price">{{vuex_orderInfo.store.packingPrice / 100}}</text>
						</view>
						<view class="card text-df">
							<text class="text-gray">配送费</text>
							<text class="text-price">{{vuex_orderInfo.store.sendingPrice / 100}}</text>
						</view>
					</block>
					<!-- 到店自取 -->
					<block v-if="takeType==tykeTypeGloabl.package">
						<view class="card text-df">
							<text class="text-gray">包装费</text>
							<text class="text-price">{{vuex_orderInfo.store.packingPrice / 100}}</text>
						</view>
					</block>

					<view class="card" style="justify-content: flex-end;flex-direction: column;text-align: right;">
						<view class="">
							<text>总计：</text>
							<text class="text-price text-bold text-xl">{{total / 100}}</text>
						</view>
						<view class="text-base text-sm margin-top-20">
							* 以实际付款为准
						</view>
					</view>
				</view>

				<view class="card margin-top-20">
					<text>备注</text>
					<view style="width: 80%;" class="flex justify-end" @click="goRemark">
						<text class="text-gray" v-if="!remark">点击填写备注</text>
						<text v-else class="text-cut-1 text-gray">{{remark}}</text>
						<text class="cuIcon-right margin-left-10 center"></text>
					</view>
				</view>
				<!-- #ifdef  MP-WEIXIN-->
				<view class="margin-top-20">
					<channel-list></channel-list>
				</view>
				<!-- #endif -->
			</view>

			<!-- 付款栏 begin -->
			<view class="" style="height: 140rpx;"></view>
			<view class="footer-fixed pay-bar" style="z-index: 99;">
				<view class="center" style="justify-content: flex-start;margin-left: 40rpx;">
					<text>总计：</text>
					<text class="text-price text-bold text-xl">{{total / 100}}</text>
				</view>
				<view @click="order" class="bg-base center text-lg" style="width: 25%;">
					付款
				</view>
			</view>
			<!-- 付款栏 end -->


		</view>
		<pay-confirm confirmText="查看订单" cancelText="继续点餐" :type="payConfirmType" v-show="payShow" :info="info"
			@confirm="payConfirm" @cancel="payCancel"></pay-confirm>

		<toast ref="toast"></toast>
		<!-- 取餐方式 -->
		<u-picker @confirm="pickConfirm" confirm-color="#FF9447" :default-selector="defaultSelector" mode="selector" v-model="takeTypeShow"
			:range="takeTypeList"></u-picker>
		<!-- 自取时间 -->
		<h-time-alert title="自取时间" :rangeStartTime="vuex_orderInfo.store.businessStartTime"
			:rangeEndTime="vuex_orderInfo.store.businessEndTime" intervalTime="30" dayStartIntTime="15" rangeDay="1"
			:isNow="true" :isShow="timeShow" @closeAlert="handelClose">
		</h-time-alert>
	</view>
</template>

<script>
	import payConfirm from '@/components/pay-confirm.vue'
	import channelList from '@/components/channel-list.vue'
	import global from "@/assets/http/global.js"
	import hTimeAlert from "../../comps/h-time-alert.vue"
	export default {
		components: {
			payConfirm,
			channelList,
			hTimeAlert
		},
		data() {
			return {
				//navbar
				title: "付款",
				isBack: true,

				shopId: '',
				//购物车
				cartKey: '',
				cart: [],
				//商品备注
				remark: '',
				//商品总数
				totalNum: 0,
				// 座位号
				seatNum: '',
				//取餐方式
				takeType: '',
				tykeTypeGloabl: global.takeType,
				takeTypeList: ['店内堂食', '到店自取'],
				takeTypeShow: false,
				//自取时间
				timeShow: false,
				takeTime: '',
				//配送地址
				address: {},
				//支付参数
				payParams: {},
				successParams: {},
				//支付结果
				payConfirmType: "",
				payResult: {
					isSuccess: false,
					msg: "交易失败",
					//总价
					totalPrice: 0,
					//消耗积分值
					pointsNum: 0,
					//消耗现金值
					amountNum: 0,
				},
				//支付确认
				bills: {},
				payShow: false,
				info: {},
			};
		},
		onLoad() {
			
			this.init()
			uni.$on('REMARK', (remark) => {
				this.remark = remark
			})

			uni.$on('ADDRESS', (address) => {
				console.log(address);
				this.address = address
			})
		},
		computed: {
			total() {
				this.totalNum = 0
				const sum = this.cart.reduce((pre, item) => {
					this.totalNum += item.number
					return pre + item.number * item.realPrice
				}, 0)
				//商家配送
				if (this.takeType == this.$global.takeType.delivery) {
					return sum + (this.vuex_orderInfo.store.packingPrice) +
						(this.vuex_orderInfo.store.sendingPrice)
				}
				//到店自取
				if (this.takeType == this.$global.takeType.package) {
					return sum + (this.vuex_orderInfo.store.packingPrice)
				}
				return sum
			},
			defaultSelector(){
				return 	[this.takeTypeList.indexOf(this.takeType)]
			}
		},
		methods: {
			init() {
				this.seatNum = this.vuex_orderInfo.seatNum
				this.address = this.vuex_orderInfo.address
				this.takeType = this.vuex_orderInfo.takeType
				this.cart = this.vuex_orderInfo.cart
				this.shopId = this.vuex_orderInfo.shopId
				this.cartKey = this.$global.cart_prefix + this.vuex_orderInfo.shopId
			},
			goRemark() {
				uni.navigateTo({
					url: "remark?data=" + this.remark
				})
			},
			pickConfirm(e) {
				let index = e[0]
				let takeType = this.takeTypeList[index]
				if (takeType == this.$global.takeType.delivery && this.total < this.vuex_orderInfo.store
					.sendingNeedLeastPrice) {
					//商家配送,总价格低于配送费
					this.modalShow = true
					return
				}
				this.takeType = takeType
			},
			handelClose(data) {
				this.timeShow = false;
				if (this.$isNotEmpty(data)) {
					this.takeTime = this.$dateTime.format(new Date(data.date))
				}
			},
			async order() {
				let params = {
					receiveId: this.shopId,
					payId: this.vuex_userId,
					takeType: this.takeType,
					goodsPreview: JSON.stringify(this.cart),
					goodsTotalNum: this.totalNum,
					totalPrice: this.total,
					extraInfo: this.remark,
					expireTime: this.$dateTime.getExpireTime(),
					userPhone: this.vuex_phone,
					appId: this.$global.wxParams.APPID,
				}
				if (this.$isNotEmpty(this.vuex_channel)) {
					params.channelId = this.vuex_channel.id
				}

				if (this.takeType == this.$global.takeType.dine_in) {
					//店内堂食
					params.seatNum = this.seatNum
				}
				if (this.takeType == this.$global.takeType.package) {
					//到店自取,包装费
					params.packingPrice = this.vuex_orderInfo.store.packingPrice

					if (this.$isEmpty(this.takeTime)) {
						this.$refs.toast.error('请选择取餐时间')
						return
					} else {
						params.takeTime = this.takeTime
					}
				}

				if (this.takeType == this.$global.takeType.delivery) {
					if (this.$isEmpty(this.address)) {
						this.$refs.toast.error('请选择配送地址')
						return
					}
					//商家配送,包装费,配送费
					params.packingPrice = this.vuex_orderInfo.store.packingPrice
					params.sendingPrice = this.vuex_orderInfo.store.sendingPrice
					params.userPhone = address.phone
					params.receiver = address.consignee
					params.addressDetail = this.address.provinceName + '-' + this.address.cityName + '-' + this.address
						.areaName + ' ' + this.address.address
				}
				let res = await this.$api.goods.order(params)
				this.payParams = res.data
				this.successParams = this.payParams.successParams
				this.bills = this.successParams.bills
				if (this.bills.discount == -1) {
					this.bills.discount = 0
				}
				if (this.successParams.status == '付款成功') {
					this.handelResult(true)
				} else if (this.successParams.status == '待付款') {
					if (this.bills.cost == this.bills.price) {
						this.doWxPay(this.bills.id)
					} else {
						this.info = {
							shop: this.vuex_orderInfo.shopDetail,
							bills: this.bills,
						}
						this.title = "支付确认"
						this.isBack = false
						this.payShow = true
					}
				} else {
					this.handelResult(false)
				}
				uni.hideLoading()
			},
			async doWxPay(orderId) {
				this.$dialog.showLoading('付款中...')
				let obj = {
					orderType: this.$global.orderType.USER_PAY,
					orderId,
					payStatus: this.$global.payStatus.IS_WAIT
				}
				let res = await this.$api.pay.payOrder(obj)
				let prePayTn = JSON.parse(res.data.prePayTn)
				this.$mpi.requestPayment(prePayTn).then(() => {
					this.handelResult(true)
				}).catch(err => {
					this.handelResult(false)
				})
				uni.hideLoading()
			},
			handelResult(flag) {
				if (flag) {
					//跳转到支付页再到订单页
					// this.payResult = {
					// 	goodsBillsId:this.payParams.goodsBills.id,
					// 	isSuccess: true,
					// 	msg: "交易成功",
					// 	totalPrice: this.successParams.totalPrice,
					// 	amountNum: this.successParams.bills.price,
					// 	pointsNum: this.$digital.floatSub(this.successParams.totalPrice, this.successParams.bills
					// 		.price),
					// }
					//本页显示支付结果+抵扣详情
					uni.removeStorageSync(this.cartKey)
					this.info = {
						shop: this.vuex_orderInfo.shopDetail,
						bills: this.bills,
					}
					this.payConfirmType = 'paySuccess'
					this.title = "支付结果"
					this.isBack = false
					this.payShow = true
					return
				}
				this.payResult.msg = '交易失败'
				this.payResult.isSuccess = false
				uni.navigateTo({
					url: "/pagesC/pages/checkstand/pay-result?payResult=" + JSON.stringify(this.payResult)
				})
			},
			viewOrder() {
				uni.reLaunch({
					url: "/pagesD/pages/take-order/take-order?id=" + this.payParams.goodsBills.id
				})
			},
			continueOrdre() {
				let params = {
					shopId: this.shopId,
					seatNum: this.seatNum
				}
				uni.redirectTo({
					url: "/pagesD/pages/menu/menu" + this.$u.queryParams(params)
				})
			},
			payCancel() {
				if (this.payConfirmType == 'paySuccess') {
					this.$back()
					return
				}
				this.title = "收银台"
				this.isBack = true
				this.payShow = false
			},
			payConfirm() {
				if (this.payConfirmType == 'paySuccess') {
					this.viewOrder()
					return
				}
				this.doWxPay(this.bills.id)
			}
		}
	};
</script>

<style lang="scss" scoped>
	.content {
		margin: 20rpx;
	}

	.card {
		padding: 30rpx;
		background-color: #FFFFFF;
		border-bottom: 1rpx solid #f1f1f1;
		display: flex;
		justify-content: space-between;
	}

	.cart {
		border-bottom: 1rpx solid #f1f1f1;
		display: flex;
		background-color: #FFFFFF;
		padding: 15rpx;

		image {
			width: 120rpx;
			height: 120rpx;
		}

		.item-content {
			width: calc(100% - 120rpx - 15rpx);
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			margin-left: 15rpx;

			text:first-child {
				font-size: 32rpx;
				padding-top: 10rpx;
			}

			text:last-child {
				font-size: 26rpx;
				color: #999;
				font-weight: 400;
				padding-bottom: 10rpx;
			}
		}

		.item-data {
			display: flex;
			align-items: center;
			width: 30%;
			justify-content: space-between;
			margin-right: 20rpx;

		}
	}

	.cart:last-child {
		border: none;
	}

	.pay-bar {
		height: 110rpx;
		background-color: #FFFFFF;
		display: flex;
		justify-content: space-between;
	}


	.add-address-box {
		min-height: 100rpx;
		background: url('http://file.shopro.top/imgs/order/order_address_line.png') no-repeat;
		background-size: 100% auto;
		background-position: bottom center;

		.select-notice {
			font-weight: 400;
			color: rgba(153, 153, 153, 1);
			line-height: 40rpx;
		}

		.name,
		.phone {
			font-size: 30rpx;
			font-weight: 500;
		}

		.phone {
			margin: 0 20rpx;
		}

		.tag {
			background: rgba(233, 191, 113, 0.2);
			border-radius: 6rpx;
			padding: 0 16rpx;
			line-height: 38rpx;
			color: #a8700d;
			font-size: 22rpx;
		}

		.detail {
			.address {
				margin-top: 25rpx;
				width: 543rpx;
				font-size: 26rpx;

				font-weight: 400;
				color: rgba(153, 153, 153, 1);
				line-height: 40rpx;
			}
		}
	}
</style>
