<template>
	<view class="container" v-if="checkStatus == '审核通过'">
		<view style="width: 100%;height: 155rpx;background: #FFFFFF;display: flex;align-items: center;"
			@click="clickAddress" v-if="addres.length">
			<view>
				<view style="font-size: 28rpx;color: #3B3B3B;font-weight: 400;display: flex;align-items: center;">
					<image src="/static/images/shoppingCart/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>
					</image>
				</view>
				<view style="font-size: 26rpx;color:#989898;font-weight: 400;margin-top: 22rpx;margin-left: 61rpx;">
					<text>{{addres.detailedAddress}}</text>
				</view>
			</view>
		</view>
		<z-paging ref="paging" v-model="dataList" @query="getList" :fixed="false" :auto-show-back-to-top="true"
			empty-view-text="暂无购物车" :hide-empty-view="false" :auto-show-system-loading="true"
			:loading-more-enabled="false" :hide-no-more="true">
			<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="#03803B" shape="circle" :customStyle="{marginBottom: '16rpx'}"
							:label="item.goodsName" :name="item.goodsName" labelSize="32rpx"
							labelColor='#3B3B3B'></u-checkbox>
					</view>
					<view style="background: #FCF7F5;padding: 20rpx;display: flex;">
						<view>
							<image :src="item.picture" style="width: 120rpx;height: 120rpx;border-radius: 10rpx;">
							</image>
						</view>
						<view style="width: 100%;margin-left: 8rpx ;">
							<view style="display: flex;justify-content: space-between;">
								<u--text :text="item.goodsName" size="24rpx" color='#797979' lines="2"></u--text>
								<u-icon name="trash" size="40rpx" color='#C9C9C9'
									@click="deleteGoods(item.id)"></u-icon>
							</view>
							<view
								style="display: flex;justify-content: space-between;align-items: flex-end;margin-top: 20rpx;">
								<view style="color: #03803B;font-size: 32rpx;">￥{{item.price}}</view>
								<view>
									<u-number-box v-model="item.goodsNum" :min="1" :max='item.inventory'
										buttonSize="53rpx" color="#414141" bgColor="#FCF7F5" iconStyle="color:#A4A4A4"
										@change="(val)=>{statistics(val,index,item)}"></u-number-box>
								</view>
							</view>
						</view>
					</view>
				</view>
			</u-checkbox-group>
			<view class="dynamic-bottom">
			</view>
		</z-paging>
		<view class="submitBar" :style="{ bottom: tabbarHeight + 'px' }">
			<view style="padding:0rpx 40rpx;">
				<!-- 第二行：全选和合计 -->
				<view class="top-row">
					<view class="select-all">
						<u-checkbox-group v-model="radiovalue" placement="column" @change="radioGroupChange" :size='15'>
							<u-checkbox label="全选" name="全选" activeColor="#03803B" shape="circle" labelSize="28rpx"
								labelColor='#3B3B3B'></u-checkbox>
						</u-checkbox-group>
					</view>
					<view class="total-price">
						<text style="font-size: 24rpx;">合计:</text>
						<text style="color: #03803B;">￥</text>
						<text style="font-size: 42rpx;color: #03803B;">{{totalPrice}}</text>
					</view>
				</view>

				<!-- 分隔线 -->
				<view style="height: 2rpx;width: 100%;background: #EEEEEE;"></view>

				<!-- 第三行：运费和支付按钮 -->
				<view style="display: flex;justify-content:flex-end;align-items: center;padding: 10rpx;">
					<view style="display: flex;">
						<!-- <view class="left-btn" @click="submit('W01')">
							<text style="line-height: 27rpx;">
								他人代付
							</text>
						</view> -->
						<view class="right-btn" @click="submit()">
							<text style="line-height: 27rpx;">
								去结算
							</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		shoppingCartList,
		generateOrder,
		generateOrderLimit,
		shoppingCartUpdate,
		getCorpsAddr,
		paramserviceDetail,
		getParamservice,
		isProcurement,
		generateOrderShare,
		updateNumber
	} from '@/api/shoppingCart/index.js'
	import {
		details
	} from '@/api/personalInformation/index.js'
	import {
		appDetail
	} from '@/api/home/index.js'
	import {
		activityList
	} from '@/api/activity/index.js'
	export default {
		data() {
			return {
				tabbarHeight: 0, // 默认tabbar高度
				qrcodeshow: false, // 二维码弹窗
				qrcodeData: [], // 二维码数据
				qrcodeurl: '', // 二维码参数
				radiovalue: [],
				companyValue: [],
				dataList: [],
				companyValueLength: 0,
				selecteList: [],
				totalPrice: 0.00,
				addres: {},
				checkStatus: null,

				adminShow: false,

				inventoryShow: false,
				inventoryContent: '',
				freight: 5,
				recoveredBalance: 0,
				checkRecoveredBalance: [],
				firstLoad: false
			}
		},
		watch: {
			companyValue() {
				if (this.companyValue.length != 0 || this.companyValueLength != 0) {
					if (this.companyValue.length == this.companyValueLength) {
						this.radiovalue = ["全选"]
					} else {
						this.radiovalue = []
					}
				}
				this.cartTotal()
			},
			getUserInfo() {
				details().then(res => {
					this.recoveredBalance = res.data.recoveredBalance
				})
			}
		},
		onLoad() {
			// 获取tabbar高度（需要根据实际tabbar高度调整）
			this.getTabbarHeight()
		},
		onShow() {
			this.getUpdate()
			// activityList({
			// 	current: 1,
			// 	size: 10,
			// 	status: 1
			// }).then(res => {
			// 	uni.setTabBarBadge({
			// 		index: 1, // tabIndex，tabBar的哪一项，从0开始
			// 		text: res.data.total.toString() // 显示的文本，超过 99 显示成 “…”
			// 	})
			// })
			// 获取审核状态
			details().then(res => {
				this.checkStatus = res.data.checkStatus
				this.recoveredBalance = res.data.recoveredBalance
				uni.setStorageSync('checkStatus', res.data.checkStatus);
				if (this.checkStatus != '审核通过') {
					uni.showToast({
						title: "当前用户未授权,请联系客服",
						icon: "none",
						mask: true
					});
				}
			})
			this.companyValue = []
			if (this.firstLoad) {
				this.$refs.paging.reload()
			}
		},
		methods: {
			getTabbarHeight() {
				// 可以通过uni.getSystemInfo获取系统信息
				// #ifdef H5
				uni.getSystemInfo({
					success: (res) => {
						// 根据设备类型设置不同的tabbar高度
						this.tabbarHeight = res.platform === 'ios' ? 50 : 48
					}
				})
				// #endif

			},
			getUpdate() {
				const updateManager = uni.getUpdateManager();
				updateManager.onCheckForUpdate(function(res) {
					// 请求完新版本信息的回调
					if (res.hasUpdate) {
						updateManager.onUpdateReady(function() {
							uni.showModal({
								title: '更新提示',
								content: '新版本已经准备好，是否重启应用？',
								success: function(res) {
									if (res.confirm) {
										// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
										updateManager.applyUpdate();
									}
								}
							});
						});

						updateManager.onUpdateFailed(function() {
							// 新的版本下载失败
							uni.showModal({
								title: '已经有新版本了哟~',
								content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
							});
						});
					}
				});
			},
			// 库存弹窗
			inventoryfun(arr) {
				let sum = ''
				arr.map((item, index) => {
					if (Number(item.goodsNum) > Number(item.inventory)) {
						sum += `${item.goodsName} 的库存数量为${item.inventory}<br>`
					}
					return item
				})
				if (sum != '') {
					this.inventoryContent = sum + '请修正数量后重新结算'
					this.inventoryShow = true
					return true
				}
				return false
			},
			clickAddress() {
				this.$u.route('/pages/views/personalInformation/addressManagement');
			},
			async getList() {
				try {

					this.companyValue = []
					this.radiovalue = []
					const res = await shoppingCartList()
					this.companyValueLength = res.data.length
					uni.setTabBarBadge({
						index: 3, // tabIndex，tabBar的哪一项，从0开始
						text: this.companyValueLength.toString() // 显示的文本，超过 99 显示成 “…”
					})
					this.$refs.paging.complete(res.data)
				} catch (e) {
					this.$refs.paging.complete(false)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				}
				this.firstLoad = true
			},
			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'
								});
								_this.getList()
								_this.companyValue = []
							}).catch(err => {
								uni.hideLoading();
							})
						}

					}
				});
			},
			// 立即支付
			submit() {
				if (this.selecteList.length == 0) {
					uni.showToast({
						title: "请先选择要支付的商品",
						icon: 'none'
					});
					return
				}
				if (this.inventoryfun(this.dataList)) {
					uni.showToast({
						title: '当前下单数量超出库存数量，请修改下单数量',
						icon: 'none',
						mask: true,
						duration: 2000
					});
					return
				}
				let obj = {
					address: null,
					payType: null,
					useRecoveredBalance: false,
					shoppingCartList: this.selecteList
				}
				let _this = this
				uni.showModal({
					title: '提示',
					content: '是否生成订单?',
					success: function(res) {
						if (res.confirm) {
							uni.showLoading({
								title: '加载中',
								mask: true
							});
							generateOrder(obj).then(res => {
									uni.showToast({
										title: '下单成功',
										icon: 'none',
										duration: 2000
									});
									// _this.$refs.paging.reload();
									// uni.navigateTo({
									// 	url: '/pages/settlement/index'
									// })
								})
								.finally(() => {
									uni.hideLoading()
								});
						}

					}
				});

			},
			radioGroupChange(e) {
				console.log(e)
				this.radiovalue = e
				if (e.length == 0) {
					this.companyValue = []
				} else {
					for (let li of this.dataList) {
						if (!this.companyValue.includes(li.goodsName)) {
							this.companyValue.push(li.goodsName)
						}
					}
				}
				this.inventoryfun(this.dataList)
				this.cartTotal()
			},
			checkRecovered(e) {
				this.checkRecoveredBalance = e
			},
			statistics(val, index, row) {
				if (val) {
					this.dataList[index].goodsNum = val.value
					console.log(row)
					let obj = {
						id: row.id,
						goodsNum: val.value
					}
					updateNumber(obj)
				}
				this.cartTotal()
			},
			cartTotal() {
				let data = []
				for (let item of this.companyValue) {
					for (let ite of this.dataList) {
						if (item == ite.goodsName) {
							data.push(ite)
						}
					}
				}
				this.selecteList = data
				this.totalPrice = 0
				let num = 0
				for (let item of data) {
					this.totalPrice += Number(item.price) * Number(item.goodsNum)
				}
				this.totalPrice = this.totalPrice.toFixed(2)
			},
			companyChange(n) {
				this.companyValue = n
				this.inventoryfun(this.dataList)
			}
		}
	}
