<template>
	<view class="waterfalls-flow">
		<view v-for="(item, index) in data.column" :key="index" class="waterfalls-flow-column"
			:id="`waterfalls_flow_column_${index + 1}`" :msg="msg" :style="{ 'width': w, 'margin-left': index == 0 ? 0 : m }">
			<view :class="['column-value', { 'column-value-show': item2.o }]" v-for="(item2, index2) in columnValue(index)"
				:key="index2" :style="[s1]" @click.stop="wapperClick(item2)">
				 <image
					:class="['img', { 'img-hide': item2[hideImageKey] == true || item2[hideImageKey] == 1 }, { 'img-error': !item2[data.imageKey] }]"
					:src="item2[data.imageKey]" mode="widthFix" @load="imgLoad(item2, index + 1)"
					@error="imgError(item2, index + 1)" @click.stop="imageClick(item2)">
				</image>
				<view class="inner">
					<view>
						<view class="good-name">{{ item2.name }}</view>
						<view class="countTime-wrap">
							<view class="countTime"
								v-if="item2.actType === 5 && item2.actPrice !== 0 && item2.trendType !== 0 && timeTen">
								{{ item2.trendType === 2 ? '降价' : '升价' }}还剩 {{ skunameMsg }}</view>
						</view>
						
						<view class="priceStyle" v-if="item2.unit">
							<text>每</text>
							<text v-if="isB2B && storeID[0] !== 666666">斤</text>
							<span v-else>{{ item2.unit }}</span>
							<text>约为</text>
							<span class="priceColor" >{{ $filters.toFixed2(item2.curPrice) }}</span>
							<text>元(以实际价格为准)</text>
						</view>
						<view class="good-price">
							<view class="price">
								<view class="price-text">
									<span class="good-price-font" v-if="isB2B || storeID[0] === 666666">{{((item2.curPrice/100).toFixed(2)).split('.')[0] + '.' + ((item2.curPrice/100).toFixed(2)).split('.')[1] }}</span>
									<span class="good-price-font" v-else-if="item2.weight">{{(((((item2.curPrice/100)/item2.weight)*500)/100).toFixed(2)).split('.')[0] + '.' + (((((item2.curPrice/100)/item2.weight)*500)/100).toFixed(2)).split('.')[1] }}</span>
									<span class="good-price-font" v-else>{{(((((item2.curPrice/100))*500)/100).toFixed(2)).split('.')[0] + '.' + (((((item2.curPrice/100))*500)/100).toFixed(2)).split('.')[1] }}</span>
								</view>
								<span class="unit" v-if="storeID[0] === 666666 || isB2B">/{{item2.unit}}</span>
								<text class="unit" v-else>/斤</text>
								<view class="ori-price" v-if="item2.oriPrice && !isMaterial" >{{$filters.toFixed2(item2.oriPrice)}}</view>
							</view>
						 
							<view class="act-type-wrapper">
								<view class="act-type" v-if="item2.actType">{{actTypeArr[item2.actType]}}</view>
							</view>
						</view>
						<view v-if="isShowShop">
							<PlusMinus :type="'input'" :skuName="item2"  :count="item2.count"  @clickPlus="skuNamePlusRecommend(item2.index)"  @clickMinus="skuNameMinusRecommend(item2.index)" @countChange="skuNameChangeRecommend($event,item2.index)" ></PlusMinus>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>

	<!-- 加载更多 -->
	<view v-if="!isMaterial" style="background:#fff;margin-top:20rpx" :style="{'background-color':topGoodsStatus === 'loading'?'#f4f4f4':'#fff'}">
		<uni-load-more :status="topGoodsStatus" ></uni-load-more>
	</view>

	<!-- <div
				class="nearlyStores"
				v-for="(item, index) in nearlyStores"
				:key="index"
				@click="clickMore(item)"
				>	
					商家信息
					<div class="storeInfo">
						<div style="display: flex;align-items: center;">
							<image :src="$filters.urlToHttps(item.storeInfo.brandLogo)" class="storeImg" alt="" />
						</div>
						<div v-if="item.storeInfo.status===-1" class="storeStatus">休息中</div>
						<div class="storeRight">
						<div class="storeName" style="display: flex;">
							<div >{{item.storeInfo.brandName}}</div>
							<div>{{item.storeInfo.storeName }}</div>
							<div>--</div>
							<div>{{ item.storeInfo.brandName }}</div>
						</div>
						营业时间
						<span class="storeTime">营业时间：</span>
						<span class="storeTime1" v-if="item.storeInfo.openTime1 && item.storeInfo.closeTime1">{{$filters.processingHours(item.storeInfo.openTime1)}}-{{$filters.processingHours(item.storeInfo.closeTime1)}}</span>
						<span class="storeTime2" v-if="item.storeInfo.openTime2 && item.storeInfo.closeTime2">{{$filters.processingHours(item.storeInfo.openTime2)}}-{{$filters.processingHours(item.storeInfo.closeTime2)}}</span>
						评分
						<div class="storeRate">
							<div>门店评分：</div>
							<div v-if="item.storeInfo && item.storeInfo.storeWeeklyScore">
								<uni-rate :size="20" allow-half :value="(item.storeInfo.storeWeeklyScore *5) /100" />
							</div>
							<div v-else>暂无评分</div>
						</div>
						满减
						<div class="fullReduce">
							<div v-if="item.StoreDeductionInfo[0].deliveryFeeDeductionFee && item.StoreDeductionInfo[0].deliveryFeeDeductionSill" class="fullReduceFee">
							满{{item.StoreDeductionInfo[0].deliveryFeeDeductionSill/100}}减{{item.StoreDeductionInfo[0].deliveryFeeDeductionFee/100}}
							</div>
							距离
							<div v-if="String(item.storeInfo.distance).length<=3">距您{{item.storeInfo.distance}}m</div>
							<div v-else>距您{{(item.storeInfo.distance/1000).toFixed(2)}}km</div>
						</div>
						</div>
					</div>
					商品
					<div class="storeGood" v-if="item.StoreSkuInfo!==null" @click.stop="clickStop">
						<div v-for="(ite,i) in item.StoreSkuInfo" :key="i" class="storeGoodItem"  @click="toDetail(ite)">
						<img :src="$filters.urlToHttps(ite.img,'img120')" class="storeGoodImg">
						<image :src="$filters.urlToHttps(ite.img)" class="storeGoodImg"  alt="" />
						<div class="storeGoodName" >{{ite.skuName}}</div>
						<div class="storeGoodPrice" >{{(ite.price/100).toFixed(2)}}元/{{ite.unit}}</div>
						</div>
						<div class="storeGoodMore" @click="clickMore(item)">
						查看更多
						</div>
					</div>
					<div class="enterStore" v-else >
						<div style="padding:20rpx;background:rgba(78, 179, 49, 0.9);color:#fff;border-radius: 10rpx;border:1rpx solid red;"> </div>
					</div>
				</div> -->
