<template>
	<view>
		<view class="header">
			<view class="searchBox" :style="{ height: localHeight + 'px', paddingTop: top + 'px' }">
				<view class="searchBox_left" @click="back">
					<u-icon name="arrow-left" size="20px" color="#000"></u-icon>
				</view>
				<view class="searchBox_mid">购物车({{ shopCarTotal }})</view>
				<view class="searchBox_right">
					<u-icon name="arrow-left" size="20px" color="#000"></u-icon>
				</view>
			</view>
		</view>
		<view class="empty" v-if="shopCarTotal == 0">
			<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/shopCar_no.png"></image>
		</view>
		<view class="main" v-else>
			<view class="deleteIcon" @click="deleteItem">
				<u-icon name="trash" size="50rpx"></u-icon>
			</view>
			<view class="is_day " v-if="isDayshow">
				<view class="footer_all" @click="is_day_checked"
					style="color: orange; font-size: 35rpx; font-weight: bolder;">
					<image v-if="!isDaychecked"
						src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check1.png">
					</image>
					<image v-if="isDaychecked"
						src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check2.png">
					</image>
					当日达
				</view>
				<view class="goodsList">
					<view v-for="(carItem, carIndex) in isDayCarList" :key="carItem.id" :index="carIndex">
						<view class="goodsItem_supplier">
							<view class="goodsItem_left" @click="supplierCheck(carItem, true)">
								<image v-if="!carItem.supplierChecked"
									src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check1.png">
								</image>
								<image v-if="carItem.supplierChecked"
									src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check2.png">
								</image>
							</view>
							<view class="goodsItem_tit">
								{{ carItem.supplier_name }}
							</view>
						</view>
						<view class="goodsItem" v-for="(item, index) in carItem.commodity_cart_and_goods_model"
							:key="item.id">
							<view class="goodsItem_left" @click="DayChecked(item)">
								<image v-if="!item.checked"
									src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check1.png">
								</image>
								<image v-if="item.checked"
									src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check2.png">
								</image>
							</view>
							<view class="goodsItem_right">
								<view class="goodsItem_msg">
									<view class="goodsItem_msg_img">
										<view class="tag tag-img">当日达</view>
										<image :src="picUrl + item.commodity_goods_info.commodity_pic">
										</image>
									</view>
									<view class="goodsItem_msg_right">
										<view class="goodsItem_msg_right_tit">
											{{ item.commodity_goods_info.goods_name }}
										</view>
										<view class="goodsItem_msg_right_subTit">
											{{ item.commodity_goods_info.goods_intro }}
										</view>
										<view class="goodsItem_msg_right_msg">
											<view class="goodsItem_msg_right_msg_left">
												<span>￥</span>{{ item.commodity_goods_info.group_buy_price ?
													item.commodity_goods_info.group_buy_price :
													item.commodity_goods_info.sales_price }}
												<span>/{{ item.commodity_goods_info.goods_unit }}</span>
											</view>
											<view class="goodsItem_msg_right_msg_right">
												<u-number-box v-model="item.count" :asyncChange="true" min="0">
													<view slot="minus" class="minus"
														@click="minus(carItem, index, carItem.commodity_cart_and_goods_model)">
														<u-icon name="minus" size="32" bold></u-icon>
													</view>
													<text slot="input" style="width: 80rpx; text-align: center"
														class="input">{{ item.count }}</text>
													<view slot="plus" class="plus" @click="add(carItem, index)">
														<u-icon name="plus" color="#FFFFFF" size="32" bold></u-icon>
													</view>
												</u-number-box>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="is_day" v-if="parcelPostshow" style="margin-top: 20rpx;">
				<view class="footer_all" @click="parcel_post_checked"
					style="color: orange; font-size: 35rpx; font-weight: bolder;">
					<image v-if="!isParcelPostchecked"
						src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check1.png">
					</image>
					<image v-if="isParcelPostchecked"
						src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check2.png">
					</image>
					包邮
				</view>
				<view class="goodsList">
					<view v-for="(carItem, carIndex) in shopCarList" :key="carItem.id" :index="carIndex">
						<view class="goodsItem_supplier">
							<view class="goodsItem_left" @click="supplierCheck(carItem, false)">
								<image v-if="!carItem.supplierChecked"
									src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check1.png">
								</image>
								<image v-if="carItem.supplierChecked"
									src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check2.png">
								</image>
							</view>
							<view class="goodsItem_tit">
								{{ carItem.supplier_name }}
							</view>
						</view>
						<view class="goodsItem" v-for="(item, index) in carItem.commodity_cart_and_goods_model"
							:key="item.id">
							<view class="goodsItem_left" @click="changeChecked(item)">
								<image v-if="!item.checked"
									src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check1.png">
								</image>
								<image v-if="item.checked"
									src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check2.png">
								</image>
							</view>
							<view class="goodsItem_right">
								<view class="goodsItem_msg">
									<view class="goodsItem_msg_img">
										<image :src="picUrl + item.commodity_goods_info.commodity_pic">
										</image>
									</view>
									<view class="goodsItem_msg_right">
										<view class="goodsItem_msg_right_tit">
											{{ item.commodity_goods_info.goods_name }}
										</view>
										<view class="goodsItem_msg_right_subTit">
											{{ item.commodity_goods_info.goods_intro }}
										</view>
										<view class="goodsItem_msg_right_msg">
											<view class="goodsItem_msg_right_msg_left">
												<span>￥</span>{{ item.commodity_goods_info.group_buy_price ?
													item.commodity_goods_info.group_buy_price :
													item.commodity_goods_info.sales_price }}
												<span>/{{ item.commodity_goods_info.goods_unit }}</span>
											</view>
											<view class="goodsItem_msg_right_msg_right">
												<u-number-box v-model="item.count" :asyncChange="true" min="0">
													<view slot="minus" class="minus"
														@click="minus(item, index, carItem.commodity_cart_and_goods_model)">
														<u-icon name="minus" size="32" bold></u-icon>
													</view>
													<text slot="input" style="width: 80rpx; text-align: center"
														class="input">{{ item.count }}</text>
													<view slot="plus" class="plus" @click="add(item, index)">
														<u-icon name="plus" color="#FFFFFF" size="32" bold></u-icon>
													</view>
												</u-number-box>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="footer">
				<view class="footer_left">
					<view class="footer_all" @click="allChecked">
						<image v-if="!isAllchecked"
							src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check1.png">
						</image>
						<image v-if="isAllchecked"
							src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check2.png">
						</image>
						全选
					</view>
					<view class="footer_total">
						<span>合计</span>
						￥{{ shopMoney }}
					</view>
				</view>
				<view class="footer_right" @click="submitOrder">结算</view>
			</view>
		</view>


	</view>
