<template>
	<view class="container">
		<view v-if="!isWeixin" class="v-navbar">
			<u-navbar title="提货付款" :safeAreaInsetTop="false" :fixed="false" @leftClick="leftClick" bgColor="transparent"
				leftIconColor="#fff" :titleStyle="{color:'#fff',fontWeight:'bold',fontSize:'32rpx'}">
			</u-navbar>
		</view>
    <view style="height: 150rpx;"></view>
		<view v-if="merchantInfo && !isEmpty">
			<view class="v-desc">
				<view>
					<view class="v-desc-main">确认提货付款</view>
					<view class="v-desc-sub">{{merchantInfo.merchant.mer_name}}</view>
				</view>
				<u-image :showLoading="true" :src="merchantInfo.merchant.mer_avatar" width="182rpx" height="182rpx"
					:radius="10" />
			</view>

			<!-- 付款金额 -->
			<view class="v-con">
				<view class="v-con-text">付款金额</view>
				<view class="v-con-input" style="margin-right: 10px;">
					<text style="color: #303133;font-size:46rpx;">￥</text>
					<u--input type="digit" fontSize="23" v-model="cartForm.total_amount" placeholder="请输入金额"
						border="none" placeholderStyle="color:#999;font-size:30rpx" @input="validateDecimal">
					</u--input>
				</view>

				<view class="v-wrap" v-if="cartForm.total_amount">
					<view class="v-wrap-money">
						<text class="icon">￥</text>
						<text class="num">{{cartForm.total_amount}}</text>
					</view>
					<view class="v-wrap-desc">
						<view class="v-wrap-desc-main">实物提货券</view>
						<view class="v-wrap-desc-sub">即买即用</view>
					</view>
				</view>
			</view>

			<view class="v-btn-wrap">
				<view class="v-btn" @click="submitOrder">提交订单</view>
			</view>

			<!-- 登陆 -->
			<authorize :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse" @onLoadFun="onLoadFun">
			</authorize>
		</view>

		<!-- 无商户信息提示 -->
		<view v-else class="empty">
			<image src="/static/images/no_thing.png"></image>
			<text style="margin-top: 60rpx;">{{tips}}</text>
			<!-- 登陆 -->
			<authorize ref="authRef" :isAuto="isAuto" :isGoIndex="false" :isShowAuth="isShowAuth" @authColse="authColse"
				@onLoadFun="onLoadFun" :isPay="true">
			</authorize>
		</view>
	</view>
</template>

