<template>
	<view>
		<view style="background-color: #fff;padding: 20rpx;border-radius: 20rpx;">
			<view>
				<!-- 				<view>
					<view style="display: flex;width: 580rpx;" v-if="!editDel" @click="clickAddress">
						<u-icon name="map"></u-icon>
						<u--text :text="addres.belongtoarea + addres.detailedAddress" size="28rpx" lines="1"></u--text>
					</view>
				</view> -->
				<view style="display: flex;justify-content: flex-end;">
					<view @click="editDel = !editDel">{{editDel?'取消':'编辑'}}</view>
				</view>
			</view>
		</view>
		<u-checkbox-group v-model="companyValue" placement="column" @change="companyChange">
			<view class="collection" v-for="(item,index) in dataList" :key="index">
				<view>
					<u-checkbox activeColor="#FD4B09" shape="circle" :customStyle="{marginBottom: '8px'}"
						:label="item.name" :name="item.name" labelSize="28rpx" :disabled="item.disabled"></u-checkbox>
				</view>
				<view style="margin-left: 20rpx;display: flex;align-items: center;" v-for="(ite,ind) in item.list"
					:key="ind">
					<view class="dingbox">
						<view v-if="ite.payType && ite.payType.indexOf('01') != -1">扫码支付</view>
						<view v-else>微信支付</view>
					</view>
					<view>
						<image v-for="(li,inde) in ite.orderItemsList" :key="inde" :src="li.goodsFilesList[0].url"
							style="width: 200rpx;height: 200rpx;border-radius: 20rpx;">
						</image>
					</view>
					<view class="goods">
						<u--text v-for="(ites,inds) in ite.orderItemsList" :key="inds" :text="ites.goodsName"
							size="24rpx" lines="2"></u--text>
						<view class="price" v-for="(ites,inds) in ite.orderItemsList" :key="inds">
							<view>￥{{ites.price}}</view>
							<view v-if="!editDel">
								<u-number-box v-model="ites.goodsNum" :min="1" :max="ites.goodsNum" buttonSize="40rpx"
									disabled @change="(val)=>{statistics(val,index,ind)}"></u-number-box>
							</view>
						</view>
					</view>
					<view v-if="editDel">
						<u-icon name="minus-circle-fill" color="#ff0000" size="52rpx"
							@click="deleteGoods(ite.id)"></u-icon>
					</view>
				</view>
			</view>
		</u-checkbox-group>
		<view style="height: 100rpx;"></view>
		<view class="submitBar" style="padding-bottom: env(safe-area-inset-bottom);">
			<view class="bar_view">
				<view v-if="!editDel" style="margin-left: 20rpx;">
					<view>总计:￥<text>{{totalPrice}}</text></view>
					<view style="font-size: 22rpx;color: #FD4B09;">运费:￥{{totalFreight}}</view>
				</view>
				<view style="height: 120rpx;display: flex;color: #fff;">
					<!-- <view v-if="!editDel" class="lvbutton" @click="submit('W01')">他人代付</view> -->
					<view v-if="!editDel" class="redbutton" @click="submit()">立即支付</view>
					<view v-else class="redbutton" @click="deleteShopping">删除</view>
				</view>
				<!-- <view style="width: 200rpx;">
					<u-button shape="circle" size="small" text="立即支付" v-if="!editDel"
						:disabled="this.selectedProduct.length == 0"
						color="linear-gradient(0deg, #FD5003 0%, #FBA680 100%)" @click="submit"></u-button>
					<u-button shape="circle" size="small" text="删除" v-else :disabled="this.selectedProduct.length == 0"
						color="linear-gradient(0deg, #FD5003 0%, #FBA680 100%)" @click="deleteShopping"></u-button>
				</view> -->
			</view>
		</view>
		<u-empty style="position: absolute;top: 45%;left: 50%;transform:translate(-50%,-50%)"
			v-if="dataList.length == 0 && !isLoading" mode="car" text="待付款为空"
			icon="http://cdn.uviewui.com/uview/empty/car.png" />

		<u-popup :show="qrcodeshow" mode="center" :closeable="true" @close="qrcodeclose">
			<view style="padding: 20rpx;">
				<view style="font-size: 26rpx;">截屏二维码支付</view>
				<view>
					<uqrcode ref="uqrcode" canvas-id="qrcode" size="600" sizeUnit="rpx" :value="qrcodeurl"
						:options="{ margin: 5 }"></uqrcode>
					<!-- options 配置项 https://uqrcode.cn/doc/document/native.html#%E5%AE%9E%E4%BE%8B%E6%96%B9%E6%B3%95  -->
				</view>

				<view>
					<!-- {{qrcodeData.contacts}} -->
					<view style="font-size: 34rpx;font-weight: 500;">{{qrcodeData.salesCompanyName}}</view>
					<view style="color: #9a9a9a;font-size: 26rpx;">
						<text>金额:</text>
						<text style="color: #FD4B09;font-size: 30rpx;">￥{{qrcodeData.salesAmount}}</text>
					</view>
					<view style="color: #9a9a9a;font-size: 26rpx;">二维码有效期: {{qrcodeData.businesDate}}</view>
				</view>
			</view>
		</u-popup>

	</view>