</template>

<script>
import {
	apiArr
} from "../../../api/shop";
import {
	picUrl,
	menuButtonInfo,
	request,
	NavgateTo
} from "../../../utils";
export default {
	data() {
		return {
			picUrl,
			top: "",
			localHeight: "",
			value: 3,
			type: "error",
			shopCarList: [],
			isDayCarList: [],
			shopCarTotal: 0,
			shopMoney: 0,
			isAllchecked: false, // 全选
			isDaychecked: false, // 当日达
			isDayshow: false,
			isParcelPostchecked: false,
			parcelPostshow: false,

		};
	},
	// watch: {
	// 	// console.log(this.isDaychecked);
	// 	isDaychecked(e) {
	// 		console.log('当日达状态', e);
	// 	},
	// 	isParcelPostchecked(e) {
	// 		console.log('包邮状态', e);
	// 	}
	// 	isAllchecked(e) {
	// 		console.log('全选状态', e);
	// 	}
	// },
	methods: {
		back() {
			NavgateTo("1");
		},

		// 商家单选框全选/取消全选
		supplierCheck(carItem, isDay) {
			carItem.supplierChecked = !carItem.supplierChecked;
			carItem.commodity_cart_and_goods_model.forEach(goods => {
				goods.checked = carItem.supplierChecked;
			});
			this.calcTotal();

			// 更新当日达或包邮全选状态
			if (isDay) {
				this.isDaychecked = this.isDayCarList.every(item =>
					item.commodity_cart_and_goods_model.every(goods => goods.checked)
				);
			} else {
				this.isParcelPostchecked = this.shopCarList.every(item =>
					item.commodity_cart_and_goods_model.every(goods => goods.checked)
				);
			}

			// 更新全选状态
			this.isAllchecked = this.isDaychecked && this.isParcelPostchecked;
		},

		// 结算
		submitOrder() {
			let arr = [];
			// 收集包邮购物车中选中的商品
			this.shopCarList.forEach((item) => {
				item.commodity_cart_and_goods_model.forEach((ite) => {
					if (ite.checked) {
						ite.supplier_name = item.supplier_name;
						arr.push(ite);
					}
				})
			});
			// 收集当日达购物车中选中的商品
			this.isDayCarList.forEach((item) => {
				item.commodity_cart_and_goods_model.forEach((ite) => {
					if (ite.checked) {
						ite.supplier_name = item.supplier_name;
						arr.push(ite);
					}
				})
			});

			// NavgateTo(`../submitOrder/index?shopCarList=${JSON.stringify(arr)}`);
			NavgateTo(`../groupPurchaseSubmit/index?shopCarList=${JSON.stringify(arr)}`);
		},

		// 获取购物车列表
		getShopCar() {
			request(apiArr.getCar, "POST", {}).then((res) => {
				if (res.normal_cart_list.length > 0) {
					res.normal_cart_list.forEach((item) => {
						item.checked = false;
						item.supplierChecked = false;
					})
					this.parcelPostshow = true;
					this.shopCarList = res.normal_cart_list
				} else {
					res.normal_cart_list.forEach((item) => {
						item.checked = false;
						item.supplierChecked = false;
					})
					this.parcelPostshow = false;
					this.shopCarList = []
				}

				if (res.same_day_cart_list.length > 0) {
					res.same_day_cart_list.forEach((item) => {
						item.checked = false;
						item.supplierChecked = false;
					})
					this.isDayshow = true;
					this.isDayCarList = res.same_day_cart_list
				} else {
					res.normal_cart_list.forEach((item) => {
						item.checked = false;
						item.supplierChecked = false;
					})
					this.isDayshow = false;
					this.isDayCarList = []
				}

				// res.normal_cart_list.forEach((item) => {
				// 	if (item.is_support_same_day == false) {
				// 		this.isDayshow = false;
				// 		this.parcelPostshow = true;
				// 		this.shopCarList = item.commodity_cart_and_goods_model;
				// 		item.checked = false;
				// 	} else {
				// 		this.isDayshow = true;
				// 		this.parcelPostshow = false;
				// 		this.isDayCarList = item.commodity_cart_and_goods_model;
				// 		item.checked = false;
				// 	}
				// });

				this.shopCarTotal = res.total;
			});
		},

		// 单个修改
		changeChecked(item) {
			item.checked = !item.checked;
			this.calcTotal();

			// 找到对应的商家并更新商家选中状态
			this.shopCarList.forEach(carItem => {
				if (carItem.commodity_cart_and_goods_model.includes(item)) {
					carItem.supplierChecked = carItem.commodity_cart_and_goods_model.every(goods => goods.checked);
				}
			});

			// 检查当日达是否全选
			this.isDaychecked = this.isDayCarList.every(carItem =>
				carItem.commodity_cart_and_goods_model.every(goods => goods.checked)
			);
			// 检查包邮是否全选
			this.isParcelPostchecked = this.shopCarList.every(carItem =>
				carItem.commodity_cart_and_goods_model.every(goods => goods.checked)
			);
			// 检查全选状态
			this.isAllchecked = this.isDaychecked && this.isParcelPostchecked;
		},
		DayChecked(item) {
			item.checked = !item.checked;
			this.calcTotal();

			// 找到对应的商家并更新商家选中状态
			this.isDayCarList.forEach(carItem => {
				if (carItem.commodity_cart_and_goods_model.includes(item)) {
					carItem.supplierChecked = carItem.commodity_cart_and_goods_model.every(goods => goods.checked);
				}
			});

			// 检查当日达是否全选
			this.isDaychecked = this.isDayCarList.every(carItem =>
				carItem.commodity_cart_and_goods_model.every(goods => goods.checked)
			);
			// 检查包邮是否全选
			this.isParcelPostchecked = this.shopCarList.every(carItem =>
				carItem.commodity_cart_and_goods_model.every(goods => goods.checked)
			);
			// 检查全选状态
			this.isAllchecked = this.isDaychecked && this.isParcelPostchecked;
		},
		// 全选
		allChecked() {
			this.isAllchecked = !this.isAllchecked;
			this.isDaychecked = this.isAllchecked;
			this.isParcelPostchecked = this.isAllchecked;

			// 设置当日达购物车商品和商家选中状态
			this.isDayCarList.forEach(carItem => {
				carItem.supplierChecked = this.isAllchecked;
				carItem.commodity_cart_and_goods_model.forEach(goods => {
					goods.checked = this.isAllchecked;
				});
			});

			// 设置包邮购物车商品和商家选中状态
			this.shopCarList.forEach(carItem => {
				carItem.supplierChecked = this.isAllchecked;
				carItem.commodity_cart_and_goods_model.forEach(goods => {
					goods.checked = this.isAllchecked;
				});
			});

			this.calcTotal();
		},

		// 全选当日达
		is_day_checked() {
			this.isDaychecked = !this.isDaychecked;

			// 设置当日达购物车商品和商家选中状态
			this.isDayCarList.forEach(carItem => {
				carItem.supplierChecked = this.isDaychecked;
				carItem.commodity_cart_and_goods_model.forEach(goods => {
					goods.checked = this.isDaychecked;
				});
			});

			// 更新全选状态
			this.isAllchecked = this.isDaychecked && this.isParcelPostchecked;

			this.calcTotal();
		},

		// 全选包邮
		parcel_post_checked() {
			this.isParcelPostchecked = !this.isParcelPostchecked;

			// 设置包邮购物车商品和商家选中状态
			this.shopCarList.forEach(carItem => {
				carItem.supplierChecked = this.isParcelPostchecked;
				carItem.commodity_cart_and_goods_model.forEach(goods => {
					goods.checked = this.isParcelPostchecked;
				});
			});

			// 更新全选状态
			this.isAllchecked = this.isDaychecked && this.isParcelPostchecked;

			this.calcTotal();
		},

		// 计算金额
		calcTotal() {
			let total = 0;

			// 计算当日达购物车金额
			this.isDayCarList.forEach(carItem => {
				carItem.commodity_cart_and_goods_model.forEach(goods => {
					if (goods.checked) {
						const price = goods.commodity_goods_info.group_buy_price !== undefined && goods.commodity_goods_info.group_buy_price !== null ?
							goods.commodity_goods_info.group_buy_price :
							goods.commodity_goods_info.sales_price;
						total += price * goods.count;
					}
				});
			});

			// 计算包邮购物车金额
			this.shopCarList.forEach(carItem => {
				carItem.commodity_cart_and_goods_model.forEach(goods => {
					if (goods.checked) {
						const price = goods.commodity_goods_info.group_buy_price !== undefined && goods.commodity_goods_info.group_buy_price !== null ?
							goods.commodity_goods_info.group_buy_price :
							goods.commodity_goods_info.sales_price;
						total += price * goods.count;
					}
				});
			});

			this.shopMoney = total;
		},

		// 减少数量
		minus(carItem, goodsIndex, item) {
			let that = this;

			if (carItem.count > 0) {
				if (carItem.count == carItem.commodity_goods_info.min_order_quantity) {
					uni.showToast({
						title: '最少购买' + carItem.commodity_goods_info.min_order_quantity + '件',
						icon: 'none'
					});
					request(apiArr.deleteCar, "POST", {
						ids: [carItem.id],
					}).then((res) => {
						item.splice(goodsIndex, 1);
						// 如果商家没有商品了，移除该商家
						if (item.length === 0) {
							const carIndex = this.shopCarList.indexOf(carItem);
							if (carIndex == -1) {
								this.shopCarList.splice(carIndex, 1);
							}
						}
						that.calcTotal();
						that.shopCarTotal = that.shopCarTotal - 1;
					});
					carItem.count = 0
					that.shopCarTotal = that.shopCarTotal - carItem.commodity_goods_info.min_order_quantity;
				} else {
					this.shopCarTotal = this.shopCarTotal - 1;
					carItem.count = carItem.count - 1;
					this.handleQuantityChange(carItem.count, carItem);
				}
				this.calcTotal();
			}
		},

		// 添加数量
		add(carItem, goodsIndex) {
			if (carItem.count == 0) {
				carItem.count = carItem.commodity_goods_info.min_order_quantity
				this.shopCarTotal += carItem.commodity_goods_info.min_order_quantity;
			} else {
				if (carItem.count == carItem.commodity_goods_info.total_stock) {
					uni.showToast({
						title: '库存不足',
						icon: 'none'
					});
					return
				}
				if (carItem.count == carItem.commodity_goods_info.max_limit_quantity) {
					uni.showToast({
						title: '一次最多购买' + carItem.commodity_goods_info.max_limit_quantity + '件',
						icon: 'none'
					});
					return
				}
				carItem.count++;
				this.shopCarTotal++;
			}

			const item = carItem.commodity_cart_and_goods_model;
			this.handleQuantityChange(carItem.count, carItem);
			this.calcTotal();
		},

		// 删除
		deleteItem() {
			let that = this;
			uni.showModal({
				title: "提示",
				content: "确定删除所选商品吗",
				success: function (res) {
					if (res.confirm) {
						let ids = [];

						// 收集当日达购物车中选中的商品ID
						that.isDayCarList.forEach(carItem => {
							carItem.commodity_cart_and_goods_model.forEach(goods => {
								if (goods.checked) {
									ids.push(goods.id);
									goods.checked = false;
								}
							});
						});

						// 收集包邮购物车中选中的商品ID
						that.shopCarList.forEach(carItem => {
							carItem.commodity_cart_and_goods_model.forEach(goods => {
								if (goods.checked) {
									ids.push(goods.id);
									goods.checked = false;
								}
							});
						});

						if (ids.length === 0) {
							uni.showToast({
								title: "请选择要删除的商品",
								icon: "none",
								duration: 2000,
							});
							return;
						}

						request(apiArr.deleteCar, "POST", {
							ids,
						})
							.then((res) => {
								uni.showToast({
									title: "删除成功",
									duration: 2000,
								});
								that.getShopCar();
								that.calcTotal();
							})
							.catch((err) => {
								console.log(err);
							});
					} else if (res.cancel) {
						console.log("用户点击取消");
					}
				},
			});
		},
		//商品数量变化
		handleQuantityChange(val, item) {
			const params = {
				user_id: uni.getStorageSync("userId"),
				goods_id_and_count: [{
					goods_id: item.goods_id,
					count: val,
				},],
			};
			request(apiArr.updateCar, "POST", params).then((res) => {
				console.log(res);
				uni.showToast({
					title: "操作成功！",
					success() { },
				});
				return Promise.resolve();
			});
		},
	},

	onLoad(options) {
		const meun = menuButtonInfo();
		this.top = meun.top;
		this.localHeight = meun.height;
		this.getShopCar();
	},
	onReachBottom() { },


};
</script>

<style>
@import url("./index.css");
</style>