</script>
<style lang="scss" scoped>
	.dynamic-bottom {
		padding-bottom: 40rpx;
	}
	.container {
		// #ifdef H5
		height: calc(100vh - var(--nav-bar, 44px) - var(--tab-bar, 50px) - 124px);
		// #endif
		// #ifdef APP-PLUS
		height: calc(100vh  - 105px);;
		// #endif
		display: flex;
		flex-direction: column;
	}

	.card {
		background: #FFFFFF;
		padding: 32rpx;
		margin: 10rpx 0;

		::v-deep .u-checkbox__icon-wrap {
			border-color: #03803B !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: 0;
		background-color: #fff;
		width: 100%;
		z-index: 10;

		.balance-row {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
			/* 改为flex-start使内容顶部对齐 */
			padding: 20rpx 0;

			.balance-info {
				text-align: right;
				display: flex;
				flex-direction: column;
			}
		}

		.top-row {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 0;

			.select-all {
				flex: 1;
			}

			.total-price {
				flex: 1;
				text-align: right;
			}
		}

		.left-btn {
			background-color: #FFEEE9;
			color: #03803B;
			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: #03803B;
			color: #fff;
			font-size: 26rpx;
			width: 160rpx;
			height: 65rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			// border-top-right-radius: 33rpx;
			// border-bottom-right-radius: 33rpx;
			border-radius: 33rpx;
		}
	}
</style>