<template>
	<view v-if="isShowPop">
		<view class="mask" @tap="hidePopup"></view>
		<view class="popup">
			<view class="close" @tap="hidePopup"><image class="image" src="/static/pages/images/close.png"></image></view>
			<view class="popinfo dflex">
				<image class="image" :src="skuPic + '?x-oss-process=style/w160'" v-if="skuPic" @click="previewSkuPic()"></image>
				<image class="image" :src="product.pic + '?x-oss-process=style/w160'" v-else @click="previewSkuPic()"></image>
				<view class="flex">
					<view class="title">{{ product.title }}</view>
					<view class="price" v-if="product.mode != 2">
						￥
						<text>{{ show_membership_price == 1 && product.actualPrice < product.salePrice ? product.actualPrice : product.salePrice }}</text>

						<!-- <text class="origin"
							v-if="product.salePrice == product.actualPrice && product.marketPrice > 0">￥{{product.marketPrice}}</text> -->
					</view>
					<view class="price dflex" v-if="product.mode == 2">
						<text>{{ product.integral }}积分</text>
						<text class="money">+￥{{ product.actualPrice }}</text>
						<text class="origin" v-if="product.salePrice == product.actualPrice && product.marketPrice > 0">￥{{ product.marketPrice }}</text>
					</view>
				</view>
			</view>
			<view class="pop-cons">
				
			
			<!-- sku参数 -->
				<view class="sku-con" v-for="(item, index) in skuParam" :key="index">
					<view class="tits">{{ item.name }}</view>
					<view class="pguige dflex">
						<view :class="'li tover ' + (it.active ? 'active' : '')" @tap="chooseSku(index, ind)" v-for="(it, ind) in item.params" :key="ind">{{ it.name }}</view>
					</view>
				</view>
			<!-- <block v-if="skuList&& skuList.length > 0">
				<view class="tits">规格</view>
				<view class="pguige dflex">
					<view v-for="(item, index) in skuList" :key="index" :class="'li ' + (item.active ? 'active' : '')"
						@tap="chooseSku" :data-index="index" :data-ind="ind">{{item.skuStr}}</view>
				</view>
			</block> -->
			<view class="shuliang dflex">
				<view class="tits">
					数量
					<text>库存{{ stock }}件</text>
				</view>
				<view class="num" v-if="stock > 0">
					<view class="jian" @tap="jianQuantity">-</view>
					<!-- <text class="nums">{{initNum}}</text> -->
					<input class="nums" :value="initNum" type="number" @input="getNum" @blur="minNum" />
					<view class="jian" @tap="jiaQuantity">+</view>
				</view>
			</view>
			</view>
			<view class="pro-p-btn dflex">
				<view :class="stock > 0 ? 'pro-add' : 'pro-addgray'" @click="addCart()">加入购物车</view>
				<view :class="'pro-buy ' + (stock > 0 ? 'mbglinear' : 'mbglinear-gray')" @click="directBuy()">{{ product.isOtc == 1 ? '预约下单' : '立即购买' }}</view>
			</view>
			<!-- <view class="confirm mbglinear" @tap="confirmBuy">确定</view> -->
		</view>
	</view>
</template>

<script>
const req = require('../../utils/request');
const utils = require('../../utils/util');

