<template>
	<view class="cu-modal bottom-modal" :class="{ show: visible }">
		<view class="mask" @click="close"></view>
		<view class="wrapper cu-dialog">
			<view class="paddingY25 flex-align-center relative">
				<image :src="resource.pay_title_dart" class="title" />
				<image :src="resource.icon_x" class="x" @click="close" />
			</view>
			<view>
				<view class="flex-align paddingB25">
					<image :src="data.cover" class="logo flex-shrink0 flex-shrink0" />
					<view class="marginL12 flex1 self-stretch flex-column-between">
						<view class="top">
							<text class="text">{{ data.name }}</text>
							<view v-if="data.sellType === 2" class="sale-pre">预售订单</view>
						</view>
						<view class="color-theme flex-align-between" style="height: 140rpx">
							<view class="flex-column-between">
								<view>
									<view class="bottom">
										<view class="price">
											¥
											<text class="price-num">
												{{
                                                  data.subjectPrice
                                                      ? data.subjectPrice
                                                      : data.price
                                              }}
											</text>
										</view>
										<view v-if="data.sellType === 2" class="deposit">
											定金：¥{{ data.deposit }}
										</view>
									</view>
								</view>
							</view>
							<view class="counter">
								<view class="counter-top">
									<view class="reduce" @click="decrement">
										<image class="reduce-img" :src="resource.reduce" />
									</view>
									<view class="number">{{ total }}</view>
									<view class="add" :class="subjectId ? 'spike_hiddren' : ''" @click="increment">
										<image class="add-img" :src="resource.add" />
									</view>
								</view>
								<view class="total">
									共
									<text class="text">{{ total }}</text>
									个
								</view>
							</view>
						</view>
						<!-- <view class="color-theme font2 line-ellipsis">含预售商品，先到货先发</view> -->
					</view>
				</view>
				<view class="flex-align paddingY15" style="border-top: 2rpx solid #eeeeee">
					<view class="flex1 font4 color-1">快递费</view>
					<view class="font2 color-theme marginR5">¥{{ expressAmount || 0 }}</view>
				</view>
				<view class="flex-align paddingY15" style="border-top: 2rpx solid #eeeeee">
					<view class="flex1 font4 color-1">优惠券</view>
					<view class="font2 color-theme marginR5">-¥{{ couponAmount || 0 }}</view>
				</view>
				<view v-if="cash && hide" class="flex-align paddingY15"
					style="border-top: 2rpx solid #eeeeee; border-bottom: 2rpx solid #eeeeee">
					<view class="flex1 font4 color-1">
						使用钱包支付
						<text class="color-theme">(余额：¥{{ cash.balance }})</text>
					</view>
					<switch class="purple" :checked="cashChecked" @change="changeCashChecked"></switch>
				</view>
				<view v-if="data.sellType === 2"
					class="deposit-phone bgcolor-white radius12 flex-align-between paddingY15">
					<text class="text">
						<text style="color: #dd524d; font-size: 35rpx">*</text>
						尾款提醒手机号
					</text>
					<input class="phone" style="width: 400rpx" v-model.trim="phone" type="text"
						placeholder="尾款支付提醒短信将发至此号码" placeholder-style="color: #ccc" />
				</view>
				<view class="flex-align-between paddingY25 color-1"
					style="border-top: 2rpx solid #eeeeee; border-bottom: 2rpx solid #eeeeee"
					@click="$router.push('address', { type: 1 })">
					<text v-if="!address" class="font-8">
						<text style="color: #dd524d; font-size: 35rpx">*</text>
						请填写收货地址
					</text>
					<view v-else>
						<view class="font4">{{ address.contactName }} {{ address.contactNo }}</view>
						<view class="font3">
							{{ address.province }}{{ address.city }}{{ address.district
                          }}{{ address.address }}
						</view>
					</view>
					<text class="cuIcon-right color-2 font4 marginL5"></text>
				</view>
				<view class="paddingY25 flex-align-between">
					<view>
						<view class="font4 color-1 flex-align" @click="showWeb">
							同意《会员购服务协议》详情
							<text class="cuIcon-right color-2 font2 marginL5"></text>
						</view>
					</view>
					<switch class="purple" :checked="checked" @change="changeChecked"></switch>
				</view>
			</view>
			<cm-button ::height="44" @click="pay">¥{{ lastPrice }} 立即支付</cm-button>
			<view class="fill"></view>
		</view>
	</view>
