<template>
	<mobile-frame :frameStyle="frameStyle" @toPath="toPath">
		<view class="main">
			<view class="top" v-if="list.length !=0">
				<view class="text_1">
					<checkbox class="checkbox" @click="selectAll(false)" :checked="isAll">全选</checkbox>
				</view>
				<view class="text_2" v-if="num==0" @click="edit(1)">编辑</view>
				<view class="text_2" v-if="num==1" @click="edit(0)">完成</view>
			</view>
			<view class="one" v-if="!user._id">
				<view class="logo"><text class="iconfont icon-geren2"></text></view>
				<view class="one_1">您还没有登录</view>
				<view class="btn">
					<button type="primary" size="mini" @click="toCommon('/pages/login/index')">去登录</button>
				</view>
			</view>
			<view class="one" v-if="list.length==0&&user._id">
				<view class="logo"><text class="iconfont icon-gouwuche"></text></view>
				<view class="one_1">购物车空空如也~</view>
				<view class="btn">
					<button type="primary" size="mini" @click="toCommon('/pages/home/index')">去逛逛</button>
				</view>
			</view>
			<view class="two" v-if="list.length !=0">
				<scroll-view scroll-y="true" class="scroll-view">
					<view class="list-scroll-view">
						<checkbox-group name="checkbox" @change="marketChange">
							<view class="lists" v-for="(item, index) in list" :key="index">
								<view class="list">
									<view class="title">
										<checkbox :value="item.shop" :checked="item.check">
											<text class="iconfont icon-shangdian"></text>
											{{item.shop_name}}
										</checkbox>
									</view>
									<checkbox-group name="checkbox" @change="goodsChange">
										<view class="content" v-for="gs in item.goods" :key="gs.goodsSpec_id">
											<view class="box">
												<checkbox :value="gs.goodsSpec_id" :checked="gs.check" />
											</view>
											<view class="img">
												<image :src="getFile(gs)"></image>
											</view>
											<view class=" one_1" v-if="num==0" @click="toCommon('/pagesHome/order/detail',gs)">
												<view class="name">{{gs.goods_name}}</view>
												<view class="info">
													<view class="title_1" v-if="gs.goodsSpec_name">
														<text>规格:{{gs.goodsSpec_name}}</text>
													</view>
												</view>
											</view>
											<view class="money" v-if="num==0">
												<view>¥{{gs.money}}</view>
												<view>x{{gs.num}}</view>
											</view>
											<view class="num" v-if="num==1">
												<uni-number-box @change="changeValue(gs)" name="num" value="gs" :min="1" v-model="gs.num" />
											</view>
											<view class="del" v-if="num==1">
												<text class="iconfont icon-del-copy" @click="toDel(gs)"></text>
											</view>
										</view>
									</checkbox-group>
								</view>
							</view>
						</checkbox-group>
					</view>
				</scroll-view>
			</view>
			<view class="foot" v-if="list.length !=0">
				<view class="total">总价：<text>￥{{totalMoney}}(不含运费)</text></view>
				<view class="btn" v-if="hasCheck()">
					<button type="primary" size="mini" @click="toSettle()" v-if="num==0">提交订单</button>
					<button type="primary" size="mini" @click="toDel()" v-if="num==1">删除</button>
				</view>
			</view>
		</view>
	</mobile-frame>
</template>

