<template>
	<view style="width: 100%; height: 100vh;">
		<u-navbar
			:is-back="false"
			title="产品线"
			:background="{ background: '#f8f8f8' }"
			title-bold
			title-color="#000"
		>
			<template #right>
				<view style="margin-right: 30rpx" @tap="reset">重置</view>
			</template>
		</u-navbar>
		<view class="u-wrap">
			<view class="u-menu-wrap">
				<view style="position: fixed; left: 8rpx; top: 6%;">
					<drag-and-drop-sort
						v-if="flag"
						ref="dragRef"
						style="display: flex; justify-content: center;"
						:controlsList="lineList"
						:controlsSize="{ width: 180, height: 40 }"
						@sheet-del="sheetDel"
						@sheet-copy="sheetCopy"
						@sheet-edit="sheetEdit"
					>
						<template #default="scope">
							<u-section
								v-if="lineList[scope.index]?.status === 1"
								:title="scope.row.name"
								:right="false"
								:show-line="scope.row?.show"
								:line-color="scope.row?.show ? '#0000f0' : ''"
								style="margin-left: 20rpx;"
							>
								<template
									v-if="item?.isSubmit || scope.row.isSubmit !== undefined"
									#right
								>
									<u-icon
										name="error-circle-fill"
										color="#ff0000"
										style="margin-right: 4rpx;"
									/>
								</template>
							</u-section>
							<view v-else class="add">
								<u-icon
									name="plus"
									color="#c6c6c6"
									size="50"
									@tap="addTabs"
								></u-icon>
							</view>
						</template>
					</drag-and-drop-sort>
				</view>
				<view class="left-cates" />
				<view class="right-cates">
					<view style="width: 80px;">
						<!-- <view style="height: 88rpx;"></view> -->
						<block v-for="(item, index) in lineList">
							<u-image
								v-if="index != lineList.length - 1"
								width="160rpx"
								mode="widthFix"
								:src="baseUrl + item.url"
							></u-image>
						</block>
					</view>
				</view>
			</view>

			<!-- 导航 -->
			<uni-goods-nav
				class="goods-nav"
				:fill="true"
				:options="options"
				:buttonGroup="buttonGroup"
				@click="onClick"
				@buttonClick="buttonClick"
			/>
		</view>

		<!-- 选择弹出框 -->
		<category-popup
			ref="categoryRef"
			:show="showPopup"
			@close="handleClose"
			@categoryData="initCategory"
		/>
		<!-- 产品线sku -->
		<goods-sku ref="goodsSkuRef" @add-product="addProduct" @close-sku="closeSku" />

		<!-- 设置标题 -->
		<set-title ref="setTitleRef" />

		<!-- model提示框 -->
		<u-modal
			v-model="model.show"
			:content="model.content"
			show-cancel-button
			@confirm="onConfirm"
		></u-modal>
	</view>
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { indexDetails } from '@/api/index';
import { useStore } from '@/store/useStore';
import {
	addProductLineCart,
	productLineCollect,
	delProductLineCollect,
	getProductLineIndex,
	getProductLineReAdd,
} from '@/api/productLine';
import config from '@/utils/config';
import dragAndDropSort from './components/drag-and-drop-sort.vue';
import categoryPopup from './components/categoryPopup.vue';
import goodsSku from '@/pages/goods/goodsSku';
import setTitle from './components/setTitle.vue';

let store = useStore();

let baseUrl = config.baseUrl;
let lineList: any = ref(store.lineData); //右侧tabber数据
let showPopup = ref(false as Boolean); // popup弹窗
let categoryRef = ref();
let goodsSkuRef = ref();
let setTitleRef = ref();
let dragRef = ref();
let detailData = ref(); // 产品信息
let star = ref(store.star); // 控制收藏
let skuClose = ref(''); // sku通过何种方式消失
let model = ref({
	show: false,
	content: '确定重置所选产品？',
});
let flag = ref(false);

