<!-- 订单确认页 -->
<template>
	<view class="order_confirm" :style="{ background: 'url(' + bgImg + ') #F4F5F9' }">
		<view class="all">
			<view class="title">您选择的{{ setData.packageName }}</view>
			<view class="menu">
				<view class="amounts flex jcsb">
					<view class="amontl">
						<view class="now flex aife">
							<text class="dw fs40">¥</text>
							<text class="num">{{ setData.currentPrice }}</text>
							<text class="unit">/条</text>
						</view>
						<view class="past flex aic">
							<text class="past_text fs28">原价</text>
							<text class="past_num fs32">¥{{ setData.originalPrice }}/条</text>
						</view>
					</view>
					<view class="amontr">
						<text class="num">{{ strip }}</text>
						<text class="unit">条</text>
					</view>
				</view>
				<view class="choose">
					<view v-for="(item, index) in setData.selectContents" :key="index"
						class="choose_item-box flex aic jcsb">
						<view class="choose_item flex aic">
							<image :src="guoxuanImg"></image>
							<text>{{ item.configKey }}可选 {{ item.count || 0 }} 个</text>
						</view>
						<!-- <view v-if="index == 0" class="choose_item-more flex aic" @click="toDetail">
							<text>查看更多</text>
							<image :src="moreBImg"></image>
						</view> -->
					</view>
				</view>
			</view>
			<view class="choosion">
				<view class="name">选择内容</view>
				<view class="content">
					<view v-for="(item, index) in orderContents" :key="index" class="content_item flex aic jcsb"
						@click="chooseScene(item, index)">
						<view class="aic flex">
							<view class="item_label">{{ item.name }}</view>
							<view v-if="item.scenes.length > 0" class="item_num">{{ item.scenes.join('; ') }}</view>
							<view v-else class="item_text">{{ setData.packageName }}可选 {{ item.count || 0 }} 个{{
								item.name
							}}
							</view>
						</view>
						<image class="more_img" :src="moreImg"></image>
					</view>
				</view>
			</view>
			<view class="choosion">
				<view class="name">支付方式</view>
				<view class="content">
					<view class="content_item flex aic jcsb">
						<view class="aic flex">
							<image class="icon_img" :src="weixinImg"></image>
							<view class="item_name">微信支付</view>
						</view>
						<image class="icon_img" :src="guoyuanImg"></image>
					</view>
				</view>
			</view>
			<view class="choosion">
				<view class="name">接收人信息</view>
				<view class="content">
					<view class="content_item flex aic jcsb">
						<view class="aic flex">
							<view class="item_label">接收人</view>
							<u--input v-model="formData.recipientName" placeholder="输入收件人姓名" fontSize="14"
								:customStyle="{ 'margin-left': '48rpx', 'padding': 0 }"></u--input>
						</view>
					</view>
					<view class="content_item flex aic jcsb">
						<view class="aic flex">
							<view class="item_label">联系电话</view>
							<u--input v-model="formData.contactPhone" placeholder="输入手机号码" fontSize="14"
								:customStyle="{ 'margin-left': '48rpx', 'padding': 0 }"></u--input>
						</view>
					</view>
					<view class="content_item flex aic jcsb">
						<view class="aic flex">
							<view class="item_label">邮箱地址</view>
							<u--input v-model="formData.email" placeholder="输入邮箱地址" fontSize="14"
								:customStyle="{ 'margin-left': '48rpx', 'padding': 0 }"></u--input>
						</view>
					</view>
				</view>
			</view>
			<view class="choosion">
				<view class="name">需求相关</view>
				<view class="content">
					<view class="content_item flex aic jcsb">
						<view class="flex">
							<view class="item_label">参考案例</view>
							<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
								:maxCount="5" accept="video">
								<view class="item_updata">
									<image :src="upImg"></image>
									<text>上传案例</text>
								</view>
							</u-upload>
						</view>
					</view>
					<view class="content_item flex aic jcsb">
						<view class="flex w100">
							<view class="item_label pt18">拍摄需求</view>
							<u--textarea v-model="formData.shootingRequirements" placeholder="简单描述您的拍摄需求" count
								maxlength="200"></u--textarea>
						</view>
					</view>
				</view>
			</view>
			<view class="agree">
				<!-- <text>点击“确认支付”，即代表您已阅读并同意</text>
				<text class="agree_text">《用户购买协议》</text> -->
			</view>
		</view>
		<view class="btom">
			<view class="sum">
				<text>应付款：</text>
				<text class="money">
					<text class="unit">¥</text>
					{{ numMultiR }}
				</text>
			</view>
			<view class="btn" :style="{ background: 'url(' + buybtnBg + ')' }" @click="submitOrder">立即购买</view>
		</view>
		<u-popup ref="uPicker" mode="bottom" :loading="loading" :show="isSelect" round="12" @close="close"
			:customStyle="{ height: '100px' }">
			<view class="popup_content safe-area-inset-bottom">
				<view class="checkbox">
					<u-checkbox-group v-model="checked" placement="column" iconPlacement="right"
						@change="checkboxChange">
						<u-checkbox v-for="(item, index) in configData" :key="index" :label="item" :name="item"
							:customStyle="{ marginBottom: '24px' }" :disabled="isDisabled(item)"></u-checkbox>
					</u-checkbox-group>
				</view>
				<view class="btns flex aic jcsb">
					<view class="cancel" @click="close">取消</view>
					<view class="confirm" @click="confirm">确认</view>
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
import {
	getPackageById,
	getConfigById,
	upload,
	save
} from '@/apis/index';
import {
	baseUrl
} from "@/config"
import {
	numMulti
} from '@/utils/calculate'
import wx from 'jweixin-module';
import {
	getWxBuyConfig,
	submitOrder
} from "../../apis";

