<template>
	<u-popup :maskCloseAble="maskCloseAble" mode="bottom" :popup="false" v-model="value" length="auto" :safeAreaInsetBottom="safeAreaInsetBottom" @close="close" :z-index="uZIndex">
		<view class="u-datetime-picker">
			<view class="u-picker-header" @touchmove.stop.prevent="">
				<view class="u-btn-picker u-btn-picker--tips" 
					:style="{ color: cancelColor }" 
					hover-class="u-opacity" 
					:hover-stay-time="150" 
					@tap="getResult('cancel')"
				>{{cancelText}}</view>
				<view class="u-picker__title">{{ title }}</view>
				<view
					class="u-btn-picker u-btn-picker--primary"
					:style="{ color: moving ? cancelColor : confirmColor }"
					hover-class="u-opacity"
					:hover-stay-time="150"
					@touchmove.stop=""
					@tap.stop="getResult('confirm')"
				>
					{{confirmText}}
				</view>
			</view>
			
			<view class="u-picker-header" >
				<view class="u-btn-picker u-btn-picker--tips" 
					:style="{ color: cancelColor }" 
					
				
				>{{texts[0]}}</view>
				<view class="u-picker__title">{{ title }}</view>
				<view
					class="u-btn-picker u-btn-picker--tips" 
					:style="{ color: cancelColor }" 
				
				
				>
					{{texts[1]}}
				</view>
			</view>
			<view class="u-picker-body">
				 
				<picker-view  :value="valueArr" @change="change" class="u-picker-view" @pickstart="pickstart" @pickend="pickend">
					
					<picker-view-column >
						<view class="u-column-item" v-for="(item, index) in showhours1" :key="index">
							{{ formatNumber(item) }}
							<text class="u-text" v-if="showTimeTag">时</text>
						</view>
					</picker-view-column>
					<picker-view-column >
						<view class="u-column-item" v-for="(item, index) in showminutes1" :key="index">
							{{ formatNumber(item) }}
							<text class="u-text" v-if="showTimeTag">分</text>
						</view>
					</picker-view-column>
					
					
					<picker-view-column >
						<view class="u-column-item" v-for="(item, index) in showhours2" 
						
						
						:key="index">
							{{ formatNumber(item) }}
							<text class="u-text" v-if="showTimeTag">时</text>
						</view>
					</picker-view-column>
					<picker-view-column >
						<view class="u-column-item" v-for="(item, index) in showminutes2"
						
						 :key="index">
							{{ formatNumber(item) }}
							<text class="u-text" v-if="showTimeTag">分</text>
						</view>
					</picker-view-column> 
				</picker-view>
				 
				 
			</view>
		</view>
	</u-popup>
</template>

<script>


/**
 * picker picker弹出选择器
 * @description 此选择器有两种弹出模式：一是时间模式，可以配置年，日，月，时，分，秒参数 二是地区模式，可以配置省，市，区参数
 * @tutorial https://www.uviewui.com/components/picker.html
 * @property {Object} params 需要显示的参数，见官网说明
 * @property {String} mode 模式选择，region-地区类型，time-时间类型（默认time）
 * @property {String Number} start-year 可选的开始年份，mode=time时有效（默认1950）
 * @property {String Number} end-year 可选的结束年份，mode=time时有效（默认2050）
 * @property {Boolean} safe-area-inset-bottom 是否开启底部安全区适配（默认false）
 * @property {Boolean} show-time-tag 时间模式时，是否显示后面的年月日中文提示
 * @property {String} cancel-color 取消按钮的颜色（默认#606266）
 * @property {String} confirm-color 确认按钮的颜色（默认#2979ff）
 * @property {String} default-time 默认选中的时间，mode=time时有效
 * @property {String} confirm-text 确认按钮的文字
 * @property {String} cancel-text 取消按钮的文字
 * @property {String} default-region 默认选中的地区，中文形式，mode=region时有效
 * @property {String} default-code 默认选中的地区，编号形式，mode=region时有效
 * @property {Boolean} mask-close-able 是否允许通过点击遮罩关闭Picker（默认true）
 * @property {String Number} z-index 弹出时的z-index值（默认1075）
 * @property {Array} default-selector 数组形式，其中每一项表示选择了range对应项中的第几个
 * @property {Array} range 自定义选择的数据，mode=selector或mode=multiSelector时有效
 * @property {String} range-key 当range参数的元素为对象时，指定Object中的哪个key的值作为选择器显示内容
 * @event {Function} confirm 点击确定按钮，返回当前选择的值
 * @event {Function} cancel 点击取消按钮，返回当前选择的值
 * @example <u-picker v-model="show" mode="time"></u-picker>
 */