let options = ref([
	{
		icon: star.value ? 'star-filled' : 'star',
		text: '收藏',
	},
	{
		icon: 'plusempty',
		text: '设置名称',
	},
]);
let buttonGroup = ref([
	{
		text: '加入购物车',
		backgroundColor: '#ff0000',
		color: '#fff',
	},
	{
		text: '立即购买',
		backgroundColor: '#ffa200',
		color: '#fff',
	},
]);

let cartId = ref(); // 修改的产品线id
let lineId = ref(); // 修改的产品线id

onLoad((options: any) => {
	// 修改产品线时使用
	if (typeof options.cartId !== 'undefined') {
		cartId.value = options.cartId;
		flag.value = false;
		lineId.value = options.id;
		// 把加入购物车变成禁用状态
		// buttonGroup.value[0].backgroundColor = '#ccc';
		initProductLine(options.id);
	} else {
		flag.value = true;
	}
});

// 修改产品线数据初始化
let initProductLine = (lineId: number) => {
	store.$patch({
		lineData: [{ show: false, status: 0 }],
	});
	lineList.value = store.lineData;
	// 获取产品线详细数据
	getProductLineIndex({ lineId }).then((res: any) => {
		if (res.data.code === 200) {
			// 处理数据
			res.data.data.cartList.forEach((item: any) => {
				item['name'] = item.goodsName;
				item['show'] = false;
				item['url'] = item.picUrl;
				item['status'] = 1;
			});
			// 合并数据
			store.$patch({
				lineData: [...res.data.data.cartList, ...lineList.value],
			});
			lineList.value = store.lineData;
			store.title = res.data.data.lineName;
			setTitleRef.value.title = store.title;
			// 处理子组件数据更新延迟问题
			nextTick(() => {
				flag.value = true;
				console.log(res.data.data.cartList, store.lineData, lineList.value);
			});
		}
	});
};

let addTabs = () => {
	categoryRef.value.currentSubCategoryData = [];
	showPopup.value = true;
	categoryRef.value.initIndex();
	// console.log(store.lineData);
};

// 获取sku隐藏方式 '' 加入后 mask 点击mask部分， close 点击关闭按钮
let closeSku = (val: string) => {
	if (editFlag.value) {
		skuClose.value = val;
		if (skuClose.value) {
			// 取消修改后的逻辑
			lineList.value.splice(editIndex.value.index, 0, editIndex.value.data);
		} else {
			// 确定修改产品
			let index = lineList.value.length - 2;
			if (lineList.value.length === 2) index = 0;
			let data = lineList.value[index];
			lineList.value.splice(index, 1);
			if (lineId.value) {
				lineEdit.value.productId = data.productId;
				lineEdit.value.specificationCustom = data.specificationCustom;
				lineEdit.value.specifications = data.specifications;
				lineEdit.value.number = data.number;
				lineList.value.splice(editIndex.value.index, 0, lineEdit.value);
			} else lineList.value.splice(editIndex.value.index, 0, data);
			console.log(lineEdit.value);
		}
		store.$patch({
			lineData: lineList.value,
		});
		goodsSkuRef.value.handleClose();
		editFlag.value = false;
	} else {
		goodsSkuRef.value.handleClose();
	}
};

let editIndex = ref();
let editFlag = ref(false);

let lineEdit = ref(); // 记录产品线修改的数据

// 产品修改
let sheetEdit = (index: number) => {
	editFlag.value = true;
	let data = lineList.value[index];
	if (lineId.value) {
		data.updateTime = null;
		lineEdit.value = data;
	}
	editIndex.value = {
		index,
		data,
	};
	store.$patch({
		lineData: lineList.value.splice(index, 1),
	});
	initDetails(data.goodsId);
};

let lineDelete = ref([] as any); // 记录产品线删除数据

// 产品删除
let sheetDel = (index: number) => {
	if (lineId.value) {
		if (lineList.value[index].hasOwnProperty('deleted')) {
			lineList.value[index].deleted = true;
			lineDelete.value.push(lineList.value[index]);
		}
	}
	lineList.value.splice(index, 1);
	store.$patch({
		lineData: lineList.value,
	});
};

// 产品复制
let sheetCopy = (index: number) => {
	flag.value = false;
	lineList.value.splice(index, 0, lineList.value[index]);
	// 避免splice改变原数组
	let lineInfos = JSON.parse(JSON.stringify(lineList.value));
	lineInfos[index].show = false;
	lineList.value = lineInfos;
	store.$patch({
		lineData: lineInfos,
	});
	// 通过购物车进入操作时进入
	if (lineId.value) {
		if (lineList.value[index + 1].hasOwnProperty('deleted'))
			delete lineList.value[index + 1].deleted;
		if (lineList.value[index + 1].hasOwnProperty('updateTime'))
			delete lineList.value[index + 1].updateTime;
		if (lineList.value[index + 1].hasOwnProperty('id')) delete lineList.value[index + 1].id;
		store.$patch({
			lineData: lineList.value,
		});
	}
	nextTick(() => {
		flag.value = true;
	});
};

// 商品加入购物车等左侧事件
let onClick = (e: any) => {
	if (e.index === 1) {
		setTitleRef.value.showTitle = true;
	} else {
		// 收藏
		if (!star.value) {
			if (JSON.stringify(store.collectData) === '{}') {
				// 初次收藏
				complete().then((data: any) => {
					productLineCollect(data).then((res: any) => {
						if (res.data.code === 200) {
							store.$patch({
								star: true,
								collectData: {
									type: 2,
									valueId: res.data.data.valueId,
								},
							});
							star.value = true;
							options.value[0].icon = 'star-filled';
							uni.showToast({
								title: '收藏成功',
								icon: 'none',
							});
						}
					});
				});
			} else {
				// 收藏取消后收藏
				delProductLineCollect(store.collectData).then((res: any) => {
					if (res.data.code === 200) {
						store.$patch({
							star: true,
						});
						star.value = true;
						options.value[0].icon = 'star-filled';
						uni.showToast({
							title: '收藏成功',
							icon: 'none',
						});
					}
				});
			}
		} else {
			// 取消收藏
			delProductLineCollect(store.collectData).then((res: any) => {
				if (res.data.code === 200) {
					store.$patch({
						star: false,
					});
					star.value = false;
					options.value[0].icon = 'star';
					uni.showToast({
						title: '取消收藏',
						icon: 'none',
					});
				}
			});
		}
	}
};

// 商品加入购物车等右侧侧事件
let buttonClick = (e: any) => {
	switch (e.index) {
		case 0:
			addCart();
			break;
		case 1:
			buyNow();
			break;
	}
};

// 加入购物车
let addCart = () => {
	complete().then((data: any) => {
		// 判断是否有失效商品
		if (
			data.item.some((item: any) => {
				return !item.isSubmit && item.isSubmit !== undefined;
			})
		)
			return uni.showToast({
				title: '请先删除带红色图标的失效商品',
				icon: 'none',
			});
		if (lineId.value) {
			// 修改
			data['lineId'] = lineId.value;
			// 把删除的数据添加进去
			if (lineDelete.value.length !== 0) {
				lineDelete.value.map((item: any) => {
					data.item.push(item);
				});
			}
			getProductLineReAdd(data).then((res: any) => {
				if (res.data.code === 200) {
					lineDelete.value = [];
					reload();
				}
			});
		} else {
			// 添加到购物车
			addProductLineCart(data).then((res: any) => {
				if (res.data.code === 200) {
					uni.showToast({
						title: '加入购物车成功',
						icon: 'none',
					});
					reload();
				}
			});
		}
	});
};