export default {
	components: {},
	data() {
		return {
			type: '',
			fileList1: [],
			count: '', //可选数量
			strip: '', //条数
			packageId: '', //套餐id
			setData: {}, // 套餐数据
			configData: [], //选择内容数据
			loading: false,
			isSelect: false,
			name: '',
			phone: '',
			checked: [], //多选
			orderContents: [], //选中后的内容
			configKey: '', //内容标题
			bgImg: "https://ovp-shop.oss-cn-hangzhou.aliyuncs.com/static/9dshop/bg_top%403x.png",
			guoxuanImg: 'https://ovp-shop.oss-cn-hangzhou.aliyuncs.com/static/9dshop/ic_guoxuan.png',
			guoyuanImg: 'https://ovp-shop.oss-cn-hangzhou.aliyuncs.com/static/9dshop/ic_guoxuanyuan.png',
			moreBImg: 'https://ovp-shop.oss-cn-hangzhou.aliyuncs.com/static/9dshop/ic_more_black.png',
			moreImg: 'https://ovp-shop.oss-cn-hangzhou.aliyuncs.com/static/9dshop/ic_more%403x.png',
			weixinImg: 'https://ovp-shop.oss-cn-hangzhou.aliyuncs.com/static/9dshop/ic_weixinzhifu.png',
			upImg: 'https://ovp-shop.oss-cn-hangzhou.aliyuncs.com/static/9dshop/ic_up.png',
			buybtnBg: 'https://ovp-shop.oss-cn-hangzhou.aliyuncs.com/static/9dshop/ic_buy.png',
			formData: {
				recipientName: '',
				contactPhone: '',
				email: '',
				shootingRequirements: '',
			}
		};
	},
	computed: {
		numMultiR() {
			return numMulti(Number(this.setData.currentPrice), Number(this.strip))
		}
	},
	watch: {},
	onLoad(options) {
		if (options.id) this.packageId = options.id
		if (options.strip) this.strip = options.strip
		if (options.type) this.type = options.type
		this.getPackage()
	},
	methods: {
		toDetail() {
			uni.navigateTo({
				url: '/pages/index/detail?type=' + this.type
			})
		},
		// 判断当前选项是否应该禁用
		isDisabled(value) {
			// 已选中6个且当前选项未被选中时禁用
			return this.checked.length >= this.count &&
				!this.checked.includes(value)
		},

		// 选择变化时的处理
		checkboxChange(values) {
			if (values.length > this.count) {
				// 如果超过6个，自动截断并提示
				this.checked = values.slice(0, thsi.count);
				uni.showToast({
					title: '最多只能选择6个选项',
					icon: 'none'
				});
			}
		},

		// 获取套餐内容
		getPackage() {
			getPackageById({
				packageId: this.packageId
			}).then(res => {
				this.setData = res
				this.orderContents = res.selectContents.map(item => {
					return {
						name: item.configKey,
						configId: item.configId,
						count: item.count,
						scenes: []
					}
				})
				console.log('orderContents', this.orderContents);
			})
		},
		// 选择内容
		chooseScene(item, index) {
			if (!item.count) {
				uni.showToast({
					title: '无可选内容',
					icon: 'none'
				});
				return
			}
			this.loading = true
			getConfigById({
				packageId: this.packageId,
				configId: item.configId
			}).then(res => {
				this.loading = false
				this.count = item.count
				console.log(this.checked, this.count, '数量');
				this.configData = res
				this.configKey = item.name
				this.orderContents.map(itm => {
					if (itm.name === this.configKey && itm.scenes.length !== 0) {
						this.checked = itm.scenes
					}
				})
				this.isSelect = true

			})
		},
		confirm() {
			if (this.checked.length < this.count) {
				uni.showToast({
					title: '至少选择' + this.count + '个选项',
					icon: 'none',
				});
				return
			}
			this.orderContents.map(item => {
				if (item.name === this.configKey) {
					item.scenes = this.checked
				}
			})
			this.checked = []
			this.isSelect = false

		},
		close() {
			this.isSelect = false
			this.checked = []
		},

		// 删除图片
		deletePic(event) {
			this[`fileList${event.name}`].splice(event.index, 1);
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式

			let lists = [].concat(event.file);
			let fileListLen = this[`fileList${event.name}`].length;
			lists.map((item) => {
				this[`fileList${event.name}`].push({
					...item,
					status: "uploading",
					message: "上传中",
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url);
				let item = this[`fileList${event.name}`][fileListLen];
				this[`fileList${event.name}`].splice(
					fileListLen,
					1,
					Object.assign({
						// status: "success",
						// message: "",
						url: result,
					})
				);
				fileListLen++;
			}
		},
		uploadFilePromise(url) {
			console.log(url, upload, 'url');
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: baseUrl + '/sys/oss/upload', // 仅为示例，非真实的接口地址
					filePath: url,
					name: "file",
					formData: {
						user: "test",
					},
					success: (res) => {
						let data = JSON.parse(res.data);
						setTimeout(() => {
							resolve(data.data.src);
						}, 1000);
					},
					fail: (err) => {
						console.log(err, 'err');
						reject(err);
					},
				});
			});
		},

		// 校验选择内容
		checkContents() {

			for (const item of this.orderContents) {
				if (!item.scenes || item.scenes.length === 0) {
					uni.showToast({
						title: `请选择${item.name}`,
						icon: 'none',
						duration: 2000
					});
					return false; // 校验失败
				}
			}
			return true; // 校验成功
		},

		// 校验表单
		checkForm() {
			if (this.formData.recipientName === '' || this.formData.contactPhone === '' || this.formData.email ===
				'') {

				if (this.formData.recipientName === '') {
					uni.showToast({
						title: '请填写接收人姓名',
						icon: 'none',
					});
					return
				}
				if (!/^1[3-9]\d{9}$/.test(this.formData.contactPhone)) {
					uni.showToast({
						title: '请填写正确的手机号码',
						icon: 'none',
					});
					return
				}
				if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(this.formData.email)) {
					uni.showToast({
						title: '请填写正确的邮箱',
						icon: 'none',
					});
					return
				}
				// uni.showToast({
				// 	title: '请填写完整收件方式',
				// 	icon: 'none',
				// });
				return false
			}
			return true; // 校验成功

		},

		invokePayment(rePayInfo) {
			WeixinJSBridge.invoke(
				'getBrandWCPayRequest', {
				appId: rePayInfo.appid,
				timeStamp: rePayInfo.timeStamp,
				nonceStr: rePayInfo.nonceStr,
				package: rePayInfo.packages,
				signType: rePayInfo.signType,
				paySign: rePayInfo.sign
			},
				(res) => {
					if (res.err_msg === 'get_brand_wcpay_request:ok') {
						uni.navigateTo({
							url: '/pages/order/success?orderId=' + rePayInfo.orderId
						})
					} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
						uni.showToast({
							title: '用户取消了支付',
							icon: 'none'
						})
					} else {
						console.error('支付失败', res.err_msg);
						// 处理支付失败的逻辑
					}
				}
			);
		},

		// 提交订单
		submitOrder() {
			if (!this.checkForm()) {
				return; // 如果校验失败，停止提交
			}

			if (!this.checkContents()) {
				return; // 如果校验失败，停止提交
			}

			let params = {
				packageId: Number(this.packageId),
				quantity: this.strip,
				unitPrice: this.setData.currentPrice,
				totalAmount: this.numMultiR,
				packageName: this.setData.packageName,
				...this.formData,
				caseFileUrls: this.fileList1.map(item => {
					return item.url
				}),
				orderContents: this.orderContents,
			}

			submitOrder({
				...params
			}).then((res) => {
				// 检查是否在微信浏览器中
				if (typeof WeixinJSBridge === 'undefined') {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', () => {
							this.invokePayment(res);
						}, false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', () => {
							this.invokePayment(res);
						});
						document.attachEvent('onWeixinJSBridgeReady', () => {
							this.invokePayment(res);
						});
					}
				} else {
					this.invokePayment(res);
				}
			})
		}


	},
	created() {

	},
	mounted() {

	},
}
</script>
<style lang="scss">
uni-toast {
	z-index: 99999 !important;
}
</style>
<style lang='scss' scoped>
.order_confirm {
	width: 100%;
	position: absolute;
	top: 0;
	bottom: 0;
	display: flex;
	flex-direction: column;
	background-size: contain !important;
	background-repeat: no-repeat !important;
	background-position: top;

	.all {
		padding: 0 24rpx;
		flex: 1;
		overflow: auto;

		.title {
			font-weight: 500;
			font-size: 36rpx;
			color: #0D121A;
			margin: 48rpx 0 40rpx;
			text-align: center;
		}

		.menu {
			width: 100%;
			background: linear-gradient(180deg, #E4F8FF 0%, #FFFFFF 100%);
			border-radius: 24rpx;
			border: 2rpx solid #FFFFFF;
			padding: 64rpx 48rpx;

			.amounts {
				.now {
					font-size: 32rpx;
					color: #0D121A;

					.dw {
						line-height: 40rpx;
					}

					.limit {
						margin-left: 24rpx;
						width: 72rpx;
						height: 40rpx;
						background: linear-gradient(144deg, #00C1FF 0%, #2FFFFC 100%);
						border-radius: 8rpx;
						font-weight: 500;
						font-size: 24rpx;
						color: #0D121A;
						text-align: center;
						line-height: 40rpx;
					}
				}

				.num {
					font-size: 72rpx;
					line-height: 56rpx;
					font-weight: bold;
				}

				.unit {
					margin-left: 8px;
				}

				.past {
					color: #0D121A;
					margin-top: 34rpx;

					.past_text {
						margin-right: 8rpx;
					}
				}
			}

			.choose {
				margin-top: 64rpx;

				.choose_item-box {
					margin-top: 16rpx;

					image {
						width: 48rpx;
						height: 48rpx;
						margin-right: 24rpx;
					}

					text {
						color: #0D121A;
						font-size: 28rpx;
					}
				}

				.choose_item-more {
					text {
						font-size: 28rpx;
						color: #0D121A;
					}

					image {
						width: 32rpx;
						height: 32rpx;
						margin-left: 12rpx;
					}
				}

				.choose_item-box:nth-child(1) {
					margin-top: 0;
				}
			}
		}

		.choosion {
			.name {
				font-weight: 400;
				font-size: 28rpx;
				color: #9EA3B1;
				margin: 32rpx 0 20rpx 32rpx;
			}

			.content {
				background-color: #FFFFFF;
				border-radius: 24rpx;

				.content_item {
					padding: 36rpx 32rpx;

					.item_updata {
						width: 168rpx;
						height: 168rpx;
						background: #F4F5F9;
						border-radius: 16rpx;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						// margin-left: 48rpx;

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

						text {
							color: #9EA3B1;
							font-weight: 400;
							font-size: 24rpx;
						}
					}

					.item_label {
						font-weight: 500;
						font-size: 28rpx;
						color: #0D121A;
						min-width: 150rpx;
						white-space: nowrap;
					}

					.item_num {
						font-size: 28rpx;
						margin-left: 48rpx;

					}

					.item_text {
						font-size: 28rpx;
						color: #9EA3B1;
						margin-left: 48rpx;
					}

					.item_name {
						font-size: 28rpx;
						color: #0D121A;
						margin-left: 16rpx;
					}

					.more_img {
						width: 32rpx;
						height: 32rpx;
						flex-shrink: 0;
					}

					.icon_img {
						width: 48rpx;
						height: 48rpx;
					}

					input {
						height: 0;
					}
				}

				.content_item_input {}
			}
		}

		.agree {
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 24rpx;
			color: #9EA3B1;
			padding: 32rpx 0 0;

			.agree_text {
				color: #0D121A;
			}
		}
	}

	.btom {
		background: #FFFFFF;
		flex-shrink: 1;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16rpx 24rpx;
		padding-bottom: calc(16rpx + constant(safe-area-inset-bottom)) !important;
		padding-bottom: calc(16rpx + env(safe-area-inset-bottom)) !important;

		.sum {
			font-weight: 400;
			font-size: 30rpx;
			color: #0D121A;

			.money {
				font-size: 56rpx;
				color: #0D121A;
			}

			.unit {
				font-size: 40rpx;
			}
		}

		.btn {
			width: 312rpx;
			height: 84rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-weight: bold;
			font-size: 32rpx;
			color: #0D121A;
			background-size: 100% 100% !important;

		}
	}

	.pt18 {
		padding-top: 18rpx;
	}

	.popup_content {
		padding: 32rpx;
		max-height: 1000rpx;
		display: flex;
		flex-direction: column;

		.checkbox {
			flex: 1;
			overflow: auto;
		}

		.btns {
			flex-shrink: 1;
		}
	}

	.btns {
		padding: 0 0 16rpx;
		color: #0D121A;

		.cancel {
			width: 45%;
			height: 84rpx;
			background: #FFFFFF;
			border-radius: 16rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			border: #9EA3B1 1px solid;
		}

		.confirm {
			width: 45%;
			height: 84rpx;
			border-radius: 16rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			background: linear-gradient(144deg, #00C1FF 0%, #2FFFFC 100%);
		}
	}

	.u-popup {
		flex: 0;
		z-index: 999;
	}
}
</style>