<template>

	<view :style="{'background-color':pageBg}">
		<view v-if="!hideTop" :style="{'height':totalHeightPx,'background-color': barColor,'box-sizing': 'border-box','width':'100%',
				'z-index':'9900','position':'fixed','top':'--window-top','left':'0'}">
			<view :style="{'height':statusBarHeightPx}">
			</view>
			<view
				:style="{'height':navHeightPx,'width':navWidthPx,'display': 'flex','flex-direction':'row','box-sizing': 'border-box','justify-content': 'space-between'}">
				<view
					:style="{'height':navHeightPx,'display': 'flex','flex-direction':'row','box-sizing': 'border-box'}">
					<image :style="{'height':navHeightPx,'width':iconPx,'flex-shrink':0}" mode="aspectFit"
						:src="backIcon" @click="clickBack"></image>
					<text class="titleStyle"
						:style="{'height':navHeightPx,'line-height':navHeightPx,'font-size':'33rpx','color':'#FFFFFF'}">{{text}}</text>
				</view>

				<view
					:style="{'height':navHeightPx,'display': 'flex','flex-direction':'row','box-sizing': 'border-box'}">
					<view v-if="useTitleLeftBtn!=0"
						:style="{'height':navHeightPx,'display': 'flex','flex-direction':'row','box-sizing': 'border-box'}"
						@click="clickLeftBtn">
						<image v-if="useTitleLeftBtn == 2 && dropLeftList.length == 0"
							:style="{'height':navHeightPx,'width':navHeightPx}" mode="aspectFit"
							:src="titleLeftBtnSource"></image>
						<text v-if="useTitleLeftBtn == 1 && dropLeftList.length == 0"
							:style="{'height':navHeightPx,'line-height':navHeightPx,'font-size':'28rpx','color':'#FFFFFF','padding-left':'20rpx','padding-right':'20rpx'}">{{titleLeftBtnSource}}</text>
						<drop-item ref="dropview" :candidates="dropLeftList" :btnType="useTitleLeftBtn"
							:btnSource="titleLeftBtnSource" @onselect="selectDrop"></drop-item>
					</view>
					<view v-if="useTitleRightBtn!=0"
						:style="{'height':navHeightPx,'display': 'flex','flex-direction':'row','box-sizing': 'border-box'}"
						@click="clickRightBtn">
						<image v-if="useTitleRightBtn==2 && dropRightList.length == 0"
							:style="{'height':navHeightPx,'width':navHeightPx}" mode="aspectFit"
							:src="titleRightBtnSource"></image>
						<text v-if="useTitleRightBtn==1 && dropRightList.length == 0"
							:style="{'height':navHeightPx,'line-height':navHeightPx,'font-size':'28rpx','color':'#FFFFFF','padding-left':'20rpx','padding-right':'20rpx'}">{{titleRightBtnSource}}</text>
						<drop-item ref="dropview" :candidates="dropRightList" :btnType="useTitleRightBtn"
							:btnSource="titleRightBtnSource" @onselect="selectDrop"></drop-item>
					</view>
				</view>
			</view>
		</view>

		<view class="mescroll-body"
			:style="{'minHeight':minHeight, 'padding-top': totalHeightPx, 'padding-bottom': padBottom, 'padding-bottom': padBottomConstant, 'padding-bottom': padBottomEnv }"
			@touchstart="touchstartEvent" @touchmove="touchmoveEvent" @touchend="touchendEvent"
			@touchcancel="touchendEvent">
			<view class="mescroll-body-content" :style="{ transform: translateY, transition: transition }">
				<!-- 下拉加载区域 (支付宝小程序子组件传参给子子组件仍报单项数据流的异常,暂时不通过mescroll-down组件实现)-->
				<!-- <mescroll-down :option="mescroll.optDown" :type="downLoadType"></mescroll-down> -->
				<view v-if="useDownScroll" class="mescroll-downwarp"
					:style="{'background-color':mescroll.optDown.bgColor,'color':mescroll.optDown.textColor}">
					<view class="downwarp-content">
						<image class="downwarp-slogan" src="../../static/img/public/mescroll-slogan.png"
							mode="widthFix" />
						<view v-if="isDownLoading" class="downwarp-loading mescroll-rotate"></view>
						<view v-else class="downwarp-progress" :style="{'transform':downRotate}"></view>
					</view>
				</view>

				<sl-filter id="header" ref="slLilter" v-if="menuList.length!=0" :color="titleColor" :themeColor="themeColor"
					:menuList.sync="menuList" @result="result" ></sl-filter>

				<!-- 列表内容 -->
				<slot></slot>

				<!-- 空布局 -->
				<mescroll-empty v-if="isShowEmpty" :option="mescroll.optUp.empty" @emptyclick="emptyClick">
				</mescroll-empty>

				<!-- 上拉加载区域 (下拉刷新时不显示, 支付宝小程序子组件传参给子子组件仍报单项数据流的异常,暂时不通过mescroll-up组件实现)-->
				<!-- <mescroll-up v-if="mescroll.optUp.use && !isDownLoading" :option="mescroll.optUp" :type="upLoadType"></mescroll-up> -->
				<view v-if="useUpScroll && !isDownLoading" class="mescroll-upwarp"
					:style="{'background-color':mescroll.optUp.bgColor,'color':mescroll.optUp.textColor}">
					<!-- 加载中 (此处不能用v-if,否则android小程序快速上拉可能会不断触发上拉回调) -->
					<view v-if="upLoadType===1">
						<view class="upwarp-progress mescroll-rotate"
							:style="{'border-color':mescroll.optUp.textColor}"></view>
						<view class="upwarp-tip">{{ mescroll.optUp.textLoading }}</view>
					</view>
					<!-- 无数据 -->
					<view v-if="upLoadType===2" class="upwarp-nodata">{{ mescroll.optUp.textNoMore }}</view>
				</view>
			</view>

			<!-- 回到顶部按钮 (fixed元素需写在transform外面,防止降级为absolute)-->
			<mescroll-top v-model="isShowToTop" :option="mescroll.optUp.toTop" @click="toTopClick"></mescroll-top>
		</view>

	</view>

