<!-- 静态数据演示版本 适合任何后端 -->
<template>
	<view class="app">
		<vk-data-goods-sku-popup
			v-if="flag"
			ref="skuPopupRef"
			v-model="skuKey"
			border-radius="20"
			:localdata="goodsInfo"
			:mode="skuMode"
			@open="onOpenSkuPopup"
			@close="SkuPopup"
			@add-cart="addCarts"
			@buy-now="buyNow"
			@change="onChange"
			@num-change="numChange"
			@add-product="addProduct"
			@plus="onPlus"
			@confirm="onConfirm"
			@blur="onBlur"
			@select-parts="selectParts"
		></vk-data-goods-sku-popup>
	</view>
</template>

<script setup lang="ts">
import { ref, watch  } from 'vue';
import { addCart, fastaddCart, readdCart } from '@/api/index';

// SKU弹窗模式
let skuMode = ref(1);
// 是否打开SKU弹窗
let skuKey = ref(false);
// 后端返回的商品信息
let goodsInfo = ref({} as any);
let skuPopupRef = ref();
let detailData = ref()
let partsIds = ref([] as any) // 选择的配件id
let detailId = ref()
let selectedGoodsItem = ref('')
let selectedGoodsSum = ref(1)
let emits = defineEmits(['selected', 'addProduct', 'close-sku'])
let props = defineProps({
	cartId : {
		type: Number
	}
})
let flag = ref(true)

 watch([selectedGoodsItem, selectedGoodsSum],(newVal)=> {
	 if(newVal) {
		 if(newVal[0] !== undefined) emits('selected', newVal)
	 }
    })

let onChange = (e: any) => {
	selectedGoodsItem.value = e.sku_name_arr
}

let numChange = (e: any) => {
	selectedGoodsSum.value = e
}

// 添加自定义规格字段
let onPlus = (index: number) => {
	goodsInfo.value.spec_list[index].isPlus = false
}

// 失去输入自定义规格输入框焦点
let onBlur = (val: string, index: number) => {
	if(!val) return goodsInfo.value.spec_list[index].isPlus = true
	goodsInfo.value.spec_list[index].custom = val
}

let onConfirm = (val: string, index: number) => {
	if(!val) return goodsInfo.value.spec_list[index].isPlus = true
	goodsInfo.value.spec_list[index].custom = val
}

// 弹出sku后给规格赋值
let resultSku = (data?: any) => {
	if(detailData.value.productList.length === 1) {
		skuPopupRef.value.selectArr = {...detailData.value.productList[0].specifications }
		// skuPopupRef.value.selectShop = {
		// 	buy_num: 1,
		// 	goods_id: detailData.value.productList[0].goodsId,
		// 	goods_name: detailData.value.info.name,
		// 	image: detailData.value.info.picUrl,
		// 	price: 0,
		// 	sku_name_arr: { ...detailData.value.productList[0].specifications },
		// 	stock: 1000,
		// 	_id: detailData.value.productList[0].id,
		// }
	}
}

// 选择配件
let selectParts = (data: any) => {
	let index = partsIds.value.indexOf(data.id)
	if(index === -1) {
		if(data.show = true) partsIds.value.push(data.id)
	} else partsIds.value.splice(index, 1)
}

// 初始化 把请求数据变成组件需要的格式
let init = (data: any, id: number, partsData?: any) => {
	detailData.value = data
	detailId.value = id
	let productList: any = [];
	productList = data.productList.map((item: any) => {
		return {
			image: data.info.designUrl,
			sku_name_arr: item.specifications,
			_id: item.id,
			goods_id: item.goodsId,
			price: item.price,
			stock: 1000,
			goods_name: data.info.name,
		};
	});
	// console.log(productList, 'productList');
	let specificationList: any = [];
	specificationList = data.specificationList.map((item: any) => {
		return {
			name: item.name,
			isPlus: true, // 控制自定义规格输入框显示
			custom: '', // 自定义规格
			isCustom: item.valueList[0].customSpec, // 后台是否设置自定义
			list: item.valueList.map((res: any) => {
				return {
					name: res.value,
				};
			}),
		};
	});
	// console.log(specificationList, 'specificationList');
	goodsInfo.value = {
		_id: 1181026,
		name: data.info.name,
		goods_thumb: data.info.designUrl,
		sku_list: productList,
		spec_list: specificationList,
		partsData
	};
	// console.log(goodsInfo.value, 'goodsInfo.value');
	productList = []
	specificationList = []
	resultSku()
};
// sku组件 开始-----------------------------------------------------------
let onOpenSkuPopup = () => {};

// 关闭弹窗
let SkuPopup = (e: any) => {
	emits('close-sku', e)
};

