<template>
	<view class="main">
		<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-else>
			<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="thr" v-if="list.length!=0&&user._id">
			<scroll-view scroll-y="true" class="scroll-view">
				<view class="list-scroll-view">
					<checkbox-group name="checkbox" @change="marketChange">
						<view class="list" v-for="(item, index) in list" :key="index">
							<view class="list_1">
								<view class="title">
									<checkbox :value="item.supplier._id" :checked="item.check">
										<text class="iconfont icon-shangdian"></text>
										{{item.supplier.name}}
									</checkbox>
								</view>
								<view v-for="gs in item.list" :key="gs.specs._id">
									<checkbox-group name="checkbox" @click="goodsChange(gs)">
										<view class="content">
											<view class="box">
												<checkbox :value="gs.cart_id" :checked="gs.check" />
											</view>
											<view class="img">
												<image :src="getFile(gs)"></image>
											</view>
											<view class="thr_1" v-if="num==0"
												@click="toCommon('/pagesGoods/index/index',gs)">
												<view class="left">
													<view class="name textOver">{{gs.goods.name}}</view>
													<view class="other">
														<view class="money" v-if="num==0">
															<view>¥{{gs.money}}</view>
															<view>x{{gs.num}}</view>
														</view>
													</view>
												</view>
												<view class="right">
													<view class="title_1 textOver" v-if="gs.specs.name">
														<text>规格:{{gs.specs.name}}</text>
													</view>
												</view>
											</view>
											<view class="num" v-if="num==1">
												<uni-number-box @change="changeValue(gs)" name="num" value="gs" :min="1"
													:max="gs.specs.num" v-model="gs.num" />
											</view>
											<view class="del" v-if="num==1">
												<text class="iconfont icon-icon-cross-empty" @click="toDel(gs)"></text>
											</view>
										</view>
									</checkbox-group>
								</view>
							</view>
						</view>
					</checkbox-group>
				</view>
			</scroll-view>
		</view>
		<view class="foot" v-if="list.length!=0&&user._id">
			<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>
</template>