export default {
	data() {
		return {
			isShowPop: false,
			skuList: [],
			skuParam: [],
			params: [],
			//规格参数List数据
			initNum: 1,
			show_membership_price: 0,
			stock: 0,
			skuPic: '',//当前sku图片
			skuPicList: [],//sku图片列表
			skuIndex: 0
		};
	},

	components: {},
	props: {
		actId: String, //产品id
		activityId: Number, //活动id
		product: Object, //产品
		maxBuy: Number, //最大购买量
		orderType: {
			//订单类型
			type: Number,
			default: 1
		},
		isCart: {
			//是否加入购物车
			type: Boolean,
			default: false
		},
		isTimely: {
			//是否及时达
			type: Number,
			default: 0
		},
		merchant: Object, //门店
		merchantId: String, //门店id
		index: String, //荣康判断
		shopId: String //小店id
	},
	options: {
		addGlobalClass: true
	},

	// created(){
	//   console.log(this.data.merchant)
	//   req.getRequest('/api/merchant/getMerchantList',{}, res => {
	//     res = res.filter(it=>it.isDefault==1)
	//      this.setData({merchant:res[0]})
	//    })
	// },
	mounted() {
		
		this.getMerchant();
		this.getConfig();
	},

	methods: {
		loadSkuParams(from) {
			let _ts = this;
			return new Promise((resolve, reject) => {
				req.getRequest(
					'/api/product/skuParam',
					from,
					data => {
						if (data && data.length > 0) {
							_ts.skuParam = data.map(it => {
								let arr = [];
								it.params.map(its => {
									let par = {
										name: its,
										active: false,
									};
									arr.push(par);
								});
								// let stock = _ts.stock;
								// console.log('stock==' + stock);
								// if (stock > 0) {
								// 	if (_ts.product.properties) {
								// 		let propertiesList = _ts.product.properties.split(' / ');
								// 		propertiesList.map(pit => {
								// 			arr.map(its => {
								// 				if (its.name == pit) {
								// 					console.log('its.name==' + its.name+'>>>>>>pit=='+pit);
								// 					its.active = true;
								// 				}
								// 				return its;
								// 			});
								// 		});
								// 	}
								// } else {
								//遍历出默认选中有库存的规格
								// let skuList = _ts.skuList;
								// for(var i=0;i<skuList.length;i++){
								// 	var skuit=skuList[i];
								// 	var properties = JSON.parse(skuit.properties);
								// 	for(var k=0;k<properties.length;k++){
								// 		var pit=properties[k];
								// 		for(var j=0;j<arr.length;j++){
								// 			var ait=arr[j];
								// 			if(_ts.stock==0&&skuit.stock > 0 && pit.value == ait.name){
								// 				arr[j].active=true;
								// 				_ts.stock = skuit.stock;
								// 				console.log(arr[j].name+'stock222==' + _ts.stock )
								// 				// return;
								// 			}
								// 		}
								// 	}
								// }
								// }

								// console.log('arr》》》》》',JSON.stringify(arr));
								// skuList.map(skuit=>{
								// 	console.log('skuit》》》》》',skuit.properties)
								// 	var properties = JSON.parse(skuit.properties);
								// 	properties.map(pit=>{
								// 		arr.some(ait => {
								// 			if(skuit.stock > 0 && pit.value == ait.name){
								// 				ait.active = true;
								// 				_ts.stock = skuit.stock;
								// 				console.log('stock222==' + _ts.stock )
								// 			}
								// 			return ait;
								// 		})
								// 	})
								// })

								console.log('arr》》》》》', JSON.stringify(arr));
								return {
									id: it.id,
									name: it.paramName,
									params: arr
								};
							});
							console.log('_ts.skuParam==',_ts.skuParam)
							// _ts.skuList.map(it=>{
							// 	arrPic.map((arrIt,index)=>{
							// 		let properties = JSON.parse(it.properties);
							// 		properties.map(pit=>{
							// 			if(arrIt.name===pit.value){
							// 				_ts.skuPicList[index] = it.skuPic
							// 			}
							// 		})
							// 	})
							// })
							console.log('_ts.skuPicList==',_ts.skuPicList)
							//遍历出默认选中有库存的规格
							let skuList = _ts.skuList;
							for (var i = 0; i < skuList.length; i++) {
								var skuit = skuList[i];
								//如果有库存
								if (skuit.stock > 0) {
									var properties = JSON.parse(skuit.properties); //得到对应的sku组合对象

									for (var k = 0; k < properties.length; k++) {
										var pit = properties[k];
										for (var g = 0; g < _ts.skuParam.length; g++) {
											var skuArr = _ts.skuParam[g].params;
											for (var f = 0; f < skuArr.length; f++) {
												var ait = skuArr[f];
												if (pit.value == ait.name) {
													_ts.skuParam[g].params[f].active = true;
												}
											}
										}
									}
									_ts.stock = skuit.stock;
									this.setSkuData(skuit);
									return;
								}
							}
							// for (var j = 0; j < arr.length; j++) {
							// 	var ait = arr[j];
							// 	for (var i = 0; i < skuList.length; i++) {
							// 		var skuit = skuList[i];
							// 		var properties = JSON.parse(skuit.properties);
							// 		for (var k = 0; k < properties.length; k++) {
							// 			var pit = properties[k];
							// 			if (skuit.stock > 0 && pit.value == ait.name) {
							// 				arr[j].active = true;
							// 				_ts.stock = skuit.stock;
							// 				console.log(arr[j].name + 'stock222==' + _ts.stock);
							// 				return;
							// 			}
							// 		}
							// 	}
							// }
						}
						resolve();
					},
					true
				);
			});
		},

		analysisSku(propterties) {
			if (propterties === -1 || propterties === 'DEFAULT_SKU') return false;
			const ties = JSON.parse(propterties);
			this.setData({
				params: this.params.map(it => {
					let value = ties.filter(r => r.id === it.id)[0].value;
					it.active = it.nodes.indexOf(value);
					return it;
				})
			});
		},

		async getMerchant() {
			// await this.loadSkuParams();
			let _ts = this;

			let from = {
				id: this.product.id
			};
			if (!this.merchantId && this.index != 'index') {
				// console.log(222);
				from.merchantId = this.merchantId;
			} else {
				from.merchantId = this.merchantId;
			} // }

			await this.loadProductSku(from);
			await this.loadSkuParams(from);
		},

		loadProductSku(from) {
			let _ts = this;

			// console.log(from);
			if (this.actId) {
				from.actId = this.actId;
			}
			uni.showLoading({
				title: '加载中'
			})
			return new Promise((resolve, reject) => {
				req.getRequest(
					'/api/product/sku',
					from,
					res => {
						// console.log("sku数据===" + JSON.stringify(res));
						let data = {}; //将规格数据抽离出来；
						
						if (res && res.length > 0) {
							// if (res[0].properties === -1 || res[0].properties === 'DEFAULT_SKU') {
							// } else {
								res.forEach(it => {
									if (it.properties === -1 || it.properties === 'DEFAULT_SKU') {
									} else {
										it.skuStr = JSON.parse(it.properties)
											.map(ij => ij.value.replace(' ', ''))
											.join(' ');
										it.active = false;
									}
								});
								res[0].active = true;
								_ts.skuIndex = 0
								_ts.skuPic = res[0].skuPic;
								data.skuList = res;
							// }
						}else{
							if (_ts.product) {
								_ts.stock = _ts.product.stock;
							}
						}

						data['product.marketPrice'] = res[0].marketPrice;
						data['activityId'] = res[0].apId;
						data.sku = res[0]; //当是活动时销售价格统一
						// if (!_ts.data.activityId) data['product.salePrice'] = res[0].salePrice;

						// console.log(!_ts.activityId);
						// console.log('sku价格数据>>>>>==' + JSON.stringify(data.skuList));
						_ts.setData(data); // _ts.analysisSku(res[0].properties);
						data.skuList.map(it => {
							if (it.skuId === _ts.product.skuId) {
								_ts.stock = it.stock;
								// console.log('skuStock==' + _ts.stock);
							}
						});
						this.isShowPop = true;
						uni.hideLoading();
						resolve();
					},
					true
				);
			});
		},
		getConfig() {
			var _this = this;

			return new Promise((resolve, reject) => {
				req.getRequest('/api/config', {}, function(res) {
					if (res && res.show_membership_price == 1) {
						_this.setData({
							show_membership_price: 1
						});
					}

					resolve();
				});
			});
		},

		// chooseSku(event) {
		// 	const index = event.currentTarget.dataset.index;
		// 	this.skuList.forEach(it => {
		// 		it.active = false;
		// 	});
		// 	this.skuList[index].active = true;
		// 	let data = {};
		// 	data.skuList = this.skuList;
		// 	const filters = this.skuList[index]; // if (filters && filters.length > 0) {

		// 	data.sku = filters;
		// 	// this.product.skuId=filters.skuId
		// 	data['product.skuId'] = filters.skuId
		// 	data['product.marketPrice'] = filters.marketPrice;
		// 	data['product.actualPrice'] = filters.actualPrice
		// 	// this.product.marketPrice=filters.marketPrice
		// 	this.activityId = filters.apId
		// 	data['product.actId'] = filters.apId
		// 	data['product.salePrice'] = filters.salePrice;
		// 	this.setData(data); // }
		// 	this.$emit('getPor', {
		// 		detail: this.product
		// 	});
		// 	// console.log(this.product, filters.marketPrice, filters.salePrice, filters.actualPrice, filters)
		// },
		getChooseParams: function() {
			var data = [];
			this.skuParam.forEach(sku => {
				sku.params.forEach(sk => {
					if (sk.active) {
						var params = {
							id: sku.id,
							name: sk.name,
							skuPic: sk.skuPic
						};
						if (
							!data.some(dt => {
								return dt.id === sku.id;
							})
						) {
							data.push(params);
						} else {
							const chooseIndex = data.findIndex(dt => dt.id === sku.id);
							data[chooseIndex] = params;
						}
					}
				});
			});
			return data;
		},
		chooseSku(index, ind) {
			console.log('index==' + index);
			console.log('ind==' + ind);
			this.skuParam[index].params.map((it, idx) => {
				it.active = false;
				return it;
			});
			this.skuParam[index].params[ind].active = true;
			const data = this.getChooseParams();
			console.log('data==' + JSON.stringify(data));
			const filters = this.skuList.filter(it => {
				if (it.properties == -1 || it.properties == 'DEFAULT_SKU') {
				} else {
					var properties = JSON.parse(it.properties);
					if (properties.length == data.length) {
						return (
							properties.filter(pro => {
								return data.some(ds => {
									return ds.id == pro.id && ds.name == pro.value;
								});
							}).length == data.length
						);
					}
				}
				return false;
			});
			console.log('filters==', filters);
			this.skuIndex = ind;
			if (filters && filters.length > 0) {
				let sku = filters[0];
				this.sku = sku;
				console.log('sku==' + JSON.stringify(sku));
				console.log('sku.stock==' + JSON.stringify(sku.stock));
				this.stock = sku.stock;
				this.skuPic = sku.skuPic;
				if (sku.stock === 0) return req.msg('库存不足');
				this.setSkuData(sku);
			} else {
				this.stock = 0;
				req.msg('库存不足');
			}
		},

		setSkuData(sku) {
			let params = {};
			params['product.marketPrice'] = sku.marketPrice;
			params['product.actualPrice'] = sku.actualPrice;
			params['product.jianMoney'] = (sku.salePrice-sku.actualPrice).toFixed(2);
			if (!this.activityId) {
				params['product.salePrice'] = sku.salePrice;
			}
			params['product.properties'] = JSON.parse(sku.properties)
				.map(pro => {
					return pro.value;
				})
				.join(' / ');
			params['product.skuId'] = sku.skuId;
			if(this.activityId) params['product.actId'] = this.activityId
			this.setData(params);
			this.$emit('getPor', {
				detail: this.product
			});
		},

		hidePopup() {
			this.$emit('hidePopup');
		},

		jianQuantity() {
			const quantity = parseInt(this.initNum) - 1;
			this.setData({
				initNum: quantity < 1 ? 1 : quantity
			});
		},

		jiaQuantity() {
			const quantity = parseInt(this.initNum) + 1;
			if (this.product.maxBuy > 0) {
				if (quantity > this.product.maxBuy) {
					return req.msg('非常的抱歉，本产品最多可购买' + this.product.maxBuy);
				}
				if (quantity > this.stock) {
					return req.msg('非常的抱歉，本产品最多可购买' + this.stock);
				}
				this.setData({
					initNum: quantity
				});
			} else {
				this.setData({
					initNum: quantity
				});
			}
		},

		// 获取输入的值
		getNum(e) {
			const quantity = parseInt(e.detail.value);
			// console.log(e.detail.value == '');
			if (this.product.maxBuy > 0) {
				// console.log(e.detail.value, quantity);
				if (quantity > this.product.maxBuy) {
					this.setData({
						initNum: this.product.maxBuy
					});
					return req.msg('非常的抱歉，本产品最多可购买' + this.product.maxBuy);
				}
				if (quantity > this.stock) {
					this.setData({
						initNum: this.stock
					});
					return req.msg('非常的抱歉，本产品最多可购买' + this.stock);
				}
				this.setData({
					initNum: e.detail.value
				});
			} else {
				if (quantity > this.stock) {
					this.setData({
						initNum: this.stock
					});
					return req.msg('非常的抱歉，本产品最多可购买' + this.stock);
				}
				this.setData({
					initNum: e.detail.value
				});
			}
		},

		// 失去焦点
		minNum(e) {
			// console.log(this.product);
			// console.log(e.detail.value == '');

			if (e.detail.value == '') {
				this.setData({
					initNum: 1
				});
			} else {
				this.setData({
					initNum: e.detail.value
				});
			}
		},
		getParams() {
			//加入购物车
			let _ts = this;
			//直接购买
			// let merchant = req.getStorage('MERCHANT');
			// console.log(this.product);

			if (this.product.payQuantity) {
				if (this.product.stock - this.product.payQuantity < 1) return req.msg('产品已售罄，平台正在紧急补货中...');
				if (this.product.stock - this.product.payQuantity < this.initNum)
					return req.msg('购买数量超出剩余库存' + (this.product.stock - this.product.payQuantity) + '，请重新选择');
			} else {
				if (this.initNum > this.product.stock) return req.msg('非常的抱歉，本产品库存量剩余' + this.product.stock);
			} // console.log(merchant)

			const params = {
				skuId: this.product.skuId,
				quantity: this.initNum,
				productId: this.product.id
			};

			if (this.product.isOtc == 5) {
				this.setData({
					orderType: 10
				});
			} // if(this.data.merchant&&this.data.merchant.type==2&&this.data.merchantId!=''){
			//   params.merchantId=this.data.merchant.merchantDTO.id
			//   params.shopId=this.data.merchant.id
			// }else{
			//   params.merchantId=this.data.merchant.id
			// }

			if (!this.merchant) {
			} else {
				if (this.merchant.type == 5) {
					(params.shopId = this.merchant.id), (params.merchantId = this.merchant.merchantDTO.id);
				} else {
					params.merchantId = this.merchant.id;
				}
			}

			if (this.activityId) params.activityId = this.activityId;
			return params;
		},
		addCart() {
			let _ts = this;
			if (_ts.initNum == 0) return req.msg('请输入商品数量');
			if (_ts.stock === 0) return req.msg('库存不足');
			let params = _ts.getParams();
			// console.log(this.merchantId, params.merchantId);
			params.orderType = _ts.orderType;
			let isShowLoading = false;
			if (!isShowLoading) {
				req.loadIng('加载中');
				isShowLoading = true;
			}
			// console.log(params);
			req.postRequest('/api/purchase/cart', params, res => {
				if (isShowLoading) {
					uni.hideLoading();
					isShowLoading = false;
					req.msg('加入购物车成功', () => {
						_ts.$emit('addCartSuccess', {
							detail: {
								quantity: params.quantity
							}
						});
					});
				}
			});
			this.$emit('hidePopup');
		},
		directBuy() {
			let _ts = this;
			if (_ts.initNum == 0) return req.msg('请输入商品数量');
			if (_ts.stock === 0) return req.msg('库存不足');
			let params = _ts.getParams();
			// console.log(this.merchantId, params.merchantId);
			if (req.getStorage('configRes')) {
				let config = JSON.parse(req.getStorage('configRes')); // JSON.parse(req.getStorage('configRes'))

				if (config.Min_Order_Money) {
					if (parseFloat(config.Min_Order_Money - (this.show_membership_price == 1 ? this.product.actualPrice : this.product.salePrice) * this.initNum).toFixed(2) > 0)
						return req.msg('最小下单金额为' + config.Min_Order_Money + '元');
				}
			}
			let isShowLoading = false;
			if (!isShowLoading) {
				req.loadIng('加载中');
				isShowLoading = true;
			}
			req.postRequest('/api/purchase/direct/buy', params, res => {
				let redirect = '/product/subOrder/subOrder?ids=' + res;
				let orderType = this.orderType;
				// console.log(orderType); // if (orderType === 1 && this.data.isTimely === 1) orderType = 5;

				redirect += '&orderType=' + orderType;
				if (!this.merchantId) {
					redirect += '&merchantId=' + this.merchant.id;
				} else {
					redirect += '&merchantId=' + this.merchantId;
				}
				if (!this.activityId) {
				} else {
					redirect += '&activityId=' + this.activityId;
				}
				if (!this.shopId) {
				} else {
					redirect += '&shopId=' + this.shopId;
				}
				if (isShowLoading) {
					uni.hideLoading();
					isShowLoading = false;
				}
				uni.navigateTo({
					url: redirect
				});
			});
			this.$emit('hidePopup');
		},

		confirmBuy() {
			//直接购买
			// let merchant = req.getStorage('MERCHANT');
			// console.log(this.product);

			if (this.product.payQuantity) {
				if (this.product.stock - this.product.payQuantity < 1) return req.msg('产品已售罄，平台正在紧急补货中...');
				if (this.product.stock - this.product.payQuantity < this.initNum)
					return req.msg('购买数量超出剩余库存' + (this.product.stock - this.product.payQuantity) + '，请重新选择');
			} else {
				if (this.initNum > this.product.stock) return req.msg('非常的抱歉，本产品库存量剩余' + this.product.stock);
			} // console.log(merchant)

			// console.log(this.product);
			const params = {
				skuId: this.product.skuId,
				quantity: this.initNum,
				productId: this.product.id
			};

			if (this.product.isOtc == 5) {
				this.setData({
					orderType: 10
				});
			} // if(this.data.merchant&&this.data.merchant.type==2&&this.data.merchantId!=''){
			//   params.merchantId=this.data.merchant.merchantDTO.id
			//   params.shopId=this.data.merchant.id
			// }else{
			//   params.merchantId=this.data.merchant.id
			// }

			if (!this.merchant) {
			} else {
				if (this.merchant.type == 5) {
					(params.shopId = this.merchant.id), (params.merchantId = this.merchant.merchantDTO.id);
				} else {
					params.merchantId = this.merchant.id;
				}
			}

			if (this.activityId) params.activityId = this.activityId;
			// console.log(this.merchantId, params.merchantId);
			if (this.isCart) {
				//加入购物车
				let _ts = this;
				params.orderType = this.orderType;
				let isShowLoading = false;
				if (!isShowLoading) {
					req.loadIng('加载中');
					isShowLoading = true;
				}
				// console.log(params);
				req.postRequest('/api/purchase/cart', params, res => {
					if (isShowLoading) {
						uni.hideLoading();
						isShowLoading = false;
						req.msg('加入购物车成功', () => {
							_ts.$emit('addCartSuccess', {
								detail: {
									quantity: params.quantity
								}
							});
						});
					}
				});
			} else {
				if (req.getStorage('configRes')) {
					let config = JSON.parse(req.getStorage('configRes')); // JSON.parse(req.getStorage('configRes'))

					if (config.Min_Order_Money) {
						if (
							parseFloat(config.Min_Order_Money - (this.show_membership_price == 1 ? this.product.actualPrice : this.product.salePrice) * this.initNum).toFixed(2) > 0
						)
							return req.msg('最小下单金额为' + config.Min_Order_Money + '元');
					}
				}
				let isShowLoading = false;
				if (!isShowLoading) {
					req.loadIng('加载中');
					isShowLoading = true;
				}
				req.postRequest('/api/purchase/direct/buy', params, res => {
					let redirect = '/product/subOrder/subOrder?ids=' + res;
					let orderType = this.orderType;
					// console.log(orderType); // if (orderType === 1 && this.data.isTimely === 1) orderType = 5;

					redirect += '&orderType=' + orderType;
					if (!this.merchantId) {
					} else {
						redirect += '&merchantId=' + this.merchantId;
					}
					if (!this.activityId) {
					} else {
						redirect += '&activityId=' + this.activityId;
					}
					if (!this.shopId) {
					} else {
						redirect += '&shopId=' + this.shopId;
					}
					if (isShowLoading) {
						uni.hideLoading();
						isShowLoading = false;
					}
					uni.navigateTo({
						url: redirect
					});
				});
			}

			this.$emit('hidePopup');
		},
		previewSkuPic(){
			let that = this;
			let arr = []
			if(this.skuPic){
				arr[0] = this.skuPic;
			}else{
				arr[0] = this.product.pic
			}
			console.log('arr=====',arr)
			uni.previewImage({
				current: this.skuIndex, //当前为第几张
				urls: arr,
				complete() {
					that.$emit('freshen', this);
				}
				// indicator: 'number',
				// loop: true
			});
		}
	}
};
</script>
<style>
@import './index.css';
</style>