</template>

<script>
	import MeScroll from '../mescroll-uni/mescroll-uni.js';
	import MescrollEmpty from '../mescroll-uni/components/mescroll-empty.vue';
	import MescrollTop from '../mescroll-uni/components/mescroll-top.vue';
	import GlobalOption from '../mescroll-uni/mescroll-uni-option.js';
	import RefreshOption from './refresh-option.js';
	import slFilter from '@/components/sl-filter/sl-filter.vue';

	export default {
		components: {
			MescrollEmpty,
			MescrollTop,
			slFilter
		},
		data() {
			return {
				mescroll: null, // mescroll实例
				downHight: 0, //下拉刷新: 容器高度
				downLoadType: 4, // 下拉刷新状态 （inOffset：1， outOffset：2， showLoading：3， endDownScroll：4）
				upLoadType: 0, // 上拉加载状态：0（loading前），1（loading中），2（没有更多了）
				isShowEmpty: false, // 是否显示空布局
				isShowToTop: false, // 是否显示回到顶部按钮
				windowHeight: 0, // 可使用窗口的高度
				statusBarH: 0, // 状态栏高度
				statusBarHeight: "",
				navHeight: "",
				navWidth: "",
				totalHeight: "",
				statusBarHeightPx: "",
				navHeightPx: "",
				navWidthPx: "",
				totalHeightPx: "",
				bg: "#2fa1f0",
				totalHeightUpx: "",
				backIcon: "",
				iconPx: "",
				LeftPos: '0px',
				themeColor: '#000000',
				titleColor: '#fd6d2a',
				hideTop: false
			};
		},
		props: {
			down: Object, // 下拉刷新的参数配置
			up: Object, // 上拉加载的参数配置
			top: [String, Number], // 下拉布局往下的偏移量 (支持20, "20rpx", "20px", "20%"格式的值, 其中纯数字则默认单位rpx, 百分比则相对于windowHeight)
			topbar: Boolean, // top的偏移量是否加上状态栏高度, 默认false (使用场景:取消原生导航栏时,配置此项可自动加上状态栏高度的偏移量)
			bottom: [String, Number], // 上拉布局往上的偏移量 (支持20, "20rpx", "20px", "20%"格式的值, 其中纯数字则默认单位rpx, 百分比则相对于windowHeight)
			safearea: Boolean, // bottom的偏移量是否加上底部安全区的距离, 默认false (需要适配iPhoneX时使用)
			height: [String, Number], // 指定mescroll最小高度,默认windowHeight,使列表不满屏仍可下拉
			text: {
				type: String,
				default: ""
			},
			pageBg: {
				type: String,
				default: "#FFFFFF"
			},
			barColor: {
				type: String,
				default: "#2fa1f0"
			},
			hasBack: {
				type: Boolean,
				default: true
			},
			isShareIn: {
				type: Boolean,
				default: false
			},
			isInterceptBack: {
				type: Boolean,
				default: false
			},
			useUpScroll: {
				type: Boolean,
				default: true
			},
			useDownScroll: {
				type: Boolean,
				default: true
			},
			useTitleLeftBtn: {
				type: String,
				// 0不使用 1使用文字 2使用图片
				default: "0"
			},
			useTitleRightBtn: {
				type: String,
				// 0不使用 1使用文字 2使用图片
				default: "0"
			},
			titleLeftBtnSource: {
				type: String,
				default: ""
			},
			titleRightBtnSource: {
				type: String,
				default: ""
			},
			dropLeftList: {
				type: Array,
				default () {
					return []
				}
			},
			dropRightList: {
				type: Array,
				default () {
					return []
				}
			},
			dropShow: {
				type: Boolean,
				default: true
			},
			menuList: {
				type: Array,
				default () {
					return []
				}
			}
		},
		computed: {
			// mescroll最小高度,默认windowHeight,使列表不满屏仍可下拉
			minHeight() {
				return this.toPx(this.height || '100%') + 'px'
			},
			// 下拉布局往下偏移的距离 (px)
			numTop() {
				return this.toPx(this.top) + (this.topbar ? this.statusBarH : 0);
			},
			padTop() {
				return this.numTop + 'px';
			},
			// 上拉布局往上偏移 (px)
			numBottom() {
				return this.toPx(this.bottom);
			},
			padBottom() {
				return this.numBottom + 'px';
			},
			padBottomConstant() {
				return this.isSafearea ? 'calc(' + this.padBottom + ' + constant(safe-area-inset-bottom))' : this
					.padBottom;
			},
			padBottomEnv() {
				return this.isSafearea ? 'calc(' + this.padBottom + ' + env(safe-area-inset-bottom))' : this.padBottom;
			},
			// 是否为重置下拉的状态
			isDownReset() {
				return this.downLoadType === 3 || this.downLoadType === 4;
			},
			// 过渡
			transition() {
				return this.isDownReset ? 'transform 300ms' : this.downTransition;
			},
			translateY() {
				return this.downHight > 0 ? 'translateY(' + this.downHight + 'px)' :
					''; // transform会使fixed失效,需注意把fixed元素写在mescroll之外
			},
			// 是否在加载中
			isDownLoading() {
				return this.downLoadType === 3
			},
			// 旋转的角度
			downRotate() {
				return this.downLoadType === 2 ? 'rotate(180deg)' : 'rotate(0deg)'
			}
		},
		methods: {
			refreshTitle(obj) {
				this.$refs.slLilter.setTitle(obj)
			  },
			  reset(){
				this.$refs.slLilter.resetSelectToDefault(function(e) {
					callback(e);
				});
			  },
			result(val) {
				console.log("val：", JSON.stringify(val));
				this.$emit('result', JSON.stringify(val))
			},
			selectDrop(index, data) {
				let left = this.arrSame(data, this.dropLeftList);
				this.$emit("drop", index, left, (left ? this.dropLeftList[index] : this.dropRightList[index]))
			},
			clickLeftBtn() {
				this.$emit("leftBtn", "左侧按钮")
			},
			clickRightBtn() {
				this.$emit("rightBtn", "右侧按钮")
			},
			clickBack() {
				if (this.hasBack) {

					if (getCurrentPages().length > 1) {

						if (this.isInterceptBack) {
							this.$emit("backClick")
						} else {
							this.Back()
						}

					} else {
						if (RefreshOption.homePageIsTabBar) {
							uni.switchTab({
								url: RefreshOption.homePagePath
							})
						} else {
							uni.navigateTo({
								url: RefreshOption.homePagePath
							})
						}
					}
				}
			},
			//number,rpx,upx,px,% --> px的数值
			toPx(num) {
				if (typeof num === 'string') {
					if (num.indexOf('px') !== -1) {
						if (num.indexOf('rpx') !== -1) {
							// "10rpx"
							num = num.replace('rpx', '');
						} else if (num.indexOf('upx') !== -1) {
							// "10upx"
							num = num.replace('upx', '');
						} else {
							// "10px"
							return Number(num.replace('px', ''));
						}
					} else if (num.indexOf('%') !== -1) {
						// 传百分比,则相对于windowHeight,传"10%"则等于windowHeight的10%
						let rate = Number(num.replace('%', '')) / 100;
						return this.windowHeight * rate;
					}
				}
				return num ? uni.upx2px(Number(num)) : 0;
			},
			//注册列表touchstart事件,用于下拉刷新
			touchstartEvent(e) {
				if (this.$props.useDownScroll) {
					this.mescroll.touchstartEvent(e);
				}
			},
			//注册列表touchmove事件,用于下拉刷新
			touchmoveEvent(e) {
				if (this.$props.useDownScroll) {
					this.mescroll.touchmoveEvent(e);
				}
			},
			//注册列表touchend事件,用于下拉刷新
			touchendEvent(e) {
				if (this.$props.useDownScroll) {
					this.mescroll.touchendEvent(e);
				}
			},
			// 点击空布局的按钮回调
			emptyClick() {
				this.$emit('emptyclick', this.mescroll);
			},
			// 点击回到顶部的按钮回调
			toTopClick() {
				this.mescroll.scrollTo(0, this.mescroll.optUp.toTop.duration); // 执行回到顶部
				this.$emit('topclick', this.mescroll); // 派发点击回到顶部按钮的回调
			},
			refreshFinished(currentPageListSize) {

				if (currentPageListSize == undefined || currentPageListSize == null || currentPageListSize === "") {
					this.mescroll.endSuccess();
				} else {
					this.mescroll.endSuccess(currentPageListSize);
				}
			},
			refreshError() {
				this.mescroll.endErr();
			},
			resetPageOne() {
				this.mescroll.resetUpScroll()
				// 防止刷新的时候 显示不是第一个
				this.toTopClick()
			},
			closeDrop() {
				// 关闭框
				if (this.$refs.dropview != undefined)
					this.$refs.dropview.closeDropItem()
			},
			/**
			 * 验证两个object 是否相同
			 * @param {Object} obj  [需要进行验证的数据1]
			 * @param {Object} newObj [需要进行验证的数据2]
			 */
			objSame(obj, newObj) {
				let bol = true;
				if (Object.keys(obj).length != Object.keys(newObj).length) {
					return false;
				}
				for (let key in obj) {
					if (obj[key] instanceof Object) {
						bol = this.objSame(obj[key], newObj[key]);
						if (!bol) {
							break;
						}
					} else if (obj[key] instanceof Array) {
						bol = arrSame(obj[key], newObj[key])
						if (!bol) {
							break;
						}
					} else if (obj[key] != newObj[key]) {
						bol = false;
						break;
					}
				}
				return bol
			},

			/**
			 * 验证两个数组是否相同
			 * @param {Array} arr  [需要进行验证的数据1]
			 * @param {Array} newArr [需要进行验证的数据2]
			 */
			arrSame(arr, newArr) {
				let bol = true;
				if (arr.length != newArr.length) {
					return false;
				}
				for (let i = 0, n = arr.length; i < n; i++) {
					if (arr[i] instanceof Array) {
						bol = arrSame(arr[i], newArr[i])
						if (!bol) {
							break;
						}
					} else if (arr[i] instanceof Object) {
						bol = this.objSame(arr[i], newArr[i])
						if (!bol) {
							break;
						}
					} else if (arr[i] != newArr[i]) {
						bol = false;
						break;
					}
				}
				return bol;
			}
		},
		// 使用created初始化mescroll对象; 如果用mounted部分css样式编译到H5会失效
		created() {

			this.navWidth = getApp().globalData.navWidth
			this.navHeight = getApp().globalData.navHeight
			this.totalHeight = getApp().globalData.totalHeight
			this.statusBarHeight = getApp().globalData.statusBarHeight
			this.navWidthPx = getApp().globalData.navWidthPx
			this.navHeightPx = getApp().globalData.navHeightPx
			this.totalHeightPx = getApp().globalData.totalHeightPx
			this.statusBarHeightPx = getApp().globalData.statusBarHeightPx
			this.totalHeightUpx = getApp().globalData.totalHeightUpx

			if (this.$props.hasBack) {
				this.backIcon = getCurrentPages().length > 1 ? RefreshOption.backIcon : RefreshOption.homeIcon
				this.iconPx = this.navHeightPx
			} else {
				this.backIcon = '../../static/custom-icon/no-back.png'
				this.iconPx = this.navHeight / 8 * 3 + 'px'
			}


			let vm = this;

			let diyOption = {
				// 下拉刷新的配置
				down: {
					inOffset(mescroll) {
						vm.downLoadType = 1; // 下拉的距离进入offset范围内那一刻的回调 (自定义mescroll组件时,此行不可删)
					},
					outOffset(mescroll) {
						vm.downLoadType = 2; // 下拉的距离大于offset那一刻的回调 (自定义mescroll组件时,此行不可删)
					},
					onMoving(mescroll, rate, downHight) {
						// 下拉过程中的回调,滑动过程一直在执行;
						vm.downHight = downHight; // 设置下拉区域的高度 (自定义mescroll组件时,此行不可删)
					},
					showLoading(mescroll, downHight) {
						vm.downLoadType = 3; // 显示下拉刷新进度的回调 (自定义mescroll组件时,此行不可删)
						vm.downHight = downHight; // 设置下拉区域的高度 (自定义mescroll组件时,此行不可删)
					},
					endDownScroll(mescroll) {
						vm.downLoadType = 4; // 结束下拉 (自定义mescroll组件时,此行不可删)
						vm.downHight = 0; // 设置下拉区域的高度 (自定义mescroll组件时,此行不可删)
					},
					// 派发下拉刷新的回调
					callback: function(mescroll) {
						vm.mescroll.resetUpScroll()
					}
				},
				// 上拉加载的配置
				up: {
					// 显示加载中的回调
					showLoading() {
						vm.upLoadType = 1;
					},
					// 显示无更多数据的回调
					showNoMore() {
						vm.upLoadType = 2;
					},
					// 隐藏上拉加载的回调
					hideUpScroll() {
						vm.upLoadType = 0;
					},
					// 空布局
					empty: {
						onShow(isShow) {
							// 显示隐藏的回调
							vm.isShowEmpty = isShow;
						}
					},
					// 回到顶部
					toTop: {
						onShow(isShow) {
							// 显示隐藏的回调
							vm.isShowToTop = isShow;
						}
					},
					// 派发上拉加载的回调
					callback: function(mescroll) {
						vm.$emit('refresh', mescroll);
					}
				}
			};

			MeScroll.extend(diyOption, GlobalOption); // 混入全局的配置
			let myOption = JSON.parse(
				JSON.stringify({
					down: vm.down,
					up: vm.up
				})
			); // 深拷贝,避免对props的影响
			MeScroll.extend(myOption, diyOption); // 混入具体界面的配置

			// 初始化MeScroll对象
			vm.mescroll = new MeScroll(myOption, true); // 传入true,标记body为滚动区域
			// init回调mescroll对象
			vm.$emit('init', vm.mescroll);

			// 设置高度
			const sys = uni.getSystemInfoSync();
			if (sys.windowHeight) vm.windowHeight = sys.windowHeight;
			if (sys.statusBarHeight) vm.statusBarH = sys.statusBarHeight;
			// 使down的bottomOffset生效
			vm.mescroll.setBodyHeight(sys.windowHeight);
			// mescroll-body在Android小程序下拉会卡顿,无法像mescroll-uni那样通过设置"disableScroll":true解决,只能用动画过渡缓解
			// #ifdef MP
			if (sys.platform == "android") vm.downTransition = 'transform 200ms'
			// #endif

			// 因为使用的是page的scroll,这里需自定义scrollTo
			vm.mescroll.resetScrollTo((y, t) => {
				uni.pageScrollTo({
					scrollTop: y,
					duration: t
				})
			});

			// 具体的界面如果不配置up.toTop.safearea,则取本vue的safearea值
			if (sys.platform == "ios") {
				vm.isSafearea = vm.safearea;
				if (vm.up && vm.up.toTop && vm.up.toTop.safearea != null) {} else {
					vm.mescroll.optUp.toTop.safearea = vm.safearea;
				}
			} else {
				vm.isSafearea = false
				vm.mescroll.optUp.toTop.safearea = false
			}
		}
	};
</script>

<style lang="scss">
	@import "@/components/mescroll-uni/mescroll-body.css";
	@import "@/components/mescroll-uni/components/mescroll-down.css";
	@import "@/components/mescroll-uni/components/mescroll-up.css";
	@import "@/components/RefreshView/mescroll-down.css";

	.titleStyle {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
	}
</style>