<script>
	export default {
		data() {
			return {
				frameStyle: {
					useBar: true
				},
				// 用户
				user: {},
				// 购物车列表
				list: [],
				// 全选
				isAll: false,
				// 编辑/完成按钮传的数字
				num: 0,
				// 总额
				totalMoney: 0,
			};
		},
		onLoad: function() {
			const that = this;
			// 监听登录
			that.watchLogin();
		},
		methods: {
			// 监听登录
			watchLogin() {
				const that = this;
				uni.getStorage({
					key: 'token',
					success: (res) => {
						let user = that.$jwt(res.data);
						if (user) {
							that.$set(that, `user`, user)
							that.searchMarket();
						}
					},
					fail: (err) => {}
				})
			},
			// 查询购物车信息
			async searchMarket() {
				const that = this;
				const res = await that.$api(`/cart/selfCart`, 'GET', {
					customer: that.user.id
				});
				if (res.errcode == '0') {
					that.$set(that, `list`, res.data)
				}
			},
			// // 转换金额
			// showMoney(money) {
			// 	const that = this;
			// 	let moneys = `${money}`.split(".");
			// 	if (moneys.length == 1) {
			// 		money = money + ".00";
			// 	} else if (moneys.length == 2) {
			// 		money = money + "0";
			// 	}
			// 	return money;
			// },
			// 编辑
			edit(num) {
				const that = this;
				that.$set(that, `num`, num)
			},
			//全选
			selectAll(e) {
				const that = this;
				const list = that.list;
				const isAll = that.isAll;
				let data = [];
				for (const val of list) {
					let a = isAll ? false : true;
					val.check = a;
					for (let s of val.goods) {
						s.check = a
					}
					data.push(val);
				}
				that.$set(that, `list`, data)
				// 计算总额
				that.countMoney();
				// 赋值是否全选
				that.$set(that, `isAll`, isAll ? false : true)
			},
			// 选择店铺
			marketChange(e) {
				const that = this;
				const list = this.list;
				const {
					value
				} = e.detail;
				for (const p1 of list) {
					let p2 = value.find((i) => i == p1.shop);
					let a = p2 ? true : false;
					p1.check = a;
					for (let s of p1.goods) {
						s.check = a
					}
				}
				that.$set(that, `list`, list);
				that.marketAllChange();
				// 计算总额
				that.countMoney();
			},
			//店铺全部选择true，全选自动选择，
			marketAllChange() {
				const that = this;
				let list = that.list;
				for (let val of list) {
					if (val.check == true) {
						that.$set(that, `isAll`, true)
					} else {
						that.$set(that, `isAll`, false)
					}
				}
				that.$set(that, `list`, list)
				// 计算总额
				that.countMoney();
			},
			//选择商品
			goodsChange(e) {
				const that = this;
				let list = that.list;
				const {
					value
				} = e.detail;
				let shop = list.find(f => f.goods.find(i => value.find(s => s == i.goodsSpec_id)))
				if (shop) {
					for (let val of shop.goods) {
						let p2 = value.find((i) => i == val.goodsSpec_id);
						if (p2) val.check = true;
						else val.check = false;
					}
				} else {
					list = list.map(i => {
						i.goods = i.goods.map(g => ({
							...g,
							check: false
						}))
						return i;
					})
				}
				that.$set(that, `list`, list)
				that.goodsAllChange();
				// 计算总额
				that.countMoney();
			},
			//商品全部选择true，店铺自动选择，
			// 所有店铺为true,则全选为true
			goodsAllChange() {
				const that = this;
				let list = that.list;
				list = list.map(i => {
					const isAllSelect = i.goods.every(f => f.check);
					if (isAllSelect) i.check = true;
					else i.check = false;
					return i;
				})
				const allSelect = list.every(e => e.check)
				if (allSelect) this.$set(this, `isAll`, true)
				else this.$set(this, `isAll`, false)
				// 计算总额
				that.countMoney();
			},
			// 加减商品数量
			async changeValue(value) {
				const that = this;
				this.$nextTick(async () => {
					const {
						goodsSpec_id: goodsSpecId,
						num,
						cart_id: cartId
					} = value
					const res = await that.$api(`/cart/checkGoodsNum`, 'GET', {
						cartId,
						goodsSpecId,
						num
					});
					if (res.errcode === 0) {
						const {
							enough,
							total
						} = res.data
						if (!enough) {
							uni.showToast({
								title: `库存最大为${total}`,
								icon: 'error',
							});
							// 将该商品的库存量修改为最大值
							value.num = total;
						}
					}
					// 计算总额
					that.countMoney();
				})
			},
			// 删除, 接口,购物车删除,然后将该数据移除
			async toDel(e) {
				let list = this.list;
				uni.showModal({
					title: '提示',
					content: '请选择要删除的商品',
					success: async (res) => {
						if (!res.confirm) return
						if (e?.cart_id) {
							const result = await this.$api(`/cart/${e.cart_id}`, 'Delete');
							if (result.errcode === 0) {
								list = list.map(i => ({
									...i,
									goods: i.goods.filter(f => f.cart_id !== e.cart_id)
								}))
								this.$set(this, `list`, list);
								// 检查店铺内是否还有商品
								this.checkShopGoodsExist();
								// 计算总额
								this.countMoney();
							}
						} else {
							const goodsList = list.map(i => i.goods).flat();
							const cartIds = goodsList.filter(i => i.check).map(i => i.cart_id)
							for (let val of cartIds) {
								const result = await this.$api(`/cart/${val}`, 'Delete');
								if (result.errcode === 0) {
									list = list.map(i => ({
										...i,
										goods: i.goods.filter(f => f.cart_id !== val)
									}))
									this.$set(this, `list`, list);
									// 检查店铺内是否还有商品
									this.checkShopGoodsExist();
									// 计算总额
									this.countMoney();
								}
							}
						}
					}
				});
			},
			//检查店铺内是否还有商品
			checkShopGoodsExist() {
				let list = this.list;
				list = list.filter(f => f.goods && f.goods.length > 0)
				this.$set(this, `list`, list);
			},
			// 计算总额
			countMoney() {
				const that = this;
				const list = this.list;
				let totalMoney = 0;
				// 渲染结束执行下面方法
				that.$nextTick(() => {
					for (const val of list) {
						for (let s of val.goods) {
							if (s.check == true) {
								let total = Number(s.money) * Number(s.num);
								totalMoney += Number(total);
							}
						}
					}
					that.$set(that, `totalMoney`, totalMoney.toFixed(2))
				})
			},
			getFile(data) {
				const file = data.file;
				if (!file) return '';
				if (file.length && file.length > 0) return file[0].url
			},
			// 去结算
			async toSettle() {
				// 将选中的购物车放到数组中,传回服务端进行检查.然后拿着key去订单页请求数据
				const goodsList = this.list.map(i => i.goods).flat();
				const cartIds = goodsList.filter(i => i.check).map(i => i.cart_id)
				const res = await this.$api(`/util/checkCartBuy`, 'POST', {
					cartIds
				});
				if (res.errcode == '0') {
					const {
						data
					} = res
					if (data.result) {
						const key = data.key;
						uni.navigateTo({
							url: `/pagesHome/order/order?key=${key}`
						})
					}
				}
			},
			// 是否选中商品,控制提交订单按钮
			hasCheck() {
				return this.list.some(e => e.goods.some(eg => eg.check))
			},
			// 公共跳转
			toCommon(route, e) {
				uni.navigateTo({
					url: `${route}?id=${e && e.goods_id}`
				})
			},
			toPath(e) {
				let url = `/${e.route}`;
				if (e.type == '0') uni.redirectTo({
					url
				})
				else {
					uni.navigateTo({
						url
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.main {
		display: flex;
		flex-direction: column;
		width: 100vw;
		height: 92vh;
		background-color: var(--footColor);

		.top {
			display: flex;
			flex-direction: row;
			background-color: var(--mainColor);
			height: 35px;
			margin: 0 0 4px 0;
			padding: 5px 4vw;

			.text_1 {
				flex-grow: 1;
				line-height: 30px;
			}

			.text_2 {
				line-height: 35px;
			}
		}

		.one {
			text-align: center;
			margin: 2vw 0;

			.logo {
				margin: 10vw 0 2vw 0;

				.iconfont {
					font-size: 35vw;
				}
			}

			.one_1 {
				margin: 3vw 0;
			}

			button {
				background-color: var(--ff0Color);
			}
		}

		.two {
			position: relative;
			flex-grow: 1;
			margin: 0 2vw;

			.list {
				background-color: var(--mainColor);
				margin: 2vw 0 2vw 0;
				padding: 2vw 3vw;
				border-radius: 4px;

				.title {
					border-bottom: 1px solid var(--fcColor);
					padding: 0 0 2vw 0;
					font-size: var(--font18Size);

					text {
						margin: 0 1vw;
					}
				}

				.content {
					display: flex;
					flex-direction: row;
					padding: 3vw 0;
					font-size: var(--font16Size);
					border-bottom: 1px dashed var(--fcColor);

					.box {
						line-height: 20vw;
					}

					.img {
						width: 20vw;
						height: 20vw;
						border-radius: 2vw;
						border: 1px solid var(--fcColor);

						image {
							width: 20vw;
							height: 20vw;
						}
					}

					.one_1 {
						margin: 2.5vw;
						flex-grow: 1;

						.info {
							width: 100%;
							display: flex;
							flex-direction: row;

							.title_1 {
								font-size: 12px;
								color: #666;
								margin-top: 10px;

								text {
									background-color: #eee;
									padding: 5px;
								}
							}
						}
					}

					.money {
						margin-top: 2vw;
						text-align: right;
						flex-grow: 1;
					}

					.num {
						margin: 6vw 4vw;
						font-size: 20px;
					}

					.del {
						margin: 6vw 0;
						text-align: right;
						flex-grow: 1;
					}
				}
			}
		}

		.foot {
			background-color: var(--fffColor);
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			height: 44px;
			padding: 0 0 0 6vw;
			border-right: 1px solid var(--f99Color);

			.total {
				flex-grow: 1;
				display: flex;
				align-content: flex-end;
				line-height: 40px;

				text {
					color: var(--ff0Color);
				}
			}

			.btn {
				button {
					width: 30vw;
					height: 44px;
					line-height: 44px;
					border-radius: 0px;
					background-color: var(--ff0Color);
					text-align: center;
					font-weight: normal;
					font-size: var(--font15Size);
					color: var(--fffColor);
				}
			}
		}
	}

	.scroll-view {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;

		.list-scroll-view {
			display: flex;
			flex-direction: column;
		}
	}

	// 复选框样式
	checkbox .wx-checkbox-input {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		border-color: var(--f99Color);
		background-color: var(--mainColor);
	}

	// 复选框选中样式
	checkbox .wx-checkbox-input.wx-checkbox-input-checked {
		border-color: var(--ff0Color);
		background-color: var(--ff0Color);
	}

	// 复选框选中之后对号的样式
	checkbox .wx-checkbox-input.wx-checkbox-input-checked::before {
		color: var(--fffColor);
	}
</style>