<script>
	export default {
		data() {
			return {
				// 用户
				user: {},
				// 购物车列表
				list: [],
				// 全选
				isAll: false,
				// 编辑/完成按钮传的数字
				num: 0,
				// 总额
				totalMoney: 0,
			}
		},
		onShow() {
			const that = this;
			that.clearPages();
			that.searchToken();
		},
		methods: {
			searchToken() {
				const that = this;
				try {
					const res = uni.getStorageSync('token');
					if (res) {
						that.$set(that, `user`, res);
						that.searchMarket();
					}
				} catch (e) {
					uni.showToast({
						title: err.errmsg,
						icon: 'error',
						duration: 2000
					});
				}
			},
			// 查询购物车信息
			async searchMarket() {
				const that = this;
				const res = await that.$api(`/Cart/self`, 'GET', {
					user: that.user._id
				});
				if (res.errcode == '0') that.$set(that, `list`, res.data)
			},
			// 编辑
			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.list) {
						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 = that.list;
				const {
					value
				} = e.detail;
				for (const p1 of list) {
					let p2 = value.find((i) => i == p1.supplier._id);
					let a = p2 ? true : false;
					p1.check = a;
					for (let s of p1.list) {
						s.check = a
					}
				}
				that.$set(that, `list`, list);
				that.marketAllChange();
				// 计算总额
				that.countMoney();
			},
			//店铺全部选择true，全选自动选择，
			marketAllChange() {
				const that = this;
				let list = that.list;
				let check = list.find((i) => i.check == false);
				if (check) that.$set(that, `isAll`, false)
				else that.$set(that, `isAll`, true)
				that.$set(that, `list`, list)
				// 计算总额
				that.countMoney();
			},
			//选择商品
			goodsChange(e) {
				const that = this;
				let list = that.list;
				for (let val of list) {
					for (let as of val.list) {
						if (e.cart_id == as.cart_id) as.check = !as.check;
					}
				}
				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.list.every(f => f.check);
					if (isAllSelect) i.check = true;
					else i.check = false;
					return i;
				})
				const allSelect = list.every(e => e.check)
				if (allSelect) that.$set(that, `isAll`, true)
				else that.$set(that, `isAll`, false)
				// 计算总额
				that.countMoney();
			},
			// 加减商品数量
			async changeValue(value) {
				const that = this;
				let user = that.user;
				let list = that.list;
				let goodsList = [];
				if (user && user._id) {
					that.$nextTick(async () => {
						let res;
						const obj = {
							num: value.num,
							total_money: that.$multiply(value.specs.money, value.num)
						}
						res = await that.$api(`/Cart/${value.cart_id}`, 'POST', obj)
						if (res.errcode == '0') {
							goodsList = list.map(i => ({
								...i,
								list: i.list.map(f => {
									if (f.cart_id == value.cart_id) {
										f.num = obj.num
										f.total_money = obj.total_money
									}
									return f
								})
							}))
							that.$set(that, `list`, goodsList)
						} else {
							uni.showToast({
								title: res.errmsg,
								icon: 'none'
							})
						}
						// 计算总额
						that.countMoney();
					})
				} else {
					uni.navigateTo({
						url: `/pages/login/index`
					})
				}
			},
			// 删除, 接口,购物车删除,然后将该数据移除
			async toDel(e) {
				const that = this;
				let list = that.list;
				uni.showModal({
					title: '提示',
					content: '请选择要删除的商品',
					success: async (res) => {
						if (!res.confirm) return
						if (e?.cart_id) {
							const result = await that.$api(`/Cart/${e.cart_id}`, 'Delete');
							if (result.errcode === 0) {
								that.searchMarket();
								// 计算总额
								that.countMoney();
							}
						} else {
							let cartIds = [];
							for (let val of list) {
								for (let s of val.list) {
									if (s.check) cartIds.push(s.cart_id)
								}
							}
							const result = await that.$api(`/Cart/deleteMany`, 'Delete', {
								cartIds
							});
							if (result.errcode === 0) {
								that.searchMarket();
								// 计算总额
								that.countMoney();
							}
						}
					}
				});
			},
			// 计算总额
			countMoney() {
				const that = this;
				const list = that.list;
				let totalMoney = 0;
				// 渲染结束执行下面方法
				that.$nextTick(() => {
					for (const val of list) {
						for (let as of val.list) {
							if (as.check == true) {
								let total = that.$multiply(as.money, as.num);
								totalMoney += Number(total);
							}
						}
					}
					that.$set(that, `totalMoney`, totalMoney.toFixed(2))
				})
			},
			// 显示图片处理
			getFile(data) {
				let file
				if (data.specs.file && data.specs.file.length > 0) file = data.specs.file
				else file = data.goods.file;
				if (!file) return '';
				if (file.length && file.length > 0) return file[0].url
			},
			// 去结算
			async toSettle() {
				const that = this;
				let list = that.list;
				const user = that.user;
				if (user && user._id) {
					if (user.role == 'jdry' || user.role == 'sqry') {
						let cartIds = [];
						for (let val of list) {
							for (let s of val.list) {
								if (s.check) cartIds.push(s.cart_id)
							}
						}
						uni.showModal({
							title: '提示',
							content: '是否确定要提交？',
							success: async (arr) => {
								if (!arr.confirm) return
								const res = await that.$api(`/Cart/checkCartBuy`, 'POST', {
									cartIds,
									totalMoney: that.totalMoney
								});
								if (res.errcode == '0') {
									uni.navigateTo({
										url: `/pagesMy/order/index?status=${'0'}`
									})
								} else {
									uni.showToast({
										title: res.errmsg,
										icon: 'none'
									})
								}
							}
						});
					} else {
						uni.showToast({
							title: '角色不匹配 无法进行结算！',
							icon: 'none'
						})
					}

				} else {
					uni.navigateTo({
						url: `/pages/login/index`
					})
				}

			},
			// 是否选中商品,控制提交订单按钮
			hasCheck() {
				const that = this;
				return that.list.some(e => e.list.some(eg => eg.check))
			},
			// 清空总信息
			clearPages() {
				const that = this;
				that.$set(that, `list`, [])
				that.$set(that, `isAll`, false)
				that.$set(that, `totalMoney`, 0)
				that.$set(that, `num`, 0)
			},
			// 公共跳转
			toCommon(route, e) {
				if (e) {
					uni.navigateTo({
						url: `${route}?id=${e && e.goods._id}`
					})
				} else {
					uni.reLaunch({
						url: `${route}`
					})
				}
			},
		}
	}
</script>

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

		.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(--f3CColor);
			}
		}

		.two {
			display: flex;
			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;
			}
		}

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

			.list_1 {
				background-color: var(--mainColor);
				margin: 2vw 0;
				padding: 2vw 2.5vw;
				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;
					padding: 2vw 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;
						}
					}

					.thr_1 {
						width: 60vw;
						margin: 0 0 0 2vw;

						.left {
							display: flex;
							justify-content: space-between;

							.other {
								margin: 0 2vw;

								.money {
									text-align: right;
									flex-grow: 1;
								}
							}
						}

						.right {
							margin: 2vw 0 0 0;

							.title_1 {
								font-size: var(--font12Size);
								color: #666;


								text {
									white-space: nowrap;
									overflow: hidden;
									text-overflow: ellipsis;
									background-color: #eee;
									padding: 5px;
								}
							}
						}
					}

					.num {
						margin: 6vw 4vw;
						font-size: var(--font20Size);
					}

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

		.foot {
			background-color: var(--fffColor);
			display: flex;
			justify-content: space-between;
			height: 45px;
			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(--f3CColor);
				}
			}

			.btn {
				button {
					width: 30vw;
					height: 45px;
					line-height: 45px;
					border-radius: 0px;
					background-color: var(--f3CColor);
					font-weight: normal;
				}
			}
		}
	}

	.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(--f3CColor);
		background-color: var(--f3CColor);
	}

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