<template>
	<view>
		<el-popup ref="popup" direction="bottom" @close="onClose" :zIndex="1" :modal="false">
			<view class="wrapper" :style="{ 'min-height' : ((windowHeight / 2) + 30) + 'px' }">
				<view class="header">
					<view class="photo">
						<image :src="goods.photo"></image>
					</view>
					
					<view class="goods-info">
						<view class="goods-price">
							<text class="symbol" v-if="type == 'goods'">￥</text>
							<text class="price">{{ products.price }}</text>
							<text class="symbol" v-if="type == 'point'">积分</text>
						</view>
						<view class="stock">
							<view>
								剩余<text>{{ products.store_nums || 0 }}</text>{{ goods.unit || "件" }}
							</view>
						</view>
						<view class="selected" v-if="products.spec.selected.length > 0">已选择: {{ products.spec.selected }}</view>
					</view>
				</view>
				
				<view class="content" v-if="goods.spec.length > 0">
					<scroll-view :style="{ 'max-height' :  '200px' }" scroll-y>
						<view class="group-wrap">
							<view class="sku-row" v-for="(value,index) in goods.spec" :key="index">
								<view class="sku-title">{{ value.name }}</view>
								<view class="sku-item" :class="{ active: item.selected && item.disable == false, disable: item.disable }" v-for="(item,j) in value.list" :key="j">
									<text @click="onSelected(value.id,item.id)">{{ item.value }}</text>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
				
				<view class="number">
					<view class="label">购买数量</view>
					<view class="number-box">
						<uni-number-box :min="minNum" :max="maxNum" v-model="products.num" @change="onChangeNumber" @blur="onChangeNumber"></uni-number-box>
					</view>
				</view>
				<view class="placeholder"></view>
			</view>
		</el-popup>
	</view>
</template>

<script setup>
	import { nextTick, onMounted, ref, watch } from "vue";
	import { inArray,isEmpty } from "@/el-ui/libs/check";
	
	const props = defineProps({
		modelValue: {
			type: Boolean,
			default: false
		},
		type: {
			type: String,
			default: "goods"
		},
		goods: {
			type: Object,
			default: {}
		}
	});
	
	const minNum = ref(1);
	const maxNum = ref(10);
	const products = ref({ id: 0, num: 1, price: 0, store_nums: 0, isSubmit: true, spec: { id: 0, selected: "" } });
	const { windowHeight } = uni.getSystemInfoSync();
	const emits = defineEmits(["modelValue","update:modelValue","change"]);
	
	const popup = ref();
	onMounted(()=>{
		nextTick(()=>{
			props.modelValue && popup.value?.open();
		})
	})
	
	watch(()=>props.goods.id,(value)=>{
		if(isEmpty(value)){
			return ;
		}
		
		minNum.value              = props.goods.min_count;
		maxNum.value              = props.goods.max_count;
		products.value.num        = minNum.value;
		products.value.id         = props.goods.id;
		products.value.price      = props.type == 'goods' ? props.goods.sell_price : props.goods.point;
		products.value.store_nums = props.goods.store_nums;
		products.value.isSubmit   = props.goods.spec.length > 0 ? false : true;
	},{ deep: true, immediate: true })
	
	watch(()=>products.value,(value)=>{
		emits("change",value);
	},{ deep: true, immediate: true })
	
	watch(()=>props.goods.spec,(newValue,oldValue)=>{
		if(newValue.length <= 0){
			return ;
		}
		
		let arr = [];
		let selectedSku = [];
		for(let obj in newValue){
		    for(let index in newValue[obj]['list']){
		        if(newValue[obj]['list'][index]['selected'] && !newValue[obj]['list'][index]['disable']){
		            selectedSku.push(newValue[obj]['list'][index]);
		            arr.push({ name: newValue[obj].name, value: newValue[obj]['list'][index].value });
		        }
		    }
		}
		
		let selectedIndex = [];
		for(let obj in selectedSku){
		    selectedIndex.push(selectedSku[obj].pid + "" + selectedSku[obj].id);
		}
		
		if(newValue.length == selectedIndex.length){
			let keys = selectedIndex.join("");
			let g = null;
			for(let obj in props.goods.item){
				if(props.goods.item[obj].sku_id == keys){
					g = props.goods.item[obj];
					break;
				}
			}
			
		    products.value.price      = props.type == 'goods' ? g.sell_price : g.point;
		    products.value.store_nums = g.store_nums;
			maxNum.value              = g.store_nums;
		    if(products.value.num >= g.store_nums){
		        products.value.num = g.store_nums;
		    }
			
		    products.value.spec.id = g.sku_id;
		    products.value.isSubmit = true;
		}else{
		    products.value.isSubmit = false;
		}
		
		products.value.spec.selected = '';
		let s = [];
		for(let i in arr){
		    s.push(arr[i].name + ":" + arr[i].value);
		}
		
		if(s.length > 0){
		    products.value.spec.selected = s.join(",");
		}
	},{ deep: true })
	
	const checkStatus = (id, pid)=>{
		let spec = props.goods.spec;
		let flag = false;
		
		for(let i in spec){
		    if(id != spec[i]['id']){
		        continue;
		    }
		
		    for(let j in spec[i]['list']){
		        let value = spec[i]['list'][j];
		        if((id == value['pid'] && pid == value['id']) && value['disable']){
		            flag = true;
		            break;
		        }
		    }
		}
		
		return flag;
	}
	
	const onSelected = (id, pid)=>{
		if(checkStatus(id, pid)){
		    return ;
		}
		
		let specArray = [];
		let spec = props.goods.spec;
		for(let i in spec){
		    specArray[i] = "[A-Za-z0-9]+";
		    if(id == spec[i]['id']){
		        for(let j in spec[i]['list']){
		            let value = spec[i]['list'][j];
		            if(id == value['pid'] && pid == value['id']){
		                let flag = !value.selected;
						spec[i]['list'][j].selected = flag;
		                if(flag == true){
		                    specArray[i] = value.pid + "" + value.id;
		                }
		            }else{
						spec[i]['list'][j].selected = false;
		            }
		        }
		    }
		}
		
		for(let i in spec){
		    for(let j in spec[i]['list']){
		        let value = spec[i]['list'][j];
		        let temp = specArray.slice();
		        temp[i] = value.pid + "" + value.id;
		        let flag = true;
		        for(let j in props.goods.item){
		            let reg = new RegExp(temp.join(""));
		            if(reg.test(props.goods.item[j].sku_id) && props.goods.item[j].store_nums > 0) {
		                flag = false;
		            }
		        }
				
				spec[i]['list'][j].disable = flag;
		    }
		}
		
	}
	
	const onChangeNumber = (ev)=>{
		let num = 0;
		if(ev.type != undefined){
			num = ev.detail.value;
		}else{
			num = ev;
		}
	}
	
	const onClose = ()=>{
		emits("update:modelValue",false);
	}
	
	watch(()=>props.modelValue,(value)=>{
		if(value){
			nextTick(()=>{
				popup.value?.open();
			})
		}else{
			nextTick(()=>{
				popup.value?.close();
			})
		}
	});
	
