<template>
	<view v-if="checkStatus == '通过'">
		<view style="width: 100%;height: 155rpx;background: #FFFFFF;display: flex;align-items: center;" v-if="!editDel"
			@click="clickAddress">
			<view>
				<view style="font-size: 28rpx;color: #3B3B3B;font-weight: 400;display: flex;align-items: center;">
					<image src="/static/images/tabBar/1061@2x.png"
						style="width: 25rpx;height: 30rpx;margin-left: 34rpx;margin-right: 2rpx;" mode="scaleToFill">
						<text>{{addres.contacts}}</text>
						<text style="margin-left: 35rpx;">{{addres.tel}}</text>
				</view>
				<view style="font-size: 26rpx;color:#989898;font-weight: 400;margin-top: 22rpx;margin-left: 61rpx;">
					<text>{{addres.belongtoarea + addres.detailedAddress}}</text>
				</view>
			</view>
		</view>
		<scroll-view scroll-y="true" style="max-height: 68vh;">
			<u-checkbox-group v-model="companyValue" placement="column" @change="companyChange" :size='15'>
				<view class="card" v-for="(item,index) in dataList" :key="index">
					<view>
						<u-checkbox activeColor="#E75F37" shape="circle" :customStyle="{marginBottom: '8px'}"
							:label="item.name" :name="item.name" labelSize="28rpx" labelColor='#3B3B3B'></u-checkbox>
					</view>
					<view style="background: #FCF7F5;padding: 30rpx 30rpx;">
						<view style="margin:15rpx 0 15rpx 20rpx;display: flex;align-items: center;"
							v-for="(ite,ind) in item.list" :key="ind">
							<view>
								<image v-for="(li,inde) in ite.filesList" :key="inde" v-if="li.version === '0'"
									:src="li.url" style="width: 200rpx;height: 200rpx;border-radius: 20rpx;">
								</image>
							</view>
							<view style="width: 100%;">
								<view style="display: flex;justify-content: space-between;">
									<u--text :text="ite.goodsName" size="24rpx" color='#797979' lines="2"></u--text>
									<u-icon name="trash" size="40rpx" color='#C9C9C9'
										@click="deleteGoods(ite.id)"></u-icon>
								</view>
								<view style="display: flex;justify-content: space-between;margin-top: 20rpx;">
									<view style="color: #E75F37;font-size: 32rpx;">￥{{ite.price}}</view>
									<view v-if="!editDel">
										<u-number-box v-model="ite.goodsNum" :min="1" buttonSize="53rpx" color="#414141"
											bgColor="#FCF7F5" iconStyle="color:#A4A4A4"
											@change="(val)=>{statistics(val,index,ind)}"></u-number-box>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</u-checkbox-group>
		</scroll-view>
		<view class="submitBar">
			<view style="margin:20rpx 47rpx;">
				<view v-if="!editDel"
					style="display: flex;justify-content: space-between;align-items: flex-end;padding: 28rpx 0 28rpx 28rpx;">
					<u-checkbox-group v-model="radiovalue" placement="column" @change="radioGroupChange" :size='15'>
						<u-checkbox label="全选" name="全选" activeColor="#E75F37" shape="circle" labelSize="28rpx"
							labelColor='#3B3B3B'></u-checkbox>
					</u-checkbox-group>
					<view style="font-size: 24rpx;">合计:<text style="color: #E75F37;">￥</text><text
							style="font-size: 42rpx;color: #E75F37;">{{totalPrice}}</text></view>
				</view>
				<view style="height: 2rpx;width: 100%;background: #EEEEEE;">
				</view>
				<view
					style="display: flex;justify-content:space-between;align-items: center;padding: 28rpx 0 28rpx 28rpx;">
					<view v-if="!editDel" style="font-size: 24rpx;">
						<view style="color:#A3A3A3">运费:<text style="color: #E75F37;">￥{{totalFreight}}</text></view>
					</view>
					<view style="display: flex;">
						<view class="right-btn" v-if="!editDel" @click="submit()">立即兑换
						</view>
					</view>
				</view>
				<view style="height: 2rpx;width: 100%;background: #EEEEEE;">
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		shoppingCartList,
		generateOrder,
		generateOrderLimit,
		shoppingCartUpdate,
		getCorpsAddr,
		paramserviceDetail,
		getParamservice,
		isProcurement,
		generateOrderPoints
	} from '@/api/tabBar/shoppingCart.js'
	import {
		registerRuntimeCompiler
	} from "vue"
	import {
		details
	} from '@/api/views/personalInformation/index.js'
	import {
		appDetail
	} from '@/api/views/salesSlip/index.js'
	import {
		activityList
	} from '@/api/tabBar/activity.js'
	export default {
		data() {
			return {
				qrcodeshow: false, // 二维码弹窗
				qrcodeData: [], // 二维码数据
				qrcodeurl: '', // 二维码参数
				editDel: false,
				radiovalue: [],
				companyValue: [],
				dataList: [],
				companyValueLength: 0,
				selectedProduct: [],
				totalPrice: 0,
				totalFreight: 0,
				addres: {},
				checkStatus: null,
				adminShow: false,
				inventoryShow: false,
				inventoryContent: '',
				freight: 5,
			}
		},
		options: {
			styleIsolation: 'shared', // 解除样式隔离
		},
		watch: {
			companyValue() {
				if (this.companyValue.length != 0 || this.companyValueLength != 0) {
					if (this.companyValue.length == this.companyValueLength) {
						this.radiovalue = ["全选"]
					} else {
						this.radiovalue = []
					}
				}
				this.statistics()
			}
		},
		created() {
			activityList({
				current: 1,
				size: 10,
				status: 1
			}).then(res => {
				uni.setTabBarBadge({
					index: 2, // tabIndex，tabBar的哪一项，从0开始
					text: res.data.total.toString() // 显示的文本，超过 99 显示成 “…”
				})
			})
			if (uni.getStorageSync('userInfo').tenant_id == '000000') {
				this.adminShow = true
				return
			}
			// 获取审核状态
			details().then(res => {
				this.checkStatus = res.data.checkStatus
				uni.setStorageSync('checkStatus', res.data.checkStatus);
				console.log(1111111)
				if (this.checkStatus != '通过') {
					uni.showToast({
						title: "当前用户未授权,请联系客服",
						icon: "none",
						mask: true
					});
					// uni.switchTab({
					// 	url:'/pages/tabBar/home'
					// })
					// return 
				}
			})


			this.editDel = false
			this.companyValue = []
			shoppingCartList({
				whetherIntegral: '1'
			}).then(res => {
				this.dataList = res.data
				this.companyValueLength = this.dataList.length
				this.inventoryfun(res.data)
				let num = 0
				res.data.forEach(e => {
					console.log(e.list)
					num = num + e.list.length
				})
				uni.setTabBarBadge({
					index: 3, // tabIndex，tabBar的哪一项，从0开始
					text: num.toString() // 显示的文本，超过 99 显示成 “…”
				})
			})
			getCorpsAddr().then(res => {
				this.addres = res.data
			})

			// 支付成功之后的回调
			let options = wx.getEnterOptionsSync();
			if (options.scene == '1038' && options.referrerInfo.appId == 'wxef277996acc166c3') {
				// 代表从收银台小程序返回
				let extraData = options.referrerInfo.extraData;
				if (!extraData) {
					// "当前通过物理按键返回，未接收到返参，建议自行查询交易结果";
					console.log('当前通过物理按键返回，未接收到返参，建议自行查询交易结果');
				} else {
					if (extraData.code == 'success') {
						// "支付成功";
					} else if (extraData.code == 'cancel') {
						// "支付已取消";
						console.log(extraData, '支付已取消');
					} else {
						console.log(extraData, '失败');
						// "支付失败：" + extraData.errmsg;
					}
				}
			}
			isProcurement({
				"param": "freight"
			}).then(res => {
				// res.data.data === '1'
				this.freight = res.data
			})

		},
		methods: {
			tabbarClick(tab) {
				// uni.$u.route('/pages/integralMall/'+tab);	
				uni.navigateTo({
					url: '/pages/integralMall/' + tab
				})
			},
			// 库存弹窗
			inventoryfun(arr) {
				let sum = ''
				arr.map((item, index) => {
					item.list.map(ite => {
						if (Number(ite.goodsNum) > Number(ite.inventory)) {
							sum += `${ite.goodsName} 的库存数量为${ite.inventory}<br>`
						}
						return ite
					})
					return item
				})
				if (sum != '') {
					this.inventoryContent = sum + '请修正数量后重新结算'
					this.inventoryShow = true
					return true
				}
				return false
			},
			// admin确认
			adminConfirm() {
				uni.clearStorageSync();
				uni.redirectTo({
					url: '/pages/login/login'
				})
			},
			// admin取消
			adminCancel() {
				uni.switchTab({
					url: '/pages/tabBar/home'
				})
			},
			// 弹窗关闭
			qrcodeclose() {
				this.qrcodeshow = false
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				// 详情调用
				shoppingCartList({
					whetherIntegral: '1'
				}).then(res => {
					this.dataList = res.data
					this.companyValueLength = this.dataList.length
					uni.hideLoading();
				}).catch(err => {
					uni.hideLoading();
				})
			},

			clickAddress() {
				this.$u.route('/pages/views/personalInformation/addressManagement');
			},
			getList() {
				shoppingCartList({
					whetherIntegral: '1'
				}).then(res => {
					this.dataList = res.data
					this.companyValueLength = this.dataList.length
					let num = 0
					res.data.forEach(e => {
						num = num + e.list.length
					})
					uni.setTabBarBadge({
						index: 3, // tabIndex，tabBar的哪一项，从0开始
						text: num.toString() // 显示的文本，超过 99 显示成 “…”
					})
					uni.hideLoading();
				}).catch(err => {
					uni.hideLoading();
				})
			},
			deleteGoods(val) {
				let _this = this
				uni.showModal({
					title: '提示',
					content: '是否删除?',
					success: function(res) {
						if (res.confirm) {
							uni.showLoading({
								title: '加载中',
								mask: true
							});
							shoppingCartUpdate({
								ids: val
							}).then(res => {
								uni.showToast({
									title: "删除成功",
									icon: 'none'
								});
								uni.showLoading({
									title: '加载中',
									mask: true
								});
								_this.getList()
								// this.editDel = false
								_this.companyValue = []

								uni.hideLoading();
							}).catch(err => {
								uni.hideLoading();
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}

					}
				});
			},
			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)
							}
						}
					}
				}
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				shoppingCartUpdate({
					ids: data.join(',')
				}).then(res => {
					uni.showToast({
						title: "删除成功",
						icon: 'none'
					});
					uni.hideLoading();
					uni.showLoading({
						title: '加载中',
						mask: true
					});
					this.editDel = false
					this.companyValue = []
					shoppingCartList({
						whetherIntegral: '1'
					}).then(res => {
						this.dataList = res.data
						this.companyValueLength = this.dataList.length
						uni.hideLoading();
					}).catch(err => {
						uni.hideLoading();
					})
				}).catch(err => {
					uni.hideLoading();
				})
			},
			// 立即支付
			async submit() {

				if (this.selectedProduct.length == 0) {
					uni.showToast({
						title: "请先选择要支付的商品",
						icon: 'none'
					});
					return
				}
				if (this.inventoryfun(this.dataList)) {
					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,
									list: ite.list
								})
							}
						}
					}
					let _this = this
					uni.showModal({
						title: '提示',
						content: '是否确认兑换?',
						success: function(res) {
							if (res.confirm) {
								uni.showLoading({
									title: '加载中',
									mask: true
								});
								generateOrderPoints({
									address: _this.addres.belongtoarea + _this.addres
										.detailedAddress,
									list: data,
								}).then(res => {
									uni.hideLoading({
										noConflict: true
									});
									uni.showToast({
										title: res.data,
										icon: "none",
									});
									shoppingCartList({
										whetherIntegral: '1'
									}).then(res => {
										_this.dataList = res.data
										_this.companyValueLength = _this.dataList.length
									})
								})
							}

						}
					});
					// 判断是否用额度支付
					// const personRef = await details()
					// console.log(personRef.data, 349);
					// const totalPrice = Number(this.totalPrice) + Number(this.totalFreight)
					// 是否开通额度
					// 	getParamservice(1, 10, {
					// 		paramKey: 'WeChat.shipping.notification'
					// 	}).then(res => {
					// 		console.log(res)
					// 		if (res.data.records.length > 0) {
					// 			let payType = res.data.records[0].paramValue == 1 ? 'W11' : 'W06'
					// 			if (personRef.data.ifLimitAmount == 1) {
					// 				// 额度是否够用
					// 				if (Number(personRef.data.limitAmount >= totalPrice)) {
					// 					// 额度

					// 					// this.payType='W06'
					// 					generateOrderLimit({
					// 						payType: res.data.records[0].paramValue == 1 ? 'W11' : 'W06',
					// 						address: this.addres.belongtoarea + this.addres.detailedAddress,
					// 						list: data,
					// 					}).then(res => {
					// 						uni.hideLoading();
					// 						uni.showToast({
					// 							title: '支付成功',
					// 							mask: true,
					// 							duration: 2000
					// 						});
					// 						setTimeout(function() {
					// 							uni.hideLoading();
					// 						}, 1000);
					// 						// 详情调用
					// 						shoppingCartList().then(res => {
					// 							this.dataList = res.data
					// 							this.companyValueLength = this.dataList.length
					// 						}).catch(err => {})
					// 					})
					// 					return
					// 				}
					// 			}

					// 			// 正常支付
					// 			generateOrder({
					// 				payType: res.data.records[0].paramValue == 1 ? 'W11' : 'W06',
					// 				address: this.addres.belongtoarea + this.addres.detailedAddress,
					// 				list: data,
					// 			}).then(res => {
					// 				let generateOrderData = res.data
					// 				paramserviceDetail({
					// 					paramKey: 'cashier.payment'
					// 				}).then(res => {
					// 					let paramservice = res.data
					// 					// paramservice.paramValue=0
					// 					// 判断是调支付台的接口还是微信支付的接口
					// 					if (paramservice && paramservice.paramValue == '1') {
					// 						console.log(222211111111);
					// 						// uni.hideLoading();
					// 						// 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,11111111);
					// 						// 		uni.showToast({
					// 						// 			title: "支付失败",
					// 						// 			icon: 'none',
					// 						// 			mask: true
					// 						// 		});
					// 						// 		setTimeout(function() {
					// 						// 			uni.hideLoading();
					// 						// 			// this_.refresh(res.data.id)
					// 						// 		}, 1000);
					// 						// 	}
					// 						// })
					// 						let obj = {
					// 							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,
					// 							},
					// 						}
					// 						console.log(obj);
					// 						if (!generateOrderData.reqsn) {
					// 							uni.showToast({
					// 								title: '当前订单号为空，请联系供应商！！！',
					// 								icon: 'none',
					// 								mask: true,
					// 								duration: 2000
					// 							});
					// 							// 详情调用
					// 							shoppingCartList().then(res => {
					// 								this.dataList = res.data
					// 								this.companyValueLength = this.dataList
					// 									.length
					// 							}).catch(err => {})
					// 							return
					// 						}
					// 						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,
					// 								limit_pay: "",
					// 								randomstr: generateOrderData.randomstr,
					// 								paytype: generateOrderData.paytype,
					// 								signtype: generateOrderData.signtype,
					// 								sign: generateOrderData.sign,
					// 							},
					// 							success: (a) => {
					// 								uni.hideLoading();
					// 							},
					// 							fail: (err) => {
					// 								uni.hideLoading();
					// 							}
					// 						})
					// 					} else {
					// 						console.log(2222222222222222);
					// 						if (payType && (payType == 'W01' || payType == 'U01' ||
					// 								payType == 'A01' || payType == 'S01'
					// 							)) {
					// 							console.log(generateOrderData, 321);
					// 							// 订单详情接口
					// 							this.qrcodeurl = generateOrderData.url
					// 							appDetail({
					// 								id: generateOrderData.id
					// 							}).then(res => {
					// 								uni.hideLoading();
					// 								this.qrcodeshow = true
					// 								this.qrcodeData = res.data
					// 								console.log(res.data);
					// 							})
					// 						} 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(22222222);

					// 									uni.showToast({
					// 										title: "支付失败",
					// 										icon: 'none',
					// 										mask: true
					// 									});
					// 									setTimeout(function() {
					// 										uni.hideLoading();
					// 										// this_.refresh(res.data.id)
					// 									}, 1000);
					// 								}
					// 							})
					// 						}

					// 					}
					// 				})

					// 			}).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.inventoryfun(this.dataList)
				this.statistics()
			},
			statistics(val, index, ind) {
				console.log(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)
				// 			}
				// 		}
				// 	}
				// }、
				for (let item of this.companyValue) {
					for (let ite of this.dataList) {
						if (item == ite.name) {
							data.push({
								name: item,
								list: ite.list
							})
						}
					}
				}
				this.totalPrice = 0
				this.totalFreight = 0
				let num = 0
				for (let item of data) {
					let num1 = 0
					for (let items of item.list) {
						this.totalPrice += Number(items.price) * Number(items.goodsNum)
						num += Number(items.goodsNum)
						num1 += Number(items.goodsNum)
					}
					if (num1 == 1) {
						this.totalFreight += this.freight ? Number(this.freight) : 5
						this.totalPrice = Number(this.totalPrice) + Number(this.totalFreight)
					}

				}

				/* if(num>1){
					this.totalFreight = 0
				} */
				this.totalFreight = this.totalFreight.toFixed(2)
				this.totalPrice = this.totalPrice
				this.selectedProduct = data
			},
			companyChange(n) {
				this.companyValue = n
				this.inventoryfun(this.dataList)
			}
		}
	}
