<template>
	<u-popup ref="popup" :show="show" mode="bottom" @close="close" background-color="#fff" @change="change">
		<view class="specPop">
			<view class="s-box padding-sm" v-if="current">
				<view class="s-img dflex-c">
					<image v-if="current.img" :src="current.img.url" mode="aspectFit"></image>
					<u-icon v-else name="photo" size="36"></u-icon>
				</view>
				<view class="g-info">
					<view class="s-name">{{current.skuName}}</view>
					<view class="s-price">￥{{current.retailPrice}}</view>
				</view>
			</view>
			<view class="s-box padding-sm" v-else>
				<view class="s-img dflex-c">
					<image v-if="supValue.majorImg" :src="supValue.majorImg" mode="aspectFit"></image>
					<u-icon v-else name="photo" size="36"></u-icon>
				</view>
				<view class="g-info">
					<view class="s-name">{{supValue.spuName}}</view>
					<view class="s-price" v-if="supValue.minPrice == supValue.maxPrice">￥{{supValue.maxPrice}}</view>
					<view class="s-price" v-else>￥{{supValue.minPrice}} ~ ￥{{supValue.maxPrice}}</view>
				</view>
			</view>
			<uni-section :title="item.name" v-for="item in temp" :key="item.field">
				<view class="spec-box padding-lr-sm">
					<view class="spec-item padding-lr-sm" :class="{'on-spec':item.value == specItem}" @click="actSpec(item,specItem)" v-for="(specItem,index) of item.data" :key="index">{{specItem}}</view>
				</view>
			</uni-section>
			<uni-section title="购买数量">
				<view class="purchase-num padding-lr-sm">
					<view class="num">
						<!-- 剩余562件 -->
					</view>
					<uni-number-box v-model="vModelValue" :min="1" @change="changeValue" />
				</view>
			</uni-section>
			<view class="btn-box">
				<view class="btn reset" @click="close">取消</view>
				<view class="btn confirm" v-if="type==1" @click="payBtn">立即购买</view>
				<view class="btn confirm" v-else @click="clickAddcart">{{cartData.skuId ? '确定' : '加入购物车'}}</view>
			</view>
			<u-loading-page :loading="load"></u-loading-page>
			<u-toast ref="uToast"></u-toast>
		</view>
	</u-popup>
</template>