export default {
	name: 'u-picker',
	props: {
		// picker中需要显示的参数
		params: {
			type: Object,
			default() {
				return {
					
					hour: true,
					minute: true,
					hour2: true,
					minute2: true,
					
				};
			}
		},
		// 当mode=selector或者mode=multiSelector时，提供的数组
		range: {
			type: Array,
			default() {
				return [];
			}
		},
		texts: {
			type: Array,
			default() {
				return ['开始时间','结束时间'];
			}
		},
	 
		// 当 range 是一个 Array＜Object＞ 时，通过 range-key 来指定 Object 中 key 的值作为选择器显示内容
		rangeKey: {
			type: String,
			default: ''
		},
		// 模式选择，region-地区类型，time-时间类型，selector-单列模式，multiSelector-多列模式
		mode: {
			type: String,
			default: 'time'
		},
	
		// "取消"按钮的颜色
		cancelColor: {
			type: String,
			default: '#606266'
		},
		// "确定"按钮的颜色
		confirmColor: {
			type: String,
			default: '#2979ff'
		},
		// 默认显示的时间，2025-07-02 || 2025-07-02 13:01:00 || 2025/07/02
		defaultTime: {
			type: String,
			default: ''
		},
		defaultTime2: {
			type: String,
			default: ''
		},
		
		// 时间模式时，是否显示后面的年月日中文提示
		showTimeTag: {
			type: Boolean,
			default: true
		},
		
		safeAreaInsetBottom: {
			type: Boolean,
			default: false
		},
		// 是否允许通过点击遮罩关闭Picker
		maskCloseAble: {
			type: Boolean,
			default: true
		},
		// 通过双向绑定控制组件的弹出与收起
		value: {
			type: Boolean,
			default: false
		},
		// 弹出的z-index值
		zIndex: {
			type: [String, Number],
			default: 0
		},
		// 顶部标题
		title: {
			type: String,
			default: ''
		},
		// 取消按钮的文字
		cancelText: {
			type: String,
			default: '取消'
		},
		// 确认按钮的文字
		confirmText: {
			type: String,
			default: '确认'
		}
	},
	data() {
		return {
		
			hours: [],
			minutes: [],
		
			hour: 0,
			minute: 0,
			hour2: 0,
			minute2: 0,
			
			reset: false,
			startDate: '',
			endDate: '',
			valueArr: [0,0,0,0],
		 	oldvalueArr: [0,0,0,0],
		  
			moving: false // 列是否还在滑动中，微信小程序如果在滑动中就点确定，结果可能不准确
		};
	},
	mounted() {
		this.init();
	},
	computed: {
		showhours1(){
			var sz= this.hours
			return sz
		},
		 showhours2(){
			 var sz= this.hours
		 // 	var sz= []
			// var i=this.valueArr[0];
			// sz=this.hours.filter((item)=>{
			// 	var bl=false
			// 	if(item>=this.showhours1[i]){
			// 		bl=true
			// 	}
				
			// 	return bl
			// })
			
			
			return sz
		 },
		 showminutes1(){
			 var sz=this.minutes;
			 
		 	return sz
		 },
		 showminutes2(){
			 var sz=this.minutes;
			 
			 // var i1=this.valueArr[0];
			 // var i2=this.valueArr[2];
			 
			 // if(this.showhours1[i1]==this.showhours2[i2]){
				//  sz=this.minutes.filter((item)=>{
				//  	var bl=false
				//  	if(item>=this.minute){
				//  		bl=true
				//  	}
				 	
				//  	return bl
				//  })
			 // }
			 
			 
			 return sz
		 },
		 
		propsChange() {
			// 引用这几个变量，是为了监听其变化
			return `${this.mode}-${this.defaultTime}-${this.startYear}-${this.endYear}-${this.defaultRegion}-${this.areaCode}`;
		},
	 
		uZIndex() {
			// 如果用户有传递z-index值，优先使用
			return this.zIndex ? this.zIndex : this.$u.zIndex.popup;
		}
	},
	watch: {
		propsChange() {
			this.reset = true;
			setTimeout(() => this.init(), 10);
		},
	 
		// 微信和QQ小程序由于一些奇怪的原因(故同时对所有平台均初始化一遍)，需要重新初始化才能显示正确的值
		value(n) {
			if (n) {
				this.reset = true;
				setTimeout(() => this.init(), 10);
			}
		}
	},
	methods: {
		// 标识滑动开始，只有微信小程序才有这样的事件
		pickstart() {
			// #ifdef MP-WEIXIN
			this.moving = true;
			// #endif
		},
		// 标识滑动结束
		pickend() {
			// #ifdef MP-WEIXIN
			this.moving = false;
			// #endif
		},
	 
		// 小于10前面补0，用于月份，日期，时分秒等
		formatNumber(num) {
			return +num < 10 ? '0' + num : String(num);
		},
		// 生成递进的数组
		generateArray: function(start, end) {
			// 转为数值格式，否则用户给end-year等传递字符串值时，下面的end+1会导致字符串拼接，而不是相加
			start = Number(start);
			end = Number(end);
			end = end > start ? end : start;
			// 生成数组，获取其中的索引，并剪出来
			return [...Array(end + 1).keys()].slice(start);
		},
		getIndex: function(arr, val) {
			let index = arr.indexOf(val);
			// 如果index为-1(即找不到index值)，~(-1)=-(-1)-1=0，导致条件不成立
			return ~index ? index : 0;
		},
		//日期时间处理
		initTimeValue() {
			// 格式化时间，在IE浏览器(uni不存在此情况)，无法识别日期间的"-"间隔符号
			let fdate = this.defaultTime.replace(/\-/g, '/');
			let fdate2 = this.defaultTime2.replace(/\-/g, '/');
			 
			fdate2 = fdate2 && fdate2.indexOf('/') == -1 ? `2020/01/01 ${fdate2}` : fdate2;
			fdate = fdate && fdate.indexOf('/') == -1 ? `2020/01/01 ${fdate}` : fdate;
			let time = null;
			if (fdate) time = new Date(fdate);
			else time = new Date();
			
			let time2 = null;
			if (fdate2) time2 = new Date(fdate2);
			else time2 = new Date();
			
			
		
			this.hour = time.getHours();
			this.minute = time.getMinutes();
			
			this.hour2 = time2.getHours();
			this.minute2 = time2.getMinutes();
		},
		init() {
			 
			//this.valueArr = [0,0,0,0];
			this.reset = false;
			this.initTimeValue()
				
				if (this.params.hour) {
					//this.valueArr.push(0);
					this.setHours();
				}
				if (this.params.minute) {
				//	this.valueArr.push(0);
					this.setMinutes();
				}
				
				if (this.params.hour2) {
					//this.valueArr.push(0);
					this.setHours2();
				}
				if (this.params.minute2) {
					
					//this.valueArr.push(0);
					this.setMinutes2();
				}
				
			 
			this.oldvalueArr=[
				...this.valueArr
			];
			
			this.$forceUpdate();
			
		},
	
		setHours() {
			this.hours = this.generateArray(0, 23);
			this.valueArr.splice(0, 1, this.getIndex(this.showhours1, this.hour));
		
		},
		setMinutes() {
			this.minutes = this.generateArray(0, 59);
			this.valueArr.splice(1, 1, this.getIndex(this.showminutes1, this.minute));
	
		},
		setHours2() {
			
			this.hours2 = this.generateArray(0, 23);
			
			this.valueArr.splice(2, 1, this.getIndex(this.showhours2, this.hour2));
		 
		},
		setMinutes2() {
			this.minutes2 = this.generateArray(0, 59);
			this.valueArr.splice(3, 1, this.getIndex(this.showminutes2, this.minute2));
		 
		},
		
		
	 
		close() {
			this.$emit('input', false);
		},
		// 用户更改picker的列选项
		change(e) {
			 
			this.valueArr = e.detail.value;
		
			 
			this.hour = this.showhours1[this.valueArr[0]]
			this.minute = this.showminutes1[this.valueArr[1]]
			for(var i in this.oldvalueArr ){
				
			}
			
			if(this.oldvalueArr[0]!=this.valueArr[0]){
				this.setHours2()
				this.setMinutes2()
			}
			if(this.oldvalueArr[1]!=this.valueArr[1]){
				if(this.hour==this.hour2){
					this.setMinutes2()
				}
			}
			if(this.oldvalueArr[2]!=this.valueArr[2]){
				
			}
			if(this.oldvalueArr[1]!=this.valueArr[1]){
				
			}
			
			this.hour = this.showhours1[this.valueArr[0]]
			this.minute = this.showminutes1[this.valueArr[1]]
			this.hour2 = this.showhours2[this.valueArr[2]]
			this.minute2 = this.showminutes2[this.valueArr[3]]
			
			
			this.oldvalueArr=[
				...this.valueArr
			]; 
		},
		// 用户点击确定按钮
		getResult(event = null) {
			// #ifdef MP-WEIXIN
			if (this.moving) return;
			// #endif
			let result = {};
			var i0=this.valueArr[0];
			var i1=this.valueArr[1];
			var i2=this.valueArr[2];
			var i3=this.valueArr[3];
			this.hour =this.showhours1[i0]
			this.minute =this.showminutes1[i1]
			this.hour2 =this.showhours2[i2]
			this.minute2 =this.showminutes2[i3]
			
			 result.hour = this.formatNumber(this.hour || 0);
			 result.minute = this.formatNumber(this.minute || 0);
			 result.hour2 = this.formatNumber(this.hour2 || 0);
			 result.minute2 = this.formatNumber(this.minute2|| 0);
				
				
			
			if (event) this.$emit(event, result);
			this.close();
		},
		
	}
};
</script>