</template>

<script>
	import cmButton from '../../components/cm-button.vue'
	import {
		throttle
	} from '@/utils'
	import {
		H5
	} from '@/utils/config'
	import resource from '@/utils/resource'
	import {
		baseEncode
	} from '../../utils/utils'
	export default {
		components: {
			cmButton
		},
		props: {
			data: Object,
			goodsId: String,
			subjectId: String
		},
		data() {
			return {
				resource,
				visible: false,
				checked: true,
				address: null,
				expressAmount: null,
				couponAmount: null,
				cash: null,
				cashChecked: false,
				lastPrice: null, //最终金额
				count: 1,
				maxCount: 5,
				unitPrice: 1,
				phone: ''
			}
		},

		mounted() {
			this.$event.on(this.$event.key.ADDRESS_SET, (data) => {
				this.address = data
			})
		},
		beforeDestroy() {
			this.$event.off(this.$event.key.ADDRESS_SET)
		},
		computed: {
			total() {
				return this.count * this.unitPrice
			},
			hide() {
				return !this.$store.state.hide
			},
			payInfo() {
				return this.$store.state.payInfo
			}
		},
		watch: {
			payInfo(val) {
				if (val && val.payResult == 'SUCCESS') {
					this.paySuccess(val)
				} else if (val && val.payResult !== 'SUCCESS') {}
			}
		},
		methods: {
			async getAddress() {
				const res = await this.$service.address.default()
				this.address = res
			},
			show(data = {}) {
				this.expressAmount = data.expressAmount || null
				this.couponAmount = data.couponAmount || null
				this.lastPrice = data.type === 1 ? data.paymentAmount : data.depositAmount
				if (data.cash && data.cash.balance > data.paymentAmount) {
					this.cash = data.cash
					this.cashChecked = true
				} else {
					this.cash = null
					this.cashChecked = false
				}
				this.visible = true
				this.getAddress()
			},
			close() {
				this.visible = false
			},
			changeCashChecked(e) {
				this.cashChecked = e.detail.value
			},
			changeChecked(e) {
				this.checked = e.detail.value
			},
			async pay() {
				if (!this.address) {
					this.$message.warn('请选择地址')
					return
				}
				if (!this.phone && this.data.sellType === 2) {
					this.$message.warn('请填写尾款提醒手机号')
					return
				}
				console.log(this.checked)
				if (!this.checked) {
					this.$message.warn('请勾选协议')
					return
				}
				this.realPay()
			},
			async realPay() {
				// let paymentType = this.cashChecked ? 'WALLET' : 'WXPAY_JSAPI'
				let self = this
				const res = await this.$service.mall.apply({
					goodsId: this.data.id,
					paymentType: 'ALIPAY_APP',
					addressBookId: this.address.id,
					quantity: this.total,
					restNotifyMobile: this.phone,
					subjectId: this.subjectId
				})
				//判断是否是微信支付
				
				console.log(res)
				if (res) {
					if (res.paySuccess) {
						this.close()
						this.$router.push('order_product')
						return
					}
					// 支付宝支付
					uni.requestPayment({
						provider: 'alipay',
						orderInfo: res.payInfo,
						success: function(res) {
							self.close()
							self.$router.push('order_product')
							self.$store.state.payInfo = null
						},
						fail: function(err) {
							console.log('fail:' + JSON.stringify(err));
						}
					});
					// if(res.redirectUrl){
					//   this.thirdPay(res)
					// }else{
					//   this.wechatPay(res)
					// }
					return
				}
			},
			wechatPay(data) {
				let payInfo = data.payInfo
				wx.requestPayment({
					timeStamp: payInfo.timeStamp,
					nonceStr: payInfo.nonceStr,
					package: payInfo.packageValue,
					signType: payInfo.signType,
					paySign: payInfo.paySign,
					success: (res) => {
						this.close()
						this.$router.push('order_product')
						this.$store.state.payInfo = null
					},
					fail: (res) => {}
				})
			},
			thirdPay(res) {
				let redirectUrl = res.redirectUrl
				let requestId = res.requestId
				const base64Url = encodeURIComponent(baseEncode(redirectUrl))
				wx.openEmbeddedMiniProgram({
					path: 'pages/pay/order', // 启动目标页面
					appId: 'wx0448557563ffc600', // 启动的小程序
					envVersion: 'release', // develop | trial | release
					verify: 'binding',
					extraData: {
						title: '订单支付', // 导航Title
						tip: `待支付订单支付`, // 支付提示内容
						requestId: requestId, // 本次请求ID
						action: 'epPay', // 支付模式
						payUrl: base64Url // 支付地址, 需要进行Base64转换
					},
					success: (res) => {
						console.info('启动成功', res)
					},
					fail: (err) => {
						console.info('启动失败', err)
					}
				})

			},
			paySuccess(payInfo) {
				this.close()
				this.$router.push('order_product')
				this.$store.state.payInfo = null
			},
			showWeb() {
				this.$router.web(H5.mall.url, H5.mall.title)
			},
			async getDetail() {
				const res = await this.$service.mall.previewSubmit({
					goodsId: this.goodsId,
					quantity: this.total
				})
				this.show(res)
			},
			increment() {
				if (this.subjectId) return
				if (this.count >= this.maxCount) {
					return
				}
				this.count += 1
				this.getDetail()
			},
			decrement() {
				if (this.count <= 1) {
					return
				}
				this.count -= 1
				this.getDetail()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.mask {
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
	}

	.wrapper {
		padding: 0 28rpx;
		background: #fff;
		overflow: hidden;
		border-top-left-radius: 30rpx !important;
		border-top-right-radius: 30rpx !important;

		.title {
			width: 172rpx;
			height: 28rpx;
		}

		.x {
			position: absolute;
			right: 28rpx;
			top: 50%;
			margin-top: -16rpx;
			width: 32rpx;
			height: 32rpx;
		}

		.logo {
			width: 180rpx;
			height: 180rpx;
			border-radius: 8rpx;
		}

		.fill {
			height: env(safe-area-inset-bottom);
		}

		.top {
			display: flex;

			.text {
				font-size: 28rpx;
				width: 323rpx;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}

			.sale-pre {
				color: #fff;
				font-size: 24rpx;
				font-weight: 400;
				width: 128rpx;
				height: 44rpx;
				background: $color-theme;
				border-radius: 32rpx;
				text-align: center;
				line-height: 44rpx;
			}
		}

		.bottom {
			display: flex;

			.price {
				color: $color-theme;
				font-size: 22rpx;
				margin-right: 12rpx;

				.price-num {
					font-size: 32rpx;
				}
			}

			.deposit {
				color: #fff;
				font-size: 24rpx;
				font-weight: 400;
				width: 157rpx;
				height: 40rpx;
				background: linear-gradient(270deg, #d070ff 0%, #8b3dff 100%);
				border-radius: 32rpx;
				text-align: center;
				line-height: 40rpx;
			}
		}

		.counter {
			display: flex;
			flex-direction: column;
			width: 190rpx;
			height: 80rpx;

			.counter-top {
				display: flex;
				vertical-align: middle;

				.reduce {
					.reduce-img {
						width: 48rpx;
						height: 48rpx;
					}
				}

				.number {
					color: #000;
					height: 45rpx;
					margin: 0 32rpx;
					line-height: 45rpx;
				}

				.add {
					.add-img {
						width: 48rpx;
						height: 48rpx;
					}
				}

				.spike_hiddren {
					opacity: 0.3;
				}
			}

			.total {
				margin-top: 18rpx;
				text-align: end;
				margin-right: 20rpx;
				font-size: 26rpx;

				.text {
					margin: 0 5rpx;
					color: #ff8040;
				}
			}
		}
	}
</style>