<template>
	<view>
		<view style="background-color: #fff;padding: 20rpx;border-radius: 20rpx;">
			<view style="display: flex;justify-content: space-between;">
				<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;">
					<view style="margin-right: 40rpx;">|</view>
					<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"></u-checkbox>
				</view>
				<view style="margin-left: 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 class="goods">
						<u--text :text="ite.goodsName" size="24rpx" lines="2"></u--text>
						<view class="price">
							<view>￥{{ite.price}}</view>
							<view v-if="!editDel">
								<u-number-box v-model="ite.goodsNum" :min="1" :max="ite.inventory" buttonSize="40rpx"
									@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">
			<view class="bar_view">
				<view>
					<u-checkbox-group v-model="radiovalue" placement="column" @change="radioGroupChange">
						<u-checkbox label="全选" name="全选" activeColor="#FD4B09" shape="circle"></u-checkbox>
					</u-checkbox-group>
				</view>
				<view v-if="!editDel">
					<view>总计:￥<text>{{totalPrice}}</text></view>
					<view style="font-size: 22rpx;color: #FD4B09;">运费:￥{{totalFreight}}</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" mode="car" icon="http://cdn.uviewui.com/uview/empty/car.png" />
	</view>
</template>
<script>
	import {
		shoppingCartList,
		generateOrder,
		shoppingCartUpdate,
		getCorpsAddr,
		paramserviceDetail
	} from '@/api/tabBar/shoppingCart.js'
import { registerRuntimeCompiler } from "vue"
import { details } from '@/api/views/personalInformation/index.js'
	export default {
		data() {
			return {
				editDel: false,
				radiovalue: [],
				companyValue: [],
				dataList: [],
				companyValueLength: 0,
				selectedProduct: [],
				totalPrice: 0.00,
				totalFreight: 0.00,
				addres: {},
				checkStatus:null,
			}
		},
		watch: {
			companyValue() {
				if (this.companyValue.length != 0 || this.companyValueLength != 0) {
					if (this.companyValue.length == this.companyValueLength) {
						this.radiovalue = ["全选"]
					} else {
						this.radiovalue = []
					}
				}
				this.statistics()
			}
		},
		onShow() {
			// 获取审核状态
			details().then(res => {
				this.checkStatus = res.data.checkStatus
				uni.setStorageSync('checkStatus', res.data.checkStatus);
				if (this.checkStatus != '通过') {
					// uni.showToast({
					// 	title: "当前用户未授权,请联系客服",
					// 	icon: "none",
					// 	mask:true
					// });
					uni.switchTab({
						url:'/pages/tabBar/home'
					})
					return 
				}
			})
			
			
			this.editDel = false
			this.companyValue = []
			shoppingCartList().then(res => {
				this.dataList = res.data
				this.companyValueLength = this.dataList.length
			})
			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;
					}
				}
			}
			
		},
		methods: {
			clickAddress() {
				this.$u.route('/pages/views/personalInformation/addressManagement');
			},
			deleteGoods(val) {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				shoppingCartUpdate({
					ids: val
				}).then(res => {
					uni.showToast({
						title: "删除成功",
						icon: 'none'
					});
					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();
					})
					uni.hideLoading();
				}).catch(err => {
					uni.hideLoading();
				})
			},
			deleteShopping() {
				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().then(res => {
						this.dataList = res.data
						this.companyValueLength = this.dataList.length
						uni.hideLoading();
					}).catch(err => {
						uni.hideLoading();
					})
				}).catch(err => {
					uni.hideLoading();
				})
			},
			// 立即支付
			submit() {
				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
								})
							}
						}
					}
					uni.showLoading({
						title: '加载中',
						mask: true
					});
					generateOrder({
						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
							// 判断是调支付台的接口还是微信支付的接口
							if (paramservice.paramValue == '1') {
								// uni.hideLoading();
								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);
								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 {
								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)
				// 			}
				// 		}
				// 	}
				// }、
				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 += 5
					}

				}
			
				/* if(num>1){
					this.totalFreight = 0
				} */
				this.totalFreight = this.totalFreight.toFixed(2)
				this.totalPrice = this.totalPrice.toFixed(2)
				this.selectedProduct = data
			},
			companyChange(n) {
				this.companyValue = n
			}
		}
	}
</script>
<style lang="scss" scoped>
	.collection {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 20rpx;
		margin-top: 20rpx;
	}

	.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;
		}
	}
</style>