</template>

<script>
import PlusMinus from "@/components/goodCmp/plus-minus/plus-minus";
import { mapGetters } from "vuex";
import { jumpPage } from "@/utils/uniapi.js";
export default {
	props: {
		value: Array,
		column: { // 列的数量 
			type: [String, Number],
			default: 2
		},
		maxColumn: { // 最大列数 
			type: [String, Number],
			default: 5
		},
		columnSpace: { // 列之间的间距 百分比
			type: [String, Number],
			default: 2
		},
		imageKey: { // 图片key
			type: [String],
			default: 'image'
		},
		hideImageKey: { // 隐藏图片key
			type: [String],
			default: 'hide'
		},
		seat: { // 文本的位置，1图片之上 2图片之下
			type: [String, Number],
			default: 2
		},
		listStyle: { // 单个展示项的样式：eg:{'background':'red'}
			type: Object
		}
	},
	components: {
		PlusMinus
	},
	data() {
		return {
			data: {
				list: this.value ? this.value : [],
				column: this.column < 2 ? 2 : this.column,
				columnSpace: this.columnSpace <= 5 ? this.columnSpace : 5,
				imageKey: this.imageKey,
				seat: this.seat
			},
			msg: 0,
			listInitStyle: {
				'border-radius': '12rpx',
				'margin-bottom': '20rpx',
				'background-color': '#fff'
			},
			adds: [], //预置数据
			isLoaded: true,
			curIndex: 0,
			isRefresh: true,
			flag: false,
			refreshDatas: [],
			skunameMsg: '',
			topGoodsStatus:'loading',
			actTypeArr:['','','','直降','秒杀','折扣']
		}
	},
	computed: {
		...mapGetters({
			isB2B: 'indexPage/isB2B',
			isMaterial: "indexPage/isMaterial",
			storeID:"indexPage/storeID",
			isShowShop: "isShowShop"
		}),
		// 计算列宽
		w() {
			const column_rate = `${100 / this.data.column - (+this.data.columnSpace)}%`;
			return column_rate;
		},
		// 计算margin
		m() {
			const column_margin = `${(100 - (100 / this.data.column - (+this.data.columnSpace)).toFixed(5) * this.data.column) / (this.data.column - 1)}%`;
			return column_margin;
		},
		// list样式
		s1() {
			return { ...this.listInitStyle, ...this.listStyle };
		}
	},
	created() {
		// 初始化
		this.refresh();
	},
	methods: {
		// 添加
		skuNamePlusRecommend(index) {
			this.$emit('clickPlus',index)
		},
		// 减少
		skuNameMinusRecommend(index) {
			this.$emit('clickMinus',index)
		},
		// 商品数量发生改变
		skuNameChangeRecommend(e,index) {
			this.$emit('countChange',e,index)
		},
		// 预加载图片
		loadImages(idx = 0) {
			let count = 0;
			const newList = this.data.list.filter((item, index) => index >= idx);
			for (let i = 0; i < newList.length; i++) {
				// #ifndef APP-PLUS || APP
				uni.getImageInfo({
					src: `${newList[i][this.imageKey]}.jpg`,
					complete: res => {
						count++;
						if (count == newList.length) this.initValue(idx);
					}
				})
				// #endif
				// #ifdef APP-PLUS || APP
				plus.io.getImageInfo({
					src: `${newList[i][this.imageKey]}.jpg`,
					complete: res => {
						count++;
						if (count == newList.length) this.initValue(idx);
					}
				})
				// #endif
			}
		},
		// 刷新
		refresh() {
			if (!this.isLoaded) {
				this.refreshDatas = this.value;
				return false;
			};
			this.topGoodsStatus = 'loading'
			this.refreshDatas = [];
			this.isRefresh = true;
			this.adds = [];
			this.data.list = this.value ? this.value : [];
			this.data.column = this.column < 2 ? 2 : this.column >= this.maxColumn ? this.maxColumn : this.column;
			this.data.columnSpace = this.columnSpace <= 5 ? this.columnSpace : 5;
			this.data.imageKey = this.imageKey;
			this.data.seat = this.seat;
			this.curIndex = 0;
			// 每列的数据初始化
			for (let i = 1; i <= this.data.column; i++) {
				this.data[`column_${i}_values`] = [];
				this.msg++;
			}
			this.$nextTick(() => {
				this.initValue(this.curIndex, 'refresh==>');
			})
		},
		columnValue(index) {
			return this.data[`column_${index + 1}_values`]
		},
		change(newValue) {
			console.log('this.data9999999999',this.data)
			for (let i = 0; i < this.data.list.length; i++) {
				console.log(i,'i',this.data.list[i],'属于哪一列',this.data.list[i].column)
				const cv = this.data[`column_${this.data.list[i].column}_values`];
				for (let j = 0; j < cv.length; j++) {
					if (newValue[i] && i === cv[j].index) {
						this.data[`column_${this.data.list[i].column}_values`][j] = Object.assign(cv[j], newValue[i]);
						this.msg++;
						break;
					}
				}
			}
		},
		getMin(a, s) {
			let m = a[0][s];
			let mo = a[0];
			for (var i = a.length - 1; i >= 0; i--) {
				if (a[i][s] < m) {
					m = a[i][s];
				}
			}
			mo = a.filter(i => i[s] == m);
			return mo[0];
		},
		// 计算每列的高度
		getMinColumnHeight() {
			return new Promise(resolve => {
				const heightArr = [];
				for (let i = 1; i <= this.data.column; i++) {
					const query = uni.createSelectorQuery().in(this);
					query.select(`#waterfalls_flow_column_${i}`).boundingClientRect(data => {
						heightArr.push({ column: i, height: data.height });
					}).exec(() => {
						if (this.data.column <= heightArr.length) {
							resolve(this.getMin(heightArr, 'height'));
						}
					});
				}
			})
		},
		async initValue(i, from) {
			this.isLoaded = false;
			if (i >= this.data.list.length || this.refreshDatas.length) {
				this.msg++;
				this.loaded();
				return false;
			}
			const minHeightRes = await this.getMinColumnHeight();
			const c = this.data[`column_${minHeightRes.column}_values`];
			this.data.list[i].column = minHeightRes.column;
			c.push({ ...this.data.list[i], cIndex: c.length, index: i, o: 0 });
			this.msg++;
			this.topGoodsStatus = 'noMore'
		},
		// 图片加载完成
		imgLoad(item, c) {
			const i = item.index;
			item.o = 1;
			this.$set(this.data[`column_${c}_values`], item.cIndex, JSON.parse(JSON.stringify(item)));
			this.initValue(i + 1);
		},
		// 图片加载失败
		imgError(item, c) {
			const i = item.index;
			item.o = 1;
			item[this.data.imageKey] = null;
			this.$set(this.data[`column_${c}_values`], item.cIndex, JSON.parse(JSON.stringify(item)));
			this.initValue(i + 1);
		},
		// 渲染结束
		loaded() {
			if (this.refreshDatas.length) {
				this.isLoaded = true;
				this.refresh();
				return false;
			}
			this.curIndex = this.data.list.length;
			if (this.adds.length) {
				this.data.list = this.adds[0];
				this.adds.splice(0, 1);
				this.initValue(this.curIndex);
			} else {
				if (this.data.list.length) this.$emit('loaded');
				this.isLoaded = true;
				this.isRefresh = false;
			}
		},
		// 单项点击事件
		wapperClick(item) {
			jumpPage('navigateTo',`/pagesGoods/good-detail/index?skuID=${item.id}&storeID=${this.storeID[0]}`)
			// this.$emit('wapperClick', item);
		},
		// 图片点击事件
		imageClick(item) {
			jumpPage('navigateTo',`/pagesGoods/good-detail/index?skuID=${item.id}&storeID=${this.storeID[0]}`)
			// this.$emit('imageClick', item);
		}
	},
	watch: {
		value: {
			deep: true,
			handler(newValue, oldValue) {
				setTimeout(() => {
					this.$nextTick(() => {
						if (this.isRefresh) return false;
						if (this.isLoaded) {
							// if (newValue.length <= this.curIndex) return this.refresh();
							if (newValue.length <= this.curIndex) return this.change(newValue);
							this.data.list = newValue;
							this.$nextTick(() => {
								this.initValue(this.curIndex, 'watch==>');
							})
						} else {
							this.adds.push(newValue);
						}
					})
				}, 1000)
			}
		},
		column(newValue) {
			this.refresh();
		}
	}
}
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