<script>
	import {
		getProductInfo,
		addCart,
		orderCheck
	} from "@/api/payment.js";
	import Cache from '@/utils/cache';
	import {
		mapGetters
	} from "vuex";
	import authorize from '@/components/Authorize';
  import { Toast } from "../../libs/uniApi";
	export default {
		components: {
			authorize
		},
		computed: {
			...mapGetters(['isLogin']),
		},
		data() {
			return {
				isEmpty: false,
        isWeixin: this.$wechat.isWeixin(),
				cartForm: {
					product_id: '',
					product_attr_unique: '',
					cart_num: 1,
					is_new: 1,
					product_type: 0,
					source: 999,
					total_amount: ''
				},
				merchantInfo: '',
        mer_name: '',
				checkForm: {
					address_id: '',
					cart_id: [],
					consumption_id: '',
					product_type: 0,
					source: 999,
					takes: [],
					use_coupon: {},
					use_integral: false
				},
				isAuto: false, //没有授权的不会自动授权
				isShowAuth: false, //是否隐藏授权
				mer_id: '',
				tips: '暂未登陆~'
			}
		},

		onLoad(opt) {
			this.mer_id = opt.mer_id;
		},
		onShow() {
			if (!this.isLogin) {
        Cache.set("login_back_url_weixin", "/" + getCurrentPages()[0].route + "?mer_id=" + this.mer_id);
        this.isAuto = true;
        this.isShowAuth = true;
			}
      this.checkForm.cart_id = [];
      this.getProductInfoByMerid(this.mer_id);
		},
		methods: {
			validateDecimal(event) {
				let val = (this.cartForm.total_amount.match(/^\d*(\.?\d{0,2})/g)[0]) || ''
				this.$nextTick(() => {
					this.cartForm.total_amount = val;
				})
			},

			leftClick(e) {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			// 授权关闭
			authColse: function(e) {
				this.isShowAuth = e;
			},
			onLoadFun() {
				this.getProductInfoByMerid(this.mer_id);
				this.isShowAuth = false;
			},

			// 提交订单
			submitOrder() {
				if (!this.cartForm.total_amount) {
					return this.$util.Tips({
						title: "请输入付款金额！"
					})
				}
				// 订单
				this.cartForm.product_id = this.merchantInfo.product_id;
				this.cartForm.product_type = this.merchantInfo.product_type;
				this.cartForm.product_attr_unique = this.merchantInfo.sku[''].unique;

				let that = this;
				addCart(this.cartForm).then(res => {
					// 购物车ID
					that.checkForm.cart_id.push(res.data.cart_id);
					orderCheck(that.checkForm).then(res1 => {
						uni.navigateTo({
							url: "/pages/payment/settlement?cartId=" + this.checkForm
								.cart_id + "&money=" + this.cartForm.total_amount +
								"&merName=" + this.merchantInfo.merchant.mer_name,
							success: (res) => {
								res.eventChannel.emit('datas', res1.data.platformConsumption);
							}
						})
					}).catch(err=>{
            Toast(err.message || err)
          });
				}).catch((err) => {
					this.$util.Tips({
						title: err.message || err.msg || err
					})
				})
			},

			getProductInfoByMerid(merid) {
				let that = this;
				getProductInfo({
					mer_id: merid
				}).then(res => {
          this.merchantInfo = res.data;
          let mer_name = '';
          if(this.merchantInfo.merchant&&this.merchantInfo.merchant.mer_name) mer_name = this.merchantInfo.merchant.mer_name || '';
          this.$nextTick(()=>{
            this.$refs.authRef.setPayInfo(mer_name);
          })
				}).catch((err) => {
					this.tips = err.message || err.smg || err;
					this.$util.Tips({
						title: err.message || err.msg || err
					})
          this.$nextTick(()=>{
            this.$refs.authRef.setPayInfo('');
          })
					// #ifdef APP
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 1500)
					// #endif

					// #ifndef APP
					that.isEmpty = true;
					// #endif
				})
			},

			// 图片保存
			handleSavePic() {
				// 获取要保存的图片路径或URL
				let imageUrl = this.qrcodeUrl; // 这里使用了网络上的图片作为示例

				// #ifdef H5
				var a = document.createElement("a");
				a.download = imageUrl;
				a.href = imageUrl;
				document.body.appendChild(a);
				a.click();
				a.remove();
				// #endif

				// #ifndef H5
				let that = this;
				uni.downloadFile({
					url: imageUrl,
					success(res) {
						if (res.statusCode === 200) {
							let tempFilePath = res.tempFilePath; // 临时文件路径
							uni.saveImageToPhotosAlbum({
								filePath: tempFilePath,
								success() {
									return that.$util.Tips({
										title: '图片已保存至相册!'
									});
								},
								fail(err) {
									console.error('保存失败', err);
								}
							});
						} else {
							console.error('下载失败', res.statusCode);
						}
					},
					fail(err) {
						console.error('下载失败', err);
					}
				});
				// #endif
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #FCDFAD;
	}

	.empty {
		margin: 0;
		text-align: center;

		image,
		uni-image {
			display: inline-block;
			width: 414rpx;
			height: 305rpx;
		}

		text {
			display: block;
			color: #666;
			font-size: 26rpx;
		}
	}

	.container {
		position: relative;
		height: 100vh;
		background-image: url("https://lihai001.oss-cn-chengdu.aliyuncs.com/def/c582c202402291601584806.webp");
		background-size: 100% auto;
		background-repeat: no-repeat;
		padding-top: var(--status-bar-height);

		.v-desc {
			position: absolute;
			top: 196rpx;
			z-index: 10;
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			padding: 0 20rpx;
			background: transparent;

			.v-desc-main {
				margin-bottom: 30rpx;
				font-weight: 600;
				font-size: 42rpx;
				color: #FFFFFF;
			}

			.v-desc-sub {
				font-weight: 500;
				font-size: 24rpx;
				color: #FFFFFF;
			}
		}

		.v-con {
			position: absolute;
			top: 436rpx;
			left: 50%;
			transform: translateX(-50%);
			width: 710rpx;
			height: 680rpx;
			background: linear-gradient(180deg, #FEB992 0%, #FFFFFF 31%, #FFFFFF 100%);
			border-radius: 20rpx;
			margin: 0 auto;
			box-shadow: 0 -4rpx 0px 0px #fff;
			padding: 53rpx 30rpx 0 30rpx;
			box-sizing: border-box;

			.v-con-text {
				margin-bottom: 60rpx;
				font-weight: 400;
				font-size: 32rpx;
				color: #2E2E2E;
				line-height: 16rpx;
			}

			.v-con-input {
				display: flex;
				align-items: center;
				margin-bottom: 83rpx;
				padding: 0 0 40rpx 12rpx;
				border-bottom: 1rpx solid #D6D6D6;
			}

			.v-wrap {
				display: flex;
				align-items: center;
				padding-left: 20rpx;
				width: 666rpx;
				height: 210rpx;
				background-image: url("https://lihai001.oss-cn-chengdu.aliyuncs.com/def/2f9c2202402291652415355.webp");
				background-size: 100% 100%;
				background-repeat: no-repeat;

				.v-wrap-money {
					display: flex;
					align-items: center;
					color: #FF5E0C;
					margin-right: 30rpx;

					.icon {
						font-size: 34rpx;
					}

					.num {
						font-size: 46rpx;
						display: inline-block;
						overflow: auto;
						width: 180rpx;
					}
				}

				.v-wrap-desc {
					.v-wrap-desc-main {
						margin-bottom: 16rpx;
						font-weight: 600;
						font-size: 32rpx;
						color: #2E2E2E;
					}

					.v-wrap-desc-sub {
						font-weight: 400;
						font-size: 24rpx;
						color: #2E2E2E;
					}
				}
			}
		}

		.v-btn-wrap {
			position: fixed;
			z-index: 11;
			bottom: 0;
			left: 0;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 100%;
			height: 240rpx;
			background-color: #FDD6A6;

			.v-btn {
				width: 650rpx;
				height: 100rpx;
				line-height: 100rpx;
				background: #FF8056;
				box-shadow: 0rpx 3rpx 3rpx 1rpx rgba(255, 94, 12, 0.4);
				border-radius: 55rpx 55rpx 55rpx 55rpx;
				border: 1rpx solid #FF8056;
				font-weight: 600;
				font-size: 32rpx;
				color: #FFFFFF;
				text-align: center;

				&:active {
					opacity: .8;
				}
			}
		}
	}
</style>