</script>
<style lang="scss" scoped>
.card {
		background: #FFFFFF;
		padding: 32rpx;
		margin: 20rpx 0;

		::v-deep .u-checkbox__icon-wrap {
			border-color: #E75F37 !important;
		}

		::v-deep .u-number-box {
			border: 2rpx #E1E1E1 solid;
			border-radius: 8rpx;
		}

		::v-deep .u-number-box__minus {
			border-right: 2rpx #E1E1E1 solid;
		}

		::v-deep .u-number-box__plus {
			border-left: 2rpx #E1E1E1 solid;
		}
	}

	.submitBar {
		position: fixed;
		bottom: calc(50px + env(safe-area-inset-bottom));
		background-color: #fff;
		width: 100%;
		z-index: 10;

		::v-deep .u-checkbox__icon-wrap {
			border-color: #E75F37 !important;
		}

		.left-btn {
			background-color: #FFEEE9;
			color: #E75F37;
			font-size: 26rpx;
			width: 160rpx;
			height: 65rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			border-top-left-radius: 33rpx;
			border-bottom-left-radius: 33rpx;
		}

		.right-btn {
			background-color: #E75F37;
			color: #fff;
			font-size: 26rpx;
			width: 160rpx;
			height: 65rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 33rpx;
		}
	}
</style>