// 立即购买
let buyNow = () => {
	complete().then((data: any) => {
		// 判断是否有失效商品
		if (
			data.item.some((item: any) => {
				return !item.isSubmit && item.isSubmit !== undefined;
			})
		)
			return uni.showToast({
				title: '请先删除带红色图标的失效商品',
				icon: 'none',
			});
		addProductLineCart(data).then((res: any) => {
			if (res.data.code === 200) {
				if (!uni.getStorageSync('addressId')) {
					uni.setStorage({
						key: 'addressId',
						data: 0,
					});
				}
				let storage: any = {
					cartId: 0,
					couponId: 0,
				};
				Object.keys(storage).forEach((prop: any) => {
					const el: any = storage[prop];
					uni.setStorage({
						key: prop,
						data: el,
					});
				});
				uni.navigateTo({
					url: '../order/checkout?type=' + 'productline' + '&buyNowId=' + res.data.data,
				});
			}
		});
	});
};

// 点击 收藏，加入购物车，立即购买 前逻辑
let complete = () => {
	return new Promise((resolve, reject) => {
		if (store.lineData.length === 1)
			return uni.showToast({
				title: '请先选择产品',
				icon: 'none',
			});
		if (!store.title)
			return uni.showToast({
				title: '请先设置标题',
				icon: 'none',
			});
		let lineData: any = [...store.lineData]; // 拷贝
		lineData.length = lineData.length - 1; // 删除最后一个数据
		let data = {
			item: lineData,
			title: store.title,
		};
		resolve(data);
	});
};

// 添加产品线产品
let initCategory = (data: any) => {
	initDetails(data.id);
	uni.showLoading({
		title: '加载中...',
	});
};

// 保存到产品线
let addProduct = (data: any, productId: number, specifications: any, specificationCustom: any) => {
	let index = lineList.value.length - 1;
	lineList.value.splice(index, 0, {
		name: data.goods_name,
		url: data.image,
		goodsId: data.goods_id,
		number: data.buy_num,
		productId: productId,
		specifications,
		specificationCustom,
		show: false,
		status: 1,
	});

	store.$patch({
		lineData: lineList.value,
	});
	console.log(store.lineData, 'store.lineData');
	goodsSkuRef.value.skuKey = false;
};

// 退出popup
let handleClose = (val: Boolean) => (showPopup.value = val);

// 根据id获取商品信息
let initDetails = (id: number) => {
	indexDetails({
		id,
	}).then((res: any) => {
		if (res.data.code === 200) {
			uni.hideLoading();
			detailData.value = res.data.data;
			// console.log(detailData.value, 'detailData.value');
			goodsSkuRef.value.init(detailData.value, id);
			goodsSkuRef.value.skuKey = true;
			goodsSkuRef.value.skuMode = 5;
			// console.log(res.data.data, '商品详情数据');
		}
	});
};

// 重置产品线
let reset = () => (model.value.show = true);

//确认重置
let onConfirm = () => {
	reload();
	model.value.show = false;
};

// 重置页面数据
let reload = () => {
	store.$reset(); // 重置pinia数据
	let pages = getCurrentPages(); //获取所有页面的数组对象
	let currPage: any = pages[pages.length - 1]; //当前页面
	uni.reLaunch({
		url: '/' + currPage.route,
	});
};
</script>

<style lang="scss" scoped>
$nav-heigth: var(--window-bottom);

.add {
	position: absolute;
	width: 180px;
	height: 40px;
	background-color: #fff;
	z-index: 0;
	text-align: center;
	line-height: 45px;
	margin-top: 20rpx;
}
.left-cates {
	width: 368rpx;
}
.right-cates {
	flex: 1;
	display: flex;
	flex-direction: row;
	justify-content: center;
	// align-items: center;
	background-color: #fff;
	min-height: 100vh;
	max-height: 200vh;
}

.u-wrap {
	// height: calc(100vh);
	/* #ifdef H5 */
	// height: calc(100vh - var(--window-top));
	// min-height: 100vh;
	// max-height: 2000px;
	/* #endif */
	display: flex;
	flex-direction: column;
}

.u-menu-wrap {
	flex: 1;
	display: flex;
	overflow: hidden;
	justify-content: space-between;
}
.goods-nav {
	position: fixed;
	bottom: $nav-heigth;
	width: 100%;
	display: inline;
	transform: none;
}
</style>