</script>

<style lang="scss" scoped>
	.wrapper {
		.header {
			margin: 0 10rpx;
			border-bottom: 2rpx solid #ebedf0;
			display: flex;
			.photo {
				position: relative;
				width: 192rpx;
				height: 192rpx;
				margin: 24rpx 0;
				image {
					border-radius: 8rpx;
					width: 192rpx;
					height: 192rpx;
				}
			}
			.goods-info {
				display: flex;
				flex-direction: column;
				justify-content: flex-end;
				min-height: 96px;
				padding: 24rpx 40rpx 24rpx 20rpx;
				overflow: hidden;
				.goods-price {
					color: #ee0a24;
					.symbol {
						font-size: 32rpx;
						vertical-align: bottom;
					}
					.price {
						font-weight: 500;
						font-size: 45rpx;
						vertical-align: bottom;
						word-wrap: break-word;
					}
				}
				.stock {
					margin-top: 16rpx;
					color: #969799;
					font-size: 24rpx;
					line-height: 32rpx;
					view {
						display: inline-block;
						margin-right: 16rpx;
						color: #969799;
						font-size: 24rpx;
						text {
							display: inline-block;
							margin:0 8rpx;
							color: #969799;
							font-size: 24rpx;
							font-style: normal;
						}
					}
				}
				.selected {
					margin-top: 16rpx;
					color: #969799;
					font-size: 24rpx;
					line-height: 32rpx;
				}
			}
		}
		.content {
			.group-wrap {
				padding: 10rpx;
				.sku-row {
					margin: 0;
					border-bottom: 2rpx solid #ebedf0;
					.sku-title {
						padding: 24rpx 0;
						font-size: 28rpx;
					}
					.sku-item {
						position: relative;
						display: inline-flex;
						align-items: center;
						justify-content: center;
						min-width: 80rpx;
						margin: 0 24rpx 24rpx 0;
						overflow: hidden;
						color: #323233;
						font-size: 24rpx;
						line-height: 32rpx;
						vertical-align: middle;
						border-radius: 8rpx;
						cursor: pointer;
						&.active { 
							color: #ee0a24;
							&:before {
							    background: #ee0a24;
							    opacity: .1;
							}
						}
						&.disable {
							color: #a8a7a7;
						}
						&:before {
						    position: absolute;
						    top: 0;
						    left: 0;
						    width: 100%;
						    height: 100%;
						    background: #f7f8fa;
						    content: "";
						}
						text {
						    font-style: normal;
						    z-index: 1;
						    padding: 16rpx;
						}
					}
				}
			}
		}
		.number {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 50px;
			font-size: 28rpx;
			padding: 10rpx;
		}
		.placeholder {
			width: 100%;
			height: 30px;
		}
	}
</style>