<script>
	export default {
		name:"specPopup",
		props:{
			noClear:{}
		},
		data(){
			return{
				dinCarData:{},
				show:false,
				load:false,
				supValue:{}, //spu数据
				temp:[], //规格列表
				checkObj:{}, //选中的规格
				skuData:[], //sku数据
				current:null, //当前sku数据
				vModelValue:1,
				cartList:[], //购物车列表
				cartData:null, //当前购物车数据
				dinCarData:{},
				type:0
			}
		},
		created() {
			let carData = uni.getStorageSync('dinCarData');
			if(carData){
				try{
					this.dinCarData = JSON.parse(carData)
				}catch(e){}
			}
			let cartInfo = uni.getStorageSync('cartInfo');
			if(cartInfo){
				try{
					this.cartList = JSON.parse(cartInfo)
				}catch(e){}
			}
		},
		methods:{
			payBtn(){
				if(!this.isCheckFind()){
					this.$refs.uToast.show({
						type:'warning',
						message: '请选择规格！'
					})
					return
				}
				if(!this.current){
					this.$refs.uToast.show({
						type:'warning',
						message: '该商品没有库存！'
					})
					return
				}
				let data = this.getSkuDataObj()
				
				uni.setStorageSync('selectPay', JSON.stringify([data]))
				uni.navigateTo({
					url: '/pages/order/submitOrder/submitOrder'
				});
			},
			setType(n){
				this.type = n
			},
			changeValue(){},
			change(){},
			getSkuDataObj() {
				let data = {
					skuId:this.current.skuId,
					basePrice:this.current.tagPrice,
					price:this.current.retailPrice,
					quantity:this.vModelValue,
					imgUrl:this.current.img?this.current.img.url:'',
					skuTitle:this.current.title,
					spuId:this.current.spuId,
					skuCode:this.current.skuCode,
					splitMergeId:this.current.splitMergeId,
					title:this.current.title,
					skuName:this.current.skuName,
					productWeight: this.current.grossWeight,
				}
				if(this.current.freightTemplateId){
					data.freightTemplateId = this.current.freightTemplateId
				}
				
				if(this.current.color){
					data.skuProperties = this.current.color
				}
				if(this.current.size){
					data.skuProperties = data.skuProperties ? data.skuProperties + ';' + this.current.size : this.current.size
				}
				if(this.current.extendProps){
					for(const key in this.current.extendProps){
						data.skuProperties = data.skuProperties ? data.skuProperties + ';' + this.current.extendProps[key] : this.current.extendProps[key]
					}
				}
				return data;
			},
			//加入购物车
			clickAddcart(){
				if(!this.isCheckFind()){
					this.$refs.uToast.show({
						type:'warning',
						message: '请选择规格！'
					})
					return
				}
				if(!this.current){
					this.$refs.uToast.show({
						type:'warning',
						message: '该商品没有库存！'
					})
					return
				}
				if(!this.vModelValue || this.vModelValue == 0){
					this.$refs.uToast.show({
						type:'warning',
						message: '请输入购买数量！'
					})
					return
				}
				// let that = this;
				
				//加个采购商验证功能
				// if(!this.dinCarData || !this.dinCarData.id){
				// 	this.$refs.uToast.show({
				// 		type:'warning',
				// 		message: '您不是采购商，请前往服务平台注册！'
				// 	})
				// 	return
				// }
				let ind = -1;
				let cartDataInd = -1; 
				this.cartList.forEach((item,index) => {
					if(item.skuId == this.current.skuId){
						ind = index
					}
					if(this.cartData && item.skuId == this.cartData.skuId){
						cartDataInd = index
					}
				})
				if(ind >= 0) {
					if(ind == cartDataInd){
						this.cartList[ind].quantity = this.vModelValue
					}else{
						this.cartList[ind].quantity = this.cartList[ind].quantity + this.vModelValue
						if(cartDataInd >= 0 ){
							this.cartList.splice(cartDataInd, 1)
						}
					}
				}else{
					// let skuProperties = '';
					// for(const key in this.checkObj){
					// 	if(!skuProperties){
					// 		skuProperties = this.checkObj[key]
					// 	}else{
					// 		skuProperties = skuProperties + ';' + this.checkObj[key]
					// 	}
					// }
					let data = this.getSkuDataObj()
					if(cartDataInd >= 0 ){
						this.cartList.splice(cartDataInd, 1)
					}
					this.cartList.push(data)
				}
				const stringData = JSON.stringify(this.cartList)
				uni.setStorageSync('cartInfo',stringData);
				this.$refs.uToast.show({
					type:'success',
					message: '操作成功！'
				})
				
				this.$emit('onSuccess')
				setTimeout(() => {
					this.close()
				},500)
			},
			//选中规格
			actSpec(item,v){
				item.value = v;
				this.checkObj[item.field] = v;
				if(this.isCheckFind()){
					for(const item of this.skuData){
						let n = true
						for(const key in this.checkObj){
							if(key == 'color' || key == 'size'){
								if(this.checkObj[key] !== item[key]){
									n = false;
									break
								}
							}else{
								if(!item.extendProps || this.checkObj[key] !== item.extendProps[key]){
									n = false;
									break
								}
							}
						}
						if(n){
							this.current = item
						}
					}
					if(this.current){
						this.$emit('onCheckSpec',{
							spec:this.checkObj,
							sku:this.current
						})
					}
				}else{
					this.current = null;
				}
			},
			//判断规格是否已选完
			isCheckFind(){
				let n = true
				for(const item of this.temp){
					if(!this.checkObj[item.field]){
						n = false
						break
					}
				}
				return n;
			},
			//根据spuId获取sku列表
			loadSkuList(bo){
				this.load = true;
				const that = this;
				this.$req({
					url:'/item/sku/queryItem',
					data:{spuId:this.supValue.spuId},
					success: res => {
						that.skuData = res.rows
						for(const item of that.skuData){
							if(item.extendProps){
								try{
									item.extendProps = JSON.parse(item.extendProps)
								}catch(e){}
							}
						}
						//是否是多规格
						if(!bo){
							if(that.skuData[0].color){
								that.temp.push({
									name:'颜色',
									field:'color',
									data:[that.skuData[0].color],
									value:''
								})
							}
							if(that.skuData[0].size){
								that.temp.push({
									name:'规格',
									field:'size',
									data:[that.skuData[0].size],
									value:''
								})
							}
						}
						//设置默认规格
						if(!that.current){
							for(const item of that.temp){
								that.actSpec(item, item.data[0])
							}
						}
						
					},
					fail: err => {
						let msg = ''
						if(err && err.msg && err.msg.length < 15){
							msg = err.msg
						}else{
							msg = '系统繁忙'
						}
						that.$refs.uToast.show({
							message: msg
						})
					},
					complete: () => {
						that.load = false
					}
				})
			},
			//重置数据
			setData(v,cartData){
				this.cartData = cartData ? cartData : null
				if(!this.noClear || !this.supValue.spuId){
					this.checkObj = {}
					this.current = null
					this.vModelValue = cartData?cartData.quantity:1
					this.loadSpu(v)
				}
			},
			loadSku(data){
				let that = this;
				this.$req({
					url:'/item/sku/queryItem/' + data.skuId,
					success: res => {
						that.current = res.data
						let d = null
						if(that.current.extendProps){
							try{
								d = JSON.parse(that.current.extendProps)
							}catch(e){}
						}
						for(const item of that.temp){
							if(that.current[item.field]){
								item.value = that.current[item.field]
								that.checkObj[item.field] = that.current[item.field]
							}
							if(d && d[item.field]){
								item.value = d[item.field]
								that.checkObj[item.field] = d[item.field]
							}
						}
					},
					fail: err => {
						let msg = ''
						if(err && err.msg && err.msg.length < 15){
							msg = err.msg
						}else{
							msg = '系统繁忙'
						}
						that.$refs.uToast.show({
							message: msg
						})
					},
					complete: () => {
						// that.load = false
					}
				})
			},
			loadSpu(v){
				let that = this;
				this.load = true
				this.$req({
					url:'/item/spu/queryProduct/' + v,
					success: res => {
						let _data = res.data;
						that.supValue = _data;
						if(that.supValue.imgList){
							for(const imgItem of that.supValue.imgList){
								if(imgItem.major == '2'){
									this.supValue.majorImg = imgItem.url
								}
							}
						}
						let valueFun = data => {
							let n = ''
							if(cartData){
								let arr = cartData.skuProperties
							}
							return n;
						}
						let extendPropsData = {}
						if(_data.extendProps){
							that.temp = []
							try{
								extendPropsData = JSON.parse(_data.extendProps);
								for(const key in extendPropsData.template.propValues){
									let name = ''
									if(key == 'color'){
										name = '颜色'
									}else if(key == 'size'){
										name = '规格'
									}else{
										name = key
									}
									that.temp.push({
										name:name,
										field:key,
										data:extendPropsData.template.propValues[key],
										value:''
									})
								}
							}catch(e){}
						}
						that.loadSkuList(extendPropsData.multiple)
						if(that.cartData){
							that.loadSku(that.cartData)
						}
					},
					fail: err => {
						let msg = ''
						if(err && err.msg && err.msg.length < 15){
							msg = err.msg
						}else{
							msg = '系统繁忙'
						}
						that.$refs.uToast.show({
							message: msg
						})
					},
					complete: () => {
						that.load = false
					}
				})
			},
			close(){
				this.show = false;
			},
			open(){
				this.show = true;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.specPop{
		height: 900upx;
		overflow-y: auto;
		position: relative;
		padding-bottom: 150upx;
	}
	.btn-box{
		width: 100%;
		display: flex;
		justify-content: space-around;
		align-items: center;
		padding-top: 50upx;
		padding-bottom: 30upx;
		position: fixed;
		left: 0;
		bottom: 0;
		background-color: #FFF;
		z-index: 10;
		.btn{
			width: 45%;
			height: 70upx;
			text-align: center;
			line-height: 70upx;
			border-radius: 35upx;
		}
		.reset{
			border:solid 1px #EEE;
			box-sizing: border-box;
		}
		.confirm{
			background-image: $base-bg-gradient-color;
			color: #FFF;
		}
	}
	.spec-box{
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		.spec-item{
			height: 60upx;
			line-height: 60upx;
			border:solid 1px #EEE;
			box-sizing: border-box;
			text-align: center;
			margin-left: 20upx;
			border-radius: 3px;
			margin-bottom: 20upx;
			font-size: 12px;
		}
		.spec-item:first-child{
			margin-left: 0;
		}
		.on-spec{
			background-image: $base-bg-gradient-color;
			color: #FFF;
		}
	}
	.s-box{
		width: 100%;
		display: flex;
		border-bottom: solid 1px #EEE;
		.s-img{
			width: 140upx;
			height: 140upx;
			background-color: #EEE;
			border-radius: 4px;
			>image{
				width: 100%;
				height: 100%;
			}
		}
		.g-info{
			padding-left: 20upx;
			.s-name{
				padding-bottom: 4px;
			}
			.s-price{
				color: #F00;
				font-size: 14px;
			}
		}
	}
	.purchase-num{
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: solid 1px #EEE;
		padding-bottom: 30upx;
		.num{
			font-size: 12px;
		}
	}
</style>