</template>
<script>
	import {
		obligationList,
		generateOrder,
		payPrepay,
		shoppingCartUpdate,
		getCorpsAddr,
		update,
		paramserviceDetail
	} from '@/api/tabBar/shoppingCart.js'
	import {
		registerRuntimeCompiler
	} from "vue"
	import {
		logo
	} from '../../../common/setting'
	import {
		appDetail
	} from '@/api/views/salesSlip/index.js'
	import {
		dateFormat
	} from '@/common/dateFormat.js'
	export default {
		data() {
			return {
				qrcodeshow: false, // 二维码弹窗
				qrcodeData: [], // 二维码数据
				qrcodeurl: '', // 二维码参数

				editDel: false,
				radiovalue: [],
				companyValue: [],
				dataList: [],
				companyValueLength: 0,
				selectedProduct: [],
				totalPrice: 0.00,
				totalFreight: 0.00,
				addres: {},
				isLoading: true
			}
		},
		watch: {
			companyValue() {

				if (this.companyValue.length != 0 || this.companyValueLength != 0) {
					if (this.companyValue.length == this.companyValueLength) {
						this.radiovalue = ["全选"]
					} else {
						this.radiovalue = []
					}
				}
				// if (this.companyValue.length > 0) {
				// 	console.log(21321324);

				// 	// if (this.companyValue.length == this.companyValueLength) {
				// 	// 	this.radiovalue = ["全选"]
				// 	// } else {
				// 	// 	this.radiovalue = []
				// 	// }
				// }
				this.statistics()
			}
		},
		onLoad() {
			console.log(Date.parse('2023-11-22 00:00:00') + 60 * 60 * 1000);
			console.log(dateFormat(new Date(Date.parse('2023-11-22 00:00:00') + 60 * 60 * 1000)), 155);
		},
		onShow() {
			this.editDel = false
			this.companyValue = []
			this.isLoading = true
			obligationList().then(res => {
				console.log(res);
				this.dataList = res.data
				this.companyValueLength = this.dataList.length
				this.isLoading = false // 添加这一行
			})
			getCorpsAddr().then(res => {
				this.addres = res.data
			})
		},
		methods: {
			// 弹窗关闭
			qrcodeclose() {
				this.qrcodeshow = false
			},

			deleteGoods(val) {
				console.log(val);

				uni.showLoading({
					title: '加载中',
					mask: true
				});
				update(val).then(res => {
					uni.showToast({
						title: "删除成功",
						icon: 'none'
					});
					uni.showLoading({
						title: '加载中',
						mask: true
					});
					this.editDel = false
					this.companyValue = []
					obligationList().then(res => {
						this.dataList = res.data
						this.companyValueLength = this.dataList.length
						uni.hideLoading();
					}).catch(err => {
						uni.hideLoading();
					})
					uni.hideLoading();
				}).catch(err => {
					uni.hideLoading();
				})
			},
			deleteShopping() {
				if (this.selectedProduct.length == 0) {
					uni.showToast({
						title: "请先选择要支付的商品",
						icon: 'none'
					});
					return
				}
				let data = []
				for (let item of this.companyValue) {
					for (let ite of this.dataList) {
						if (item == ite.name) {
							for (let it of ite.list) {
								data.push(it.id)
							}
						}
					}
				};

				console.log(data.join(","));
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				update(data.join(",")).then(res => {
					uni.showToast({
						title: "删除成功",
						icon: 'none'
					});
					uni.hideLoading();
					uni.showLoading({
						title: '加载中',
						mask: true
					});
					this.editDel = false
					this.companyValue = []
					obligationList().then(res => {
						this.dataList = res.data
						this.companyValueLength = this.dataList.length
						uni.hideLoading();
					}).catch(err => {
						uni.hideLoading();
					})
				}).catch(err => {
					uni.hideLoading();
				})
			},
			submit(payType) {
				if (this.selectedProduct.length == 0) {
					uni.showToast({
						title: "请先选择要支付的商品",
						icon: 'none'
					});
					return
				}
				for (let item of this.selectedProduct) {
					if (!item.payType) return uni.showToast({
						title: "当前订单支付方式异常,请重新购买",
						icon: 'none',
						duration: 2500
					});
					if (item.payType && item.payType == 'W06') {
						// 微信支付
					} else {
						// 扫码支付
						let i = 0
						let j = 0
						console.log(this.selectedProduct)
						this.selectedProduct.forEach((item, index) => {
							console.log(item.payType.indexOf('01'))
							if (item.payType && item.payType.indexOf('01') != -1) {
								i++
							} else {
								j++
							}
						})
						if (j != 0) {
							uni.showToast({
								title: "请选择相同的支付方式",
								icon: 'none'
							});
							return
						}
						if (i > 1) {
							uni.showToast({
								title: "扫码支付只能选择一个",
								icon: 'none'
							});
							return
						}
					}
				}

				if (this.companyValue.length > 0) {
					let data = []
					for (let item of this.companyValue) {
						for (let ite of this.dataList) {
							if (item == ite.name) {
								data.push({
									name: item,
								})
							}
						}
					}

					console.log('data', data);
					uni.showLoading({
						title: '加载中',
						mask: true
					});

					payPrepay({
						srcOrderNo: data[0].name
					}).then(res => {
						let generateOrderData = res.data
						paramserviceDetail({
							paramKey: 'cashier.payment'
						}).then(res => {
							let paramservice = res.data
							// 判断是调支付台的接口还是微信支付的接口
							if (paramservice && paramservice.paramValue == '1') {
								wx.openEmbeddedMiniProgram({
									appId: 'wxef277996acc166c3',
									extraData: {
										cusid: generateOrderData.cusid,
										appid: generateOrderData.appid,
										orgid: generateOrderData.orgid,
										version: generateOrderData.version,
										trxamt: generateOrderData.trxamt,
										reqsn: generateOrderData.reqsn,
										notify_url: generateOrderData.notify_url,
										body: generateOrderData.body,
										remark: generateOrderData.remark,
										validtime: generateOrderData.validtime,
										limit_pay: generateOrderData.limit_pay,
										randomstr: generateOrderData.randomstr,
										paytype: generateOrderData.paytype,
										signtype: generateOrderData.signtype,
										sign: generateOrderData.sign,
									},
									success: (a) => {
										uni.hideLoading();
									},
									fail: (err) => {
										uni.hideLoading();
									}
								})
							} else {
								if (this.selectedProduct[0].payType &&
									(this.selectedProduct[0].payType == 'W01' || this.selectedProduct[0]
										.payType == 'U01' || this.selectedProduct[0].payType == 'A01' ||
										this.selectedProduct[0].payType == 'S01')) {
									this.qrcodeurl = this.selectedProduct[0].payUrl
									appDetail({
										id: this.selectedProduct[0].id
									}).then(res => {
										uni.hideLoading();
										this.qrcodeshow = true
										this.qrcodeData = res.data
										// 往后延长一小时
										this.qrcodeData.businesDate = dateFormat(new Date(Date
											.parse(this.qrcodeData.businesDate) + 60 * 60 *
											1000))

									})
								} else {
									uni.requestPayment({
										provider: "wxpay",
										appId: generateOrderData.appId,
										timeStamp: generateOrderData.timeStamp,
										nonceStr: generateOrderData.nonceStr,
										package: generateOrderData.package,
										signType: generateOrderData.signType,
										paySign: generateOrderData.paySign,
										success(res) {
											uni.showToast({
												title: '支付成功',
												mask: true,
												duration: 2000
											});
											setTimeout(function() {
												uni.hideLoading();
												// this_.refresh(res.data.data.id)
											}, 1000);
										},
										fail(e) {
											console.log(e);
											uni.showToast({
												title: "支付失败",
												icon: 'none',
												mask: true
											});
											setTimeout(function() {
												uni.hideLoading();
												// this_.refresh(res.data.id)
											}, 1000);
										}
									})
								}

							}
						})


						// uni.showToast({
						// 	title: "提交成功",
						// 	icon: 'none'
						// });
						// uni.hideLoading();
						// uni.showLoading({
						// 	title: '加载中',
						// 	mask: true
						// });
						// this.editDel = false
						// this.companyValue = []
						// shoppingCartList().then(res => {
						// 	this.dataList = res.data
						// 	this.companyValueLength = this.dataList.length
						// 	uni.hideLoading();
						// }).catch(err => {
						// 	uni.hideLoading();
						// })
					}).catch(err => {
						uni.hideLoading();
					})
				}
			},
			radioGroupChange(e) {
				this.radiovalue = e
				if (e.length == 0) {
					this.companyValue = []
				} else {
					for (let li of this.dataList) {
						if (!this.companyValue.includes(li.name)) {
							this.companyValue.push(li.name)
						}
					}
				}
				this.statistics()
			},
			statistics(val, index, ind) {
				if (val) {
					this.dataList[index].list[ind].goodsNum = val.value
				}
				let data = []
				for (let item of this.companyValue) {
					for (let ite of this.dataList) {
						if (item == ite.name) {
							for (let it of ite.list) {
								data.push(it)
							}
						}
					}
				}
				console.log(data);
				this.totalPrice = 0
				this.totalFreight = 0
				for (let item of data) {
					for (let orderItem of item.orderItemsList) {
						this.totalPrice += Number(orderItem.price) * Number(orderItem.goodsNum)
						console.log(orderItem.goodsNum);
						if (Number(orderItem.goodsNum) == 1) {
							this.totalFreight += 5
						}
					}

				}
				this.totalFreight = this.totalFreight.toFixed(2)
				this.totalPrice = this.totalPrice.toFixed(2)
				this.selectedProduct = data
			},
			companyChange(n) {
				if (n == 0) {
					this.dataList.forEach((e => {
						e.disabled = false
					}))
				} else {
					this.dataList.forEach((e => {
						if (n[0] != e.name) {
							e.disabled = true
						}

					}))
				}
				this.companyValue = n
			}
		}
	}
</script>
<style lang="scss" scoped>
	.collection {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 20rpx;
		margin-top: 20rpx;
		position: relative;

		.dingbox {
			position: absolute;
			top: 20rpx;
			right: 20rpx;
			font-size: 26rpx;
			color: #FD4B09;
		}
	}

	.goods {
		width: 100%;
		margin-left: 20rpx;
		height: 200rpx;
		display: grid;
		align-content: space-between;

		.price {
			display: flex;
			justify-content: space-between !important;
			margin-top: 20rpx;
			align-items: center;

			view:nth-child(1) {
				color: #FD4B09;
				font-size: 40rpx;
			}
		}
	}

	.submitBar {
		position: fixed;
		bottom: 0;
		background-color: #fff;
		width: 100%;
		z-index: 10;

		.bar_view {
			display: flex;
			justify-content: space-between;
			align-items: center;
			// padding: 10rpx;
		}
	}

	.redbutton {
		background-color: #FD4B09;
		height: 120rpx;
		line-height: 120rpx;
		width: 200rpx;
		text-align: center;
	}

	.lvbutton {
		background-color: #4c9e44;
		height: 120rpx;
		line-height: 120rpx;
		width: 200rpx;
		text-align: center;
	}
</style>