<template>
	<u-navbar :is-back="false" title="">
		<template #right>
			<text style="margin-right: 30rpx;" @tap="tapSwitch">
				{{ type === 0 ? '切换产品线' : '返回商品' }}
			</text>
			<text style="margin-right: 30rpx;" @tap="tapDel">{{ administration }}</text>
		</template>
	</u-navbar>
	<view v-if="cartList.length > 0" style="width: 100%; display:flex; margin-top: 10rpx;">
		<u-checkbox-group @change="checkboxGroupChange" style="width: 100%; display:flex">
			<block v-for="(item, index) in cartList" :key="item.id">
				<view v-if="item.isSubmit" class="group-item">
					<u-row class="item">
						<u-col :span="1">
							<u-checkbox
								:name="item.id"
								v-model="item.checked"
								shape="circle"
							></u-checkbox>
						</u-col>
						<u-col :span="3">
							<u-image
								v-if="type === 0"
								width="140rpx"
								height="200rpx"
								:src="baseUrl + item.picUrl"
								class="img"
							></u-image>
						</u-col>
						<u-col
							:span="delCircle ? 7 : 5"
							class="details"
							@tap="
								delCircle
									? () => {
											return;
									  }
									: togoods(item)
							"
						>
							<view>{{ item.goodsName }}</view>
							<view class="b-tag">
								<block
									v-for="(item1, index1) in item.specifications?.length"
									:key="index1"
								>
									<u-tag
										:text="item.specifications[index1]"
										type="info"
										size="mini"
										style="margin: 8rpx 8rpx 8rpx 0;"
									/>
								</block>
							</view>
							<view v-if="item.partList?.length !== 0" class="b-tag">
								<block
									v-for="(item1, index1) in item.partList?.length"
									:key="index1"
								>
									<u-tag
										:text="item.partList[index1]"
										type="warning"
										size="mini"
										style="margin: 8rpx 8rpx 8rpx 0;"
									/>
								</block>
							</view>
						</u-col>
						<u-col v-if="delCircle" :span="1">
							<view class="circle" @tap="deleteCart(index)">
								<view class="horizontal"></view>
							</view>
						</u-col>
						<u-col v-else :span="3" style="margin-top: 20%;">
							<view class="number-box">
								<u-number-box
									v-model="item.number"
									:min="1"
									disabled-input
									@change="valChange($event, item)"
								></u-number-box>
							</view>
						</u-col>
					</u-row>
				</view>
				<!-- 失效商品数据 -->
				<view v-else class="group-item">
					<view class="item">
						<u-row>
							<u-col :span="1">
								<u-checkbox
									:name="item.id"
									:disabled="!item.isSubmit && !delCircle"
									v-model="item.checked"
									shape="circle"
								></u-checkbox>
							</u-col>
							<u-col :span="3">
								<u-image
									v-if="type === 0"
									width="140rpx"
									height="200rpx"
									:src="baseUrl + item.picUrl"
									class="img"
								></u-image>
							</u-col>
							<u-col :span="7">
								<view
									class="details"
									@tap="
										item.deleted
											? () => {
													return;
											  }
											: togoods(item)
									"
								>
									<view>{{ item.goodsName }}</view>
									<view style="color: #ccc; margin-top: 20%;">
										{{ item.message }}
									</view>
								</view>
							</u-col>
							<u-col :span="1">
								<view v-if="delCircle" class="circle" @tap="deleteCart(index)">
									<view class="horizontal"></view>
								</view>
							</u-col>
						</u-row>
					</view>
				</view>
			</block>
		</u-checkbox-group>
	</view>
	<view v-else style="margin-top: 200rpx;"><u-empty text="购物车为空" mode="car" /></view>
	<view style="width: 100%; height: 100rpx;" />
	<view class="footer">
		<view class="left">
			<u-checkbox-group>
				<u-checkbox v-model="checkedAll" @tap="checkboxChange" shape="circle" name="全选">
					全选
				</u-checkbox>
			</u-checkbox-group>
		</view>
		<view class="right">
			<text v-show="!delCircle">总计：</text>
			<text v-show="!delCircle" style="color: red; font-size: 40rpx;">
				￥{{ totalPrice }}
			</text>
			<u-button
				shape="circle"
				size="medium"
				hover-class="#f32329"
				style="background-color: #f32329; margin-left: 20rpx; color: #fff;"
				@tap="tapOptions"
			>
				{{ !delCircle ? '结算' : '删除' }}
			</u-button>
		</view>
	</view>

	<!-- 删除模态框 -->
	<u-modal
		v-model="showModel.show"
		:content="showModel.content"
		:title="showModel.title"
		show-cancel-button
		async-close
		:cancel-text="showModel.cancelText"
		@confirm="onConfirm"
	></u-modal>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { getCartIndex, cartChecked, cartDelete, cartUpdate } from '@/api/cart';
import { onShow } from '@dcloudio/uni-app';
import _ from 'lodash';
import config from '@/utils/config';

let baseUrl = config.baseUrl;

const cartList = ref([] as any); // 购物车数据
const checkedAll = ref(false); // 全选checkbox
const allGoods = ref(); // 购物车列表id
const checkedGoods = ref(); // 购物车列表check为true id
const totalPrice = ref(); // 总价
const delCircle = ref(false); // 控制删除与管理
const administration = ref('管理');
const delIds = ref([] as any); // 删除id
const type = ref(0); // 产品线跟普通商品查询的区别
const showModel = reactive({
	title: '',
	show: false,
	content: '确认删除所选商品吗',
	cancelText: '再想想',
}); // model元素

// 管理
const tapDel = () => {
	if (delCircle.value) {
		initCartIndex(type.value);
		delCircle.value = false;
		administration.value = '管理';
	} else {
		delCircle.value = true;
		administration.value = '退出管理';
	}
};

const tapSwitch = () => {
	if (type.value === 0) {
		type.value = 2;
		initCartIndex(type.value);
	} else {
		type.value = 0;
		initCartIndex(type.value);
	}
};

// 点击购物车列表checkbox
const checkboxGroupChange = (e: any) => {
	let addIds: any = [];
	_.each(e, (v: any) => {
		let ids = _.find(cartList.value, (result: any) => {
			return result.id === v;
		});

		if (ids == undefined) initCartIndex(type.value);
		else addIds.push(ids.id);
	});

	// 取消checkedbox
	let delIds: any = [];
	_.each(_.difference(allGoods.value, e), (v: any) => {
		let ids = _.find(cartList.value, (result: any) => {
			return result.id === v;
		}).id;
		delIds.push(ids);
	});

	if (addIds.length > 0) initCartChecked(1, addIds, type.value);

	if (delIds.length > 0) initCartChecked(0, delIds, type.value);

	if (e.length === allGoods.value.length) checkedAll.value = true;
	else checkedAll.value = false;
};

// 单个删除
const deleteCart = (index: number) => {
	delIds.value.push(cartList.value[index].id);
	showModel.show = true;
};

// 批量操作
const tapOptions = () => {
	// 删除
	if (delCircle.value) {
		delIds.value = [];
		_.each(checkedGoods.value, (id: any) => {
			delIds.value.push(
				_.find(cartList.value, (vv: any) => {
					return id === vv.id;
				}).id
			);
		});
		showModel.show = true;
	} else {
		let flag = cartList.value.every((item: any) => {
			return item.checked === false;
		});
		if (flag)
			return uni.showToast({
				title: '请先选择购买商品',
				icon: 'none',
			});
		// 结算
		let storage: any = {
			cartId: 0,
			addressId: 0,
			couponId: 0,
		};
		Object.keys(storage).forEach((prop: any) => {
			const el: any = storage[prop];
			uni.setStorage({
				key: prop,
				data: el,
				success(res: any) {
					if (prop == 'couponId' && el == 0) {
						if (type.value === 0)
							uni.navigateTo({ url: `../order/checkout?type=` + 'cart' });
						else uni.navigateTo({ url: `../order/checkout?type=` + 'productLineCart' });
					}
				},
			});
		});
	}
};

let togoods = (data: any) => {
	if (type.value === 0)
		uni.navigateTo({ url: '../goods/index?id=' + data.goodsId + '&cartId=' + data.id });
	else
		uni.reLaunch({
			url: '../productLine/productLine?id=' + data.goodsId + '&cartId=' + data.id,
		});
};

// 确认删除
const onConfirm = () => {
	if (delIds.value) {
		if (delIds.value.length === 1) {
			cartDelete({ ids: delIds.value, type: type.value }).then((res: any) => {
				if (res.data.code === 200) {
					delIds.value = [];
					cartList.value = res.data.data.cartList;
					allGoods.value = getAllList();
					checkedGoods.value = getCheckedList(cartList.value);
					totalPrice.value = res.data.data.cartTotal.checkedGoodsAmount.toFixed(2);
					showModel.show = false;
				}
			});
		} else {
			cartDelete({ ids: delIds.value, type: type.value }).then((res: any) => {
				if (res.data.code === 200) {
					delIds.value = [];
					cartList.value = res.data.data.cartList;
					allGoods.value = getAllList();
					checkedGoods.value = getCheckedList(cartList.value);
					totalPrice.value = res.data.data.cartTotal.checkedGoodsAmount.toFixed(2);
					showModel.show = false;
				}
			});
		}
	}
};

// 是否全选
const checkboxChange = () => {
	let ids: any = [];
	_.each(cartList.value, (v: any) => {
		ids.push(v.id);
	});
	if (checkedAll.value) {
		initCartChecked(1, ids, type.value);
		checkedAll.value = true;
	} else {
		initCartChecked(0, ids, type.value);
		checkedAll.value = false;
	}
};

// 商品数量变化
const valChange = (e: any, item: any) => {
	cartUpdate({
		number: e.value,
		goodsId: item.goodsId,
		id: item.id,
		ids: item.ids,
		productId: item.productId,
	}).then((res: any) => {
		if (res.data.code === 200) initCartIndex(type.value);
	});
};

// 初始化数据
const initCartIndex = (type: number) => {
	getCartIndex({ type }).then((res: any) => {
		if (res.data.code === 200) {
			cartList.value = res.data.data.cartList;
			totalPrice.value = res.data.data.cartTotal.checkedGoodsAmount.toFixed(2);
			allGoods.value = getAllList();
			checkedGoods.value = getCheckedList(cartList.value);
			let sort = 0;
			cartList.value.map((item: any) => {
				if (!item.checked) sort += 1;
			});
			if (sort === 0) checkedAll.value = true;
			else checkedAll.value = false;
			sort = 0;
		}
	});
};

// 点击复选框操作
const initCartChecked = (isChecked: number, ids: any, type: number) => {
	cartChecked({ isChecked, ids, type }).then((res: any) => {
		totalPrice.value = res.data.data.cartTotal.checkedGoodsAmount.toFixed(2);
		cartList.value = res.data.data.cartList;
		allGoods.value = getAllList();
		checkedGoods.value = getCheckedList(cartList.value);
	});
};

// 获取所有的id
const getAllList = () => {
	let result: any = [];
	_.each(cartList.value, (v: any) => {
		result.push(v.id);
	});
	return result;
};

// 获取check为true的id
const getCheckedList = (goods: any) => {
	let result: any = [];
	_.each(goods, (v: any) => {
		if (v.checked) {
			result.push(v.id);
		}
	});
	return result;
};

onShow(() => {
	initCartIndex(type.value);
	// type.value = 0;
});
</script>

<style lang="scss" scoped>
.group-item {
	width: 100%;
	padding: 15rpx;
	margin-bottom: 10rpx;
	background-color: #fff;
	.details {
		width: 55%;
		min-height: 200rpx;
		display: flex;
		flex-direction: column;
		align-items: self-start !important;
		margin-left: 20rpx;
		.b-tag {
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
		}
	}
	.circle {
		position: relative;
		display: inline-block;
		width: 36rpx;
		height: 36rpx;
		border-radius: 50%;
		background-color: #f32329;
		margin-right: 20rpx;
		.horizontal {
			position: absolute;
			top: 44%;
			left: 50%;
			width: 24rpx;
			height: 6rpx;
			margin-left: -12rpx;
			margin-bottom: -3rpx;
			border-radius: 4rpx;
			background-color: #fff;
		}
	}
	.number-box {
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
	}
}

.footer {
	position: fixed;
	bottom: var(--window-bottom);
	width: 100%;
	height: 100rpx;
	background-color: #fff;
	padding: 10rpx 40rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 2rpx;
	.left {
		// height: 100%;
	}
	.right {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}
}
</style>