<style lang="scss" scoped>
// @import '../../libs/css/style.components.scss';

.u-datetime-picker {
	position: relative;
	z-index: 999;
}

.u-picker-view {
	height: 100%;
	box-sizing: border-box;
}

.u-picker-header {
	width: 100%;
	height: 90rpx;
	padding: 0 40rpx;
	//@include vue-flex;
	    display: flex;
	justify-content: space-between;
	align-items: center;
	box-sizing: border-box;
	font-size: 30rpx;
	background: #fff;
	position: relative;
}

.u-picker-header::after {
	content: '';
	position: absolute;
	border-bottom: 1rpx solid #eaeef1;
	-webkit-transform: scaleY(0.5);
	transform: scaleY(0.5);
	bottom: 0;
	right: 0;
	left: 0;
}

.u-picker__title {
	color: $u-content-color;
}

.u-picker-body {
	width: 100%;
	height: 500rpx;
	overflow: hidden;
	background-color: #fff;
}

.u-column-item {
	//@include vue-flex;
	    display: flex;
	align-items: center;
	justify-content: center;
	font-size: 18px;
	color: $u-main-color;
	padding: 0 8rpx;
}

.u-text {
	font-size: 24rpx;
	padding-left: 8rpx;
}

.u-btn-picker {
	padding: 16rpx;
	box-sizing: border-box;
	text-align: center;
	text-decoration: none;
}

.u-opacity {
	opacity: 0.5;
}

.u-btn-picker--primary {
	color: $u-type-primary;
}

.u-btn-picker--tips {
	color: $u-tips-color;
}
.u-column-item-dis{
	color: #8c8c8c;
}
</style>