// 选择自定义规格后的逻辑
let custom = (selectShop: any) => {
	let flag = false
	let customArr: any = [] // 存储选择的自定义的数组
	goodsInfo.value.spec_list.map((item: any, i: number) => {
		if(item.custom) {
			selectShop.sku_name_arr[i] = item.custom
			let obj: any = {}
			obj[item.name] = item.custom
			customArr.push(obj)
			flag = true
		}
	})
	return { selectShop, flag, customArr }
}

// 加入购物车前的判断
let addCartFn = (obj: any) => {
	let { selectShop } = obj;
	let productId: any = getProductId(selectShop.sku_name_arr)
	let shop = custom(selectShop)
	let specifications: any = []
	let specificationCustom: any = []
	// 有自定义会走下面的逻辑
	if(shop.flag) {
		productId = 0
		selectShop = shop.selectShop
		specifications = shop.selectShop.sku_name_arr
		specificationCustom = shop.customArr
	}
	let data = {
		goodsId: detailId.value,
		number: selectShop.buy_num,
		productId: productId,
		type: 0,
		specifications,
		specificationCustom,
		partIds: partsIds.value
	}
	if(props.cartId) {
		data = { ...{id: props.cartId }, ...data }
		readdCart(data).then((res: any) => {
			if(res.data.code === 200) {
				uni.showToast({
					title: '已添加至购物车',
					icon: 'none',
					duration: 300,
					success() {
						handleClose()
						skuKey.value = false
					}
				});
			} else {
				console.log(res, '加入购物车错误');
			}
		})
	} else {
		addCart(data).then((res: any) => {
			if(res.data.code === 200) {
				uni.showToast({
					title: '已添加至购物车',
					icon: 'none',
					duration: 300,
					success() {
						handleClose()
						skuKey.value = false
					}
				});
			} else {
				console.log(res, '加入购物车错误');
			}
		})
	}
};
// 加入购物车按钮
let addCarts = (selectShop: any) => {
	addCartFn({
		selectShop: selectShop,
		success: function() {
			setTimeout(function() {
				skuKey.value = false;
			}, 300);
		},
	});
};
// 立即购买
let buyNow = (selectShop: any) => {
	// console.log(selectShop, selectShop.sku_name_arr ,' selectShop.sku_name_arr');
	let productId: any = getProductId(selectShop.sku_name_arr)
	let shop = custom(selectShop)
	let specifications: any = []
	let specificationCustom: any = []
	// 有自定义会走下面的逻辑
	if(shop.flag) {
		productId = 0
		selectShop = shop.selectShop
		specifications = shop.selectShop.sku_name_arr
		specificationCustom = shop.customArr
	}
	let data: object = {
		goodsId: detailId.value,
		number: selectShop.buy_num,
		productId: productId,
		type: 0,
		specifications,
		specificationCustom,
		partIds: partsIds.value
	}
	fastaddCart(data).then((res: any) => {
		if(res.data.code === 200) {
			uni.navigateTo({
				url: `../order/checkout?type=` + 'goods' + '&buyNowId=' + res.data.data,
				success() {
					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
						})
					});
					setTimeout(function() {
						handleClose()
						skuKey.value = false
					}, 300);
				}
			})
		} else {
			console.log(res.data.msg);
		}
	})
};

// 加入产品线
const addProduct = (selectShop: any) => {
	console.log(selectShop);
	skuPopupRef.value.handClose()
	let productId: any = getProductId(selectShop.sku_name_arr)
	let shop = custom(selectShop)
	let specifications: any = []
	let specificationCustom: any = []
	// 有自定义会走下面的逻辑
	if(shop.flag) {
		productId = 0
		selectShop = shop.selectShop
		specifications = shop.selectShop.sku_name_arr
		specificationCustom = shop.customArr
	}
	// console.log(selectShop, '加入产品线');
	emits('addProduct', selectShop, productId, specifications, specificationCustom)
	emits('close-sku', '') // 在修改规格时使用
	handleClose()
	detailData.value = undefined
	detailId.value = undefined
}


// 获取分组id
const getProductId = (specText: any) => {
	let productId;
	detailData.value?.productList.forEach((item: any) => {
		// 判断是否相等
		if(item.specifications.length === specText.length) {
			let bool = true
			item.specifications.forEach((res: any) => {
				if(specText.indexOf(res) == -1) bool = false
			})
			if(bool) productId = item.id
			bool = true
		}
	})
	return productId
}

// 清楚sku数据
const handleClose = () => {
	goodsInfo.value = {}
	skuPopupRef.value.handClose()
}

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

defineExpose({
	skuKey,
	skuMode,
	init,
	handleClose,
	partsIds
});
</script>

<style lang="scss" scoped>
.app {
	padding: 30rpx;
	font-size: 28rpx;
}
</style>
