<template>
	<u-popup :class="['u-theme-' + cTheme]" :maskCloseAble="maskCloseAble" mode="bottom" :popup="false" v-model="popupValue" length="auto" :safeAreaInsetBottom="safeAreaInsetBottom" @close="close" :z-index="uZIndex">
		<view class="u-datetime-picker">
			<u-tabs v-if="mode == 'time' && showTabs" :list="list" :is-scroll="false" :current="current" @change="timechange"></u-tabs>
			<u-gap height="2"></u-gap>
			<u-tabs v-if="mode == 'time' && timeRange" :list="timelist" :is-scroll="false" :current="timeCurrent" @change="timeRangechange"></u-tabs>
			<view class="u-picker-body">
				<picker-view v-if="mode == 'region'" :value="valueArr" @change="change" class="u-picker-view" @pickstart="pickstart" @pickend="pickend">
					<picker-view-column v-if="!reset && newParams.province">
						<view class="u-column-item" v-for="(item, index) in provinces" :key="index">
							<view class="u-line-1">{{ item.label }}</view>
						</view>
					</picker-view-column>
					<picker-view-column v-if="!reset && newParams.city">
						<view class="u-column-item" v-for="(item, index) in citys" :key="index">
							<view class="u-line-1">{{ item.label }}</view>
						</view>
					</picker-view-column>
					<picker-view-column v-if="!reset && newParams.area">
						<view class="u-column-item" v-for="(item, index) in areas" :key="index">
							<view class="u-line-1">{{ item.label }}</view>
						</view>
					</picker-view-column>
				</picker-view>
				<picker-view v-else-if="mode == 'time'" :value="valueArr" @change="change" class="u-picker-view" @pickstart="pickstart" @pickend="pickend">
					<picker-view-column v-if="!reset && newParams.year">
						<view class="u-column-item" v-for="(item, index) in years" :key="index">
							{{ item }}
							<text class="u-text" v-if="showTimeTag">年</text>
						</view>
					</picker-view-column>
					<picker-view-column v-if="!reset && newParams.quarter">
						<view class="u-column-item" v-for="(item, index) in quarters" :key="index">
							<text class="u-text" v-if="showTimeTag">第</text>
							{{ item }}
							<text class="u-text" v-if="showTimeTag">季度</text>
						</view>
					</picker-view-column>
					<picker-view-column v-if="!reset && newParams.month">
						<view class="u-column-item" v-for="(item, index) in months" :key="index">
							{{ formatNumber(item) }}
							<text class="u-text" v-if="showTimeTag">月</text>
						</view>
					</picker-view-column>
					<picker-view-column v-if="!reset && newParams.day">
						<view class="u-column-item" v-for="(item, index) in days" :key="index">
							{{ formatNumber(item) }}
							<text class="u-text" v-if="showTimeTag">日</text>
						</view>
					</picker-view-column>
					<picker-view-column v-if="!reset && newParams.hour">
						<view class="u-column-item" v-for="(item, index) in hours" :key="index">
							{{ formatNumber(item) }}
							<text class="u-text" v-if="showTimeTag">时</text>
						</view>
					</picker-view-column>
					<picker-view-column v-if="!reset && newParams.minute">
						<view class="u-column-item" v-for="(item, index) in minutes" :key="index">
							{{ formatNumber(item) }}
							<text class="u-text" v-if="showTimeTag">分</text>
						</view>
					</picker-view-column>
					<picker-view-column v-if="!reset && newParams.second">
						<view class="u-column-item" v-for="(item, index) in seconds" :key="index">
							{{ formatNumber(item) }}
							<text class="u-text" v-if="showTimeTag">秒</text>
						</view>
					</picker-view-column>
				</picker-view>
				<picker-view v-else-if="mode == 'selector'" :value="valueArr" @change="change" class="u-picker-view" @pickstart="pickstart" @pickend="pickend">
					<picker-view-column v-if="!reset">
						<view class="u-column-item" v-for="(item, index) in range" :key="index">
							<view class="u-line-1">{{ getItemValue(item, 'selector') }}</view>
						</view>
					</picker-view-column>
				</picker-view>
				<picker-view v-else-if="mode == 'multiSelector'" :value="valueArr" @change="change" class="u-picker-view" @pickstart="pickstart" @pickend="pickend">
					<picker-view-column v-if="!reset" v-for="(item, index) in range" :key="index">
						<view class="u-column-item" v-for="(item1, index1) in item" :key="index1">
							<view class="u-line-1">{{ getItemValue(item1, 'multiSelector') }}</view>
						</view>
					</picker-view-column>
				</picker-view>
			</view>
			<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-header-btn" v-if="mode == 'time' && timeRange">
					<u-button throttle-time="0" shape="circle" @tap="getResult('reset')">重置</u-button>
					<u-button throttle-time="0" shape="circle" type="primary" @touchmove.stop="" @tap.stop="getResult('confirm')">确定</u-button>
				</view>
				<view class="u-picker-header-btn" v-else>
					<u-button throttle-time="0" shape="circle" @tap="getResult('cancel')">{{cancelText}}</u-button>
					<u-button throttle-time="0" shape="circle" type="primary" @touchmove.stop="" @tap.stop="getResult('confirm')">{{confirmText}}</u-button>
				</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>
	</u-popup>
</template>

<script>
import provinces from '../../libs/util/province.js';
import citys from '../../libs/util/city.js';
import areas from '../../libs/util/area.js';

/**
 * 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 确认按钮的颜色（默认#0084FF）
 * @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的值作为选择器显示内容
 * @property {Boolean} show-tabs 是否显示tabs
 * @property {Boolean} time-range 是否显示时间范围
 * @event {Function} confirm 点击确定按钮，返回当前选择的值
 * @event {Function} cancel 点击取消按钮，返回当前选择的值
 * @example <u-picker v-model="show" mode="time"></u-picker>
 */
export default {
	name: 'u-picker',
	emits: ["update:modelValue", "input", "confirm", "cancel"],
	props: {
		// 通过双向绑定控制组件的弹出与收起
		value: {
			type: Boolean,
			default: false
		},
		modelValue: {
			type: Boolean,
			default: false
		},
		// picker中需要显示的参数
		params: {
			type: Object,
			default() {
				return {
					year: true,
					quarter: false,
					month: true,
					day: true,
					hour: true,
					minute: false,
					second: false,
					province: true,
					city: true,
					area: true,
					timestamp: true,
				};
			}
		},
		// 当mode=selector或者mode=multiSelector时，提供的数组
		range: {
			type: Array,
			default() {
				return [];
			}
		},
		// 当mode=selector或者mode=multiSelector时，提供的默认选中的下标
		defaultSelector: {
			type: Array,
			default() {
				return [0];
			}
		},
		// 当 range 是一个 Array＜Object＞ 时，通过 range-key 来指定 Object 中 key 的值作为选择器显示内容
		rangeKey: {
			type: String,
			default: ''
		},
		// 模式选择，region-地区类型，time-时间类型，selector-单列模式，multiSelector-多列模式
		mode: {
			type: String,
			default: 'time'
		},
		// 年份开始时间
		startYear: {
			type: [String, Number],
			default: 1950
		},
		// 年份结束时间
		endYear: {
			type: [String, Number],
			default: 2050
		},
		// "取消"按钮的颜色
		cancelColor: {
			type: String,
			default: '#606266'
		},
		// "确定"按钮的颜色
		confirmColor: {
			type: String,
			default: '#0084FF'
		},
		// 默认显示的时间，2025-07-02 || 2025-07-02 13:01:00 || 2025/07/02
		defaultTime: {
			type: String,
			default: ''
		},
		// 默认显示的地区，可传类似["河北省", "秦皇岛市", "北戴河区"]
		defaultRegion: {
			type: Array,
			default() {
				return [];
			}
		},
		// 时间模式时，是否显示后面的年月日中文提示
		showTimeTag: {
			type: Boolean,
			default: true
		},
		// 默认显示地区的编码，defaultRegion和areaCode同时存在，areaCode优先，可传类似["13", "1303", "130304"]
		areaCode: {
			type: Array,
			default() {
				return [];
			}
		},
		safeAreaInsetBottom: {
			type: Boolean,
			default: false
		},
		// 是否允许通过点击遮罩关闭Picker
		maskCloseAble: {
			type: Boolean,
			default: true
		},
		// 弹出的z-index值
		zIndex: {
			type: [String, Number],
			default: 0
		},
		// 顶部标题
		title: {
			type: String,
			default: ''
		},
		// 取消按钮的文字
		cancelText: {
			type: String,
			default: '取消'
		},
		// 确认按钮的文字
		confirmText: {
			type: String,
			default: '确认'
		},
		// 关怀模式: normal, care(fpi新增)
		theme: {
			type: String,
			default: ''
		},
		showTabs: {
			type: Boolean,
			default: false
		},
		timeRange: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			popupValue: false,
			current: 0,
			list: [{
					name: '小时'
				}, {
					name: '日'
				}, {
					name: '月'
				}, {
					name: '季'
				}, {
					name: '年'
				}
			],
			timeCurrent: 0,
			timelist: [
				{
					name: ''
				}, {
					name: ''
				}
			],
			years: [],//年份数据
			quarters: [],//季度数据
			months: [], //月份数据 
			days: [], //日数据
			hours: [], //小时数据
			minutes: [], // 分钟数据
			seconds: [], //秒数据
			year: 0, //年份
			quarter: 0, //季度
			month: 0, //月份
			day: 0, //日
			hour: 0, //小时
			minute: 0, //分钟
			second: 0, //秒

			sYear: 0,
			sQuarter: 0,
			sMonth: 0,
			sDay: 0,
			sHour: 0,
			sMinute: 0,
			sSecond: 0,
			eYear: 0,
			eQuarter: 0,
			eMonth: 0,
			eDay: 0,
			eHour: 0,
			eMinute: 0,
			eSecond: 0,
			reset: false,
			startDate: '',
			endDate: '',
			valueArr: [],
			provinces: provinces,
			citys: citys[0],
			areas: areas[0][0],
			province: 0,
			city: 0,
			area: 0,
			moving: false, // 列是否还在滑动中，微信小程序如果在滑动中就点确定，结果可能不准确
			newParams:{
				year: true,
				quarter: false,
				month: true,
				day: true,
				hour: true,
				minute: false,
				second: false,
				province: true,
				city: true,
				area: true,
				timestamp: true,
			}
		};
	},
	mounted() {
		this.init();
	},
	computed: {
		valueCom() {
			// #ifndef VUE3
			return this.value;
			// #endif

			// #ifdef VUE3
			return this.modelValue;
			// #endif
		},
		propsChange() {
			// 引用这几个变量，是为了监听其变化
			return `${this.mode}-${this.defaultTime}-${this.startYear}-${this.endYear}-${this.defaultRegion}-${this.areaCode}`;
		},
		regionChange() {
			// 引用这几个变量，是为了监听其变化
			return `${this.province}-${this.city}`;
		},
		yearAndMonth() {
			return `${this.year}-${this.month}`;
		},
		uZIndex() {
			// 如果用户有传递z-index值，优先使用
			return this.zIndex ? this.zIndex : this.$u.zIndex.popup;
		},
		cTheme() {
			return this.theme || (uni.$u || {}).theme;
		},
	},
	watch: {
		propsChange() {
			this.reset = true;
			setTimeout(() => this.init(), 10);
		},
		// 如果地区发生变化，为了让picker联动起来，必须重置this.citys和this.areas
		regionChange(val) {
			this.citys = citys[this.province];
			this.areas = areas[this.province][this.city];
		},
		// watch监听月份的变化，实时变更日的天数，因为不同月份，天数不一样
		// 一个月可能有30，31天，甚至闰年2月的29天，平年2月28天
		yearAndMonth(val) {
			if (this.newParams.year) this.setDays();
		},
		// 微信和QQ小程序由于一些奇怪的原因(故同时对所有平台均初始化一遍)，需要重新初始化才能显示正确的值
		valueCom(n) {
			if (n) {
				this.reset = true;
				setTimeout(() => this.init(), 10);
			}
			this.popupValue = n;
		},
		current: {
			handler(newValue, oldValue) {
				// console.log(newValue)
				switch (newValue) {
				case 0:
					this.newParams.year= true
					this.newParams.quarter= false
					this.newParams.month= true
					this.newParams.day= true
					this.newParams.hour= true
					this.init()
					break;
				case 1:
					this.newParams.year= true
					this.newParams.quarter= false
					this.newParams.month= true
					this.newParams.day= true
					this.newParams.hour= false
					this.init()
					break;
				case 2:
					this.newParams.year= true
					this.newParams.quarter= false
					this.newParams.month= true
					this.newParams.day= false
					this.newParams.hour= false
					this.init()
					break;
				case 3:
					this.newParams.year= true
					this.newParams.quarter= true
					this.newParams.month= false
					this.newParams.day= false
					this.newParams.hour= false
					this.init()
					break;
				case 4:
					this.newParams.year= true
					this.newParams.quarter= false
					this.newParams.month= false
					this.newParams.day= false
					this.newParams.hour= false
					this.init()
					break;
				default:
					break;
			}
			let input = ''
			if (this.timeRange) {
				// 范围选择
				if (this.timeCurrent == 0) {
					if (this.newParams.year) { input += this.sYear+'年';}
					if (this.newParams.quarter) { input +=  '第' + this.sQuarter+'季度';}
					if (this.newParams.month) {  input += this.sMonth+'月';}
					if (this.newParams.day)  { input += this.sDay+'日';}
					if (this.newParams.hour) { input += this.sHour+'时';}
					if (this.newParams.minute) { input += this.sMinute+'分';}
					if (this.newParams.second) { input += this.sSecond+'秒';}
				}else {
					if (this.newParams.year) { input += this.eYear+'年';}
					if (this.newParams.quarter) { input +=  '第' + this.eQuarter+'季度';}
					if (this.newParams.month) {  input += this.eMonth+'月';}
					if (this.newParams.day)  { input += this.eDay+'日';}
					if (this.newParams.hour) { input += this.eHour+'时';}
					if (this.newParams.minute) { input += this.eMinute+'分';}
					if (this.newParams.second) { input += this.eSecond+'秒';}
				}
			}else {
				// 单选
				if (this.newParams.year) { input += this.year+'年';}
				if (this.newParams.quarter) { input +=  '第' + this.quarter+'季度';}
				if (this.newParams.month) {  input += this.month+'月';}
				if (this.newParams.day)  { input += this.day+'日';}
				if (this.newParams.hour) { input += this.hour+'时';}
				if (this.newParams.minute) { input += this.minute+'分';}
				if (this.newParams.second) { input += this.second+'秒';}
			}
			// 赋值开始、结束时间
			this.timelist[this.timeCurrent].name = input
			// 切换tabs 重置开始时间、结束时间的current，并且把结束时间置空
			this.timeCurrent = 0
			this.timelist[1].name = ''
			},
			deep: true
		},
		timeCurrent: {
			handler(newValue, oldValue) {
				// console.log(newValue)
				let input = ''
				if (this.timeCurrent == 0) {
					if (this.newParams.year) { input += this.sYear+'年';}
					if (this.newParams.quarter) { input +=  '第' + this.sQuarter+'季度';}
					if (this.newParams.month) {  input += this.sMonth+'月';}
					if (this.newParams.day)  { input += this.sDay+'日';}
					if (this.newParams.hour) { input += this.sHour+'时';}
					if (this.newParams.minute) { input += this.sMinute+'分';}
					if (this.newParams.second) { input += this.sSecond+'秒';}
				}else {
					// 当从开始时间切换到结束时间时,结束时间应该等于开始时间
					if (oldValue == 0) {
						this.eYear =this.sYear
						this.eQuarter =this.sQuarter
						this.eMonth =this.sMonth
						this.eDay =this.sDay
						this.eHour =this.sHour
						this.eMinute =this.sMinute
						this.eSecond =this.sSecond
					}
					if (this.newParams.year) { input += this.eYear+'年';}
					if (this.newParams.quarter) { input +=  '第' + this.eQuarter+'季度';}
					if (this.newParams.month) {  input += this.eMonth+'月';}
					if (this.newParams.day)  { input += this.eDay+'日';}
					if (this.newParams.hour) { input += this.eHour+'时';}
					if (this.newParams.minute) { input += this.eMinute+'分';}
					if (this.newParams.second) { input += this.eSecond+'秒';}
				}
				this.timelist[this.timeCurrent].name = input
			},
			deep: true
		}
	},
	methods: {
		// 标识滑动开始，只有微信小程序才有这样的事件
		pickstart() {
			// #ifdef MP-WEIXIN
			this.moving = true;
			// #endif
		},
		// 标识滑动结束
		pickend() {
			// #ifdef MP-WEIXIN
			this.moving = false;
			// #endif
		},
		// 对单列和多列形式的判断是否有传入变量的情况
		getItemValue(item, mode) {
			// 目前(2020-05-25)uni-app对微信小程序编译有错误，导致v-if为false中的内容也执行，错误导致
			// 单列模式或者多列模式中的getItemValue同时被执行，故在这里再加一层判断
			if (this.mode == mode) {
				return typeof item == 'object' ? item[this.rangeKey] : item;
			}
		},
		// 小于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, '/');
			fdate = fdate && fdate.indexOf('/') == -1 ? `2020/01/01 ${fdate}` : fdate;
			let time = null;
			if (fdate) time = new Date(fdate);
			else time = new Date();
			if (this.timeRange) {
				if (this.timeCurrent == 0) {
					// 获取年日月时分秒
					if (this.newParams.year) this.sYear = time.getFullYear();
					if (this.newParams.month) this.sMonth = Number(time.getMonth()) + 1;
					// 获取当前季度：
					let currMonth= new Date().getMonth()+1;
					if (this.newParams.quarter) this.sQuarter= Math.floor( ( currMonth % 3 == 0 ? ( currMonth / 3 ) : ( currMonth / 3 + 1 ) ) );
					if (this.newParams.day) this.sDay = time.getDate();
					if (this.newParams.hour) this.sHour = time.getHours();
					if (this.newParams.minute) this.sMinute = time.getMinutes();
					if (this.newParams.second) this.sSecond = time.getSeconds();
				}else {
					// 获取年日月时分秒
					if (this.newParams.year) this.eYear = time.getFullYear();
					if (this.newParams.month) this.eMonth = Number(time.getMonth()) + 1;
					// 获取当前季度：
					let currMonth= new Date().getMonth()+1;
					if (this.newParams.quarter) this.eQuarter= Math.floor( ( currMonth % 3 == 0 ? ( currMonth / 3 ) : ( currMonth / 3 + 1 ) ) );
					if (this.newParams.day) this.eDay = time.getDate();
					if (this.newParams.hour) this.eHour = time.getHours();
					if (this.newParams.minute) this.eMinute = time.getMinutes();
					if (this.newParams.second) this.eSecond = time.getSeconds();
				}
			}else {
				// 获取年日月时分秒
				if (this.newParams.year) this.year = time.getFullYear();
				if (this.newParams.month) this.month = Number(time.getMonth()) + 1;
				// 获取当前季度：
				let currMonth= new Date().getMonth()+1;
				if (this.newParams.quarter) this.quarter= Math.floor( ( currMonth % 3 == 0 ? ( currMonth / 3 ) : ( currMonth / 3 + 1 ) ) );
				if (this.newParams.day) this.day = time.getDate();
				if (this.newParams.hour) this.hour = time.getHours();
				if (this.newParams.minute) this.minute = time.getMinutes();
				if (this.newParams.second) this.second = time.getSeconds();
			}

			this.getSelectDate()
		},
		getSelectDate(){
			let input = ''
			if (this.timeRange) {
				if (this.timeCurrent == 0) {
					if (this.newParams.year) { input += this.sYear+'年';}
					if (this.newParams.quarter) { input +=  '第' + this.sQuarter+'季度';}
					if (this.newParams.month) {  input += this.sMonth+'月';}
					if (this.newParams.day)  { input += this.sDay+'日';}
					if (this.newParams.hour) { input += this.sHour+'时';}
					if (this.newParams.minute) { input += this.sMinute+'分';}
					if (this.newParams.second) { input += this.sSecond+'秒';}
				}else {
					if (this.newParams.year) { input += this.eYear+'年';}
					if (this.newParams.quarter) { input +=  '第' + this.eQuarter+'季度';}
					if (this.newParams.month) {  input += this.eMonth+'月';}
					if (this.newParams.day)  { input += this.eDay+'日';}
					if (this.newParams.hour) { input += this.eHour+'时';}
					if (this.newParams.minute) { input += this.eMinute+'分';}
					if (this.newParams.second) { input += this.eSecond+'秒';}
				}
			}else {
				if (this.newParams.year) { input += this.year+'年';}
				if (this.newParams.quarter) { input +=  '第' + this.quarter+'季度';}
				if (this.newParams.month) {  input += this.month+'月';}
				if (this.newParams.day)  { input += this.day+'日';}
				if (this.newParams.hour) { input += this.hour+'时';}
				if (this.newParams.minute) { input += this.minute+'分';}
				if (this.newParams.second) { input += this.second+'秒';}
			}
			this.timelist[this.timeCurrent].name = input
		},
		init() {
			this.newParams = this.params
			this.valueArr = [];
			this.reset = false;
			if (this.mode == 'time') {
				this.initTimeValue();
				if (this.newParams.year) {
					this.valueArr.push(0);
					this.setYears();
				}
				if (this.newParams.quarter) {
					this.valueArr.push(0);
					this.setQuarters();
				}
				if (this.newParams.month) {
					this.valueArr.push(0);
					this.setMonths();
				}
				if (this.newParams.day) {
					this.valueArr.push(0);
					this.setDays();
				}
				if (this.newParams.hour) {
					this.valueArr.push(0);
					this.setHours();
				}
				if (this.newParams.minute) {
					this.valueArr.push(0);
					this.setMinutes();
				}
				if (this.newParams.second) {
					this.valueArr.push(0);
					this.setSeconds();
				}
			} else if (this.mode == 'region') {
				if (this.newParams.province) {
					this.valueArr.push(0);
					this.setProvinces();
				}
				if (this.newParams.city) {
					this.valueArr.push(0);
					this.setCitys();
				}
				if (this.newParams.area) {
					this.valueArr.push(0);
					this.setAreas();
				}
			} else if (this.mode == 'selector') {
				this.valueArr = this.defaultSelector;
			} else if (this.mode == 'multiSelector') {
				this.valueArr = this.defaultSelector;
				this.multiSelectorValue = this.defaultSelector;
			}
			this.$forceUpdate();
		},
		// 设置picker的某一列值
		setYears() {
			// 获取年份集合
			this.years = this.generateArray(this.startYear, this.endYear);
			// 设置this.valueArr某一项的值，是为了让picker预选中某一个值
			if (this.timeRange) {
				this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.years, this.sYear));
			}else {
				this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.years, this.year));
			}
		},
		setQuarters(){
			this.quarters = this.generateArray(1, 4);
			if (this.timeRange) {
				this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.quarters, this.sQuarter));
			}else {
				this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.quarters, this.quarter));
			}
		},
		setMonths() {
			this.months = this.generateArray(1, 12);
			if (this.timeRange) {
				this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.months, this.sMonth));
			}else {
				this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.months, this.month));
			}
		},
		setDays() {
			let totalDays = new Date(this.year, this.month, 0).getDate();
			this.days = this.generateArray(1, totalDays);
			let index = 0;
			// 这里不能使用类似setMonths()中的this.valueArr.splice(this.valueArr.length - 1, xxx)做法
			// 因为this.month和this.year变化时，会触发watch中的this.setDays()，导致this.valueArr.length计算有误
			if (this.newParams.year && this.newParams.month) index = 2;
			else if (this.newParams.month) index = 1;
			else if (this.newParams.year) index = 1;
			else index = 0;
			// 当月份变化时，会导致日期的天数也会变化，如果原来选的天数大于变化后的天数，则重置为变化后的最大值
			// 比如原来选中3月31日，调整为2月后，日期变为最大29，这时如果day值继续为31显然不合理，于是将其置为29(picker-column从1开始)
			if (this.timeRange) {
				if(this.sDay > this.days.length) this.sDay = this.days.length;
				this.valueArr.splice(index, 1, this.getIndex(this.days, this.sDay));
			}else {
				if(this.day > this.days.length) this.day = this.days.length;
				this.valueArr.splice(index, 1, this.getIndex(this.days, this.day));
			}
		},
		setHours() {
			this.hours = this.generateArray(0, 23);
			if (this.timeRange) {
				this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.hours, this.sHour));
			}else {
				this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.hours, this.hour));
			}
		},
		setMinutes() {
			this.minutes = this.generateArray(0, 59);
			this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.minutes, this.minute));
		},
		setSeconds() {
			this.seconds = this.generateArray(0, 59);
			this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.seconds, this.second));
		},
		setProvinces() {
			// 判断是否需要province参数
			if (!this.newParams.province) return;
			let tmp = '';
			let useCode = false;
			// 如果同时配置了defaultRegion和areaCode，优先使用areaCode参数
			if (this.areaCode.length) {
				tmp = this.areaCode[0];
				useCode = true;
			} else if (this.defaultRegion.length) tmp = this.defaultRegion[0];
			else tmp = 0;
			// 历遍省份数组匹配
			provinces.map((v, k) => {
				if (useCode ? v.value == tmp : v.label == tmp) {
					tmp = k;
				}
			});
			this.province = tmp;
			this.provinces = provinces;
			// 设置默认省份的值
			this.valueArr.splice(0, 1, this.province);
		},
		setCitys() {
			if (!this.newParams.city) return;
			let tmp = '';
			let useCode = false;
			if (this.areaCode.length) {
				tmp = this.areaCode[1];
				useCode = true;
			} else if (this.defaultRegion.length) tmp = this.defaultRegion[1];
			else tmp = 0;
			citys[this.province].map((v, k) => {
				if (useCode ? v.value == tmp : v.label == tmp) {
					tmp = k;
				}
			});
			this.city = tmp;
			this.citys = citys[this.province];
			this.valueArr.splice(1, 1, this.city);
		},
		setAreas() {
			if (!this.newParams.area) return;
			let tmp = '';
			let useCode = false;
			if (this.areaCode.length) {
				tmp = this.areaCode[2];
				useCode = true;
			} else if (this.defaultRegion.length) tmp = this.defaultRegion[2];
			else tmp = 0;
			areas[this.province][this.city].map((v, k) => {
				if (useCode ? v.value == tmp : v.label == tmp) {
					tmp = k;
				}
			});
			this.area = tmp;
			this.areas = areas[this.province][this.city];
			this.valueArr.splice(2, 1, this.area);
		},
		close() {
			// 重置
			this.current= 0
			this.newParams={
				year: true,
				quarter: false,
				month: true,
				day: true,
				hour: true,
				minute: false,
				second: false,
				province: true,
				city: true,
				area: true,
				timestamp: true,
			}
			if (this.timeRange) {
				this.timeCurrent =0
				this.timelist= [{name: ''}, {name: ''}]
			}
			this.$emit('input', false);
			this.$emit("update:modelValue", false);
		},
		// 用户更改picker的列选项
		change(e) {
			this.valueArr = e.detail.value;
			let i = 0;
			if (this.timeRange && this.mode == 'time') {
				if (this.newParams.year) {
					if(this.timeCurrent == 0) {
						this.sYear = this.years[this.valueArr[i++]];
					}else {
						this.eYear = this.years[this.valueArr[i++]];
					}
				}
				if (this.newParams.quarter) {
					if(this.timeCurrent == 0) {
					this.sQuarter = this.quarters[this.valueArr[i++]];
					}else {
						this.eQuarter = this.quarters[this.valueArr[i++]];
					}
				}
				if (this.newParams.month) {
					if(this.timeCurrent == 0) {
						this.sMonth = this.months[this.valueArr[i++]];
						}else {
						this.eMonth = this.months[this.valueArr[i++]];
					}
				}
				if (this.newParams.day) {
					if(this.timeCurrent == 0) {
						this.sDay = this.days[this.valueArr[i++]];
						}else {
						this.eDay = this.days[this.valueArr[i++]];
					}
				}
				if (this.newParams.hour) {
					if(this.timeCurrent == 0) {
						this.sHour = this.hours[this.valueArr[i++]];
					}else {
						this.eHour = this.hours[this.valueArr[i++]];
					}
				}
				if (this.newParams.minute) {
					if(this.timeCurrent == 0) {
						this.sMinute = this.minutes[this.valueArr[i++]];
					}else {
						this.eMinute = this.minutes[this.valueArr[i++]];
					}
				}
				if (this.newParams.second) {
					if(this.timeCurrent == 0) {
						this.sSecond = this.seconds[this.valueArr[i++]];
					}else {
						this.eSecond = this.seconds[this.valueArr[i++]];
					}
				}
				// if (this.newParams.timestamp) {
				// 	if(this.timeCurrent == 0) {
				// 		this.sTimestamp = this.getTimestamp(this.sYear,this.sMonth,this.sDay,this.sHour);
				// 		}else {
				// 		this.eTimestamp = this.getTimestamp(this.eYear,this.eMonth,this.eDay,this.eHour);
				// 	}
				// }
				let input = ''
				if (this.timeCurrent == 0) {
					if (this.newParams.year) { input += this.sYear+'年';}
					if (this.newParams.quarter) { input +=  '第' + this.sQuarter+'季度';}
					if (this.newParams.month) {  input += this.sMonth+'月';}
					if (this.newParams.day)  { input += this.sDay+'日';}
					if (this.newParams.hour) { input += this.sHour+'时';}
					if (this.newParams.minute) { input += this.sMinute+'分';}
					if (this.newParams.second) { input += this.sSecond+'秒';}
				}else {
					if (this.newParams.year) { input += this.eYear+'年';}
					if (this.newParams.quarter) { input +=  '第' + this.eQuarter+'季度';}
					if (this.newParams.month) {  input += this.eMonth+'月';}
					if (this.newParams.day)  { input += this.eDay+'日';}
					if (this.newParams.hour) { input += this.eHour+'时';}
					if (this.newParams.minute) { input += this.eMinute+'分';}
					if (this.newParams.second) { input += this.eSecond+'秒';}
				}
				this.timelist[this.timeCurrent].name = input

			}else {
				if (this.mode == 'time') {
					// 这里使用i++，是因为this.valueArr数组的长度是不确定长度的，它根据this.params的值来配置长度
					// 进入if规则，i会加1，保证了能获取准确的值
					if (this.newParams.year) this.year = this.years[this.valueArr[i++]];
					if (this.newParams.quarter) this.quarter = this.quarters[this.valueArr[i++]];
					if (this.newParams.month) this.month = this.months[this.valueArr[i++]];
					if (this.newParams.day) this.day = this.days[this.valueArr[i++]];
					if (this.newParams.hour) this.hour = this.hours[this.valueArr[i++]];
					if (this.newParams.minute) this.minute = this.minutes[this.valueArr[i++]];
					if (this.newParams.second) this.second = this.seconds[this.valueArr[i++]];
				} else if (this.mode == 'region') {
					if (this.newParams.province) this.province = this.valueArr[i++];
					if (this.newParams.city) this.city = this.valueArr[i++];
					if (this.newParams.area) this.area = this.valueArr[i++];
				} else if (this.mode == 'multiSelector') {
					let index = null;
					// 对比前后两个数组，寻找变更的是哪一列，如果某一个元素不同，即可判定该列发生了变化
					this.defaultSelector.map((val, idx) => {
						if (val != e.detail.value[idx]) index = idx;
					});
					// 为了让用户对多列变化时，对动态设置其他列的变更
					if (index != null) {
						this.$emit('columnchange', {
							column: index,
							index: e.detail.value[index]
						});
					}
				}
			}
		},
		// 用户点击确定按钮
		getResult(event = null) {
			// #ifdef MP-WEIXIN
			if (this.moving) return;
			// #endif
			let result = {};
			// 只返回用户在this.params中配置了为true的字段
			if (this.timeRange && this.mode == 'time') {
				if (event == 'reset') {
					// 重置,结束时间清空,开始时间回到当前时间
					let time =new Date()
					// 获取年日月时分秒
					this.sYear = time.getFullYear();
					this.sMonth = Number(time.getMonth()) + 1;
					// 获取当前季度：
					let currMonth= new Date().getMonth()+1;
					this.sQuarter= Math.floor( ( currMonth % 3 == 0 ? ( currMonth / 3 ) : ( currMonth / 3 + 1 ) ) );
					this.sDay = time.getDate();
					this.sHour = time.getHours();
					// 初始化
					this.init()
					if (this.timeCurrent == 0) {
						// 当下标在开始时间时,结束时间清空
						this.timelist[1].name = ''
					}else {
						// 当下标在结束时间时,结束时间清空,下标回到开始时间
						this.timelist[this.timeCurrent].name = ''
						this.timeCurrent =0
					}
				}else if(event == 'confirm') {
					if (this.timeCurrent == 0) {
						// 当在下标在开始时间时
						// 下一步
						this.timeCurrent = 1
						this.getSelectDate()
					}else {
						// 当在下标在开结束时间时
						// 确定
						if (this.newParams.year) { result.sYear = this.formatNumber(this.sYear || 0);result.eYear = this.formatNumber(this.eYear || 0); }
						if (this.newParams.quarter) { result.sQuarter = this.sQuarter || 0;result.eQuarter = this.eQuarter || 0; }
						if (this.newParams.month) { result.sMonth = this.formatNumber(this.sMonth || 0);result.eMonth = this.formatNumber(this.eMonth || 0); }
						if (this.newParams.day) { result.sDay = this.formatNumber(this.sDay || 0);result.eDay = this.formatNumber(this.eDay || 0); }
						if (this.newParams.hour) { result.sHour = this.formatNumber(this.sHour || 0);result.eHour = this.formatNumber(this.eHour || 0); }
						if (this.newParams.minute) { result.sMinute = this.formatNumber(this.sMinute || 0);result.eMinute = this.formatNumber(this.eMinute || 0); }
						if (this.newParams.second) { result.sSecond = this.formatNumber(this.sSecond || 0);result.eSecond = this.formatNumber(this.eSecond || 0); }
						if (this.newParams.timestamp) {
							switch (this.current) {
								case 0:
									result.sTimestamp = this.getTimestamp(result.sYear || null,result.sMonth || '1',result.sDay || '1',result.sHour || '00',result.sMinute || '00',result.sSecond || '00');
									result.eTimestamp = this.getTimestamp(result.eYear || null,result.eMonth || '1',result.eDay || '1',result.eHour || '00',result.sMinute || '00',result.sSecond || '00');
									break;
								case 1:
									result.sTimestamp = this.getTimestamp(this.sYear,this.sMonth,this.sDay);
									result.eTimestamp = this.getTimestamp(this.eYear,this.eMonth,this.eDay,23,59,59);
									break;
								case 2:
									result.sTimestamp = this.getTimestamp(this.sYear,this.sMonth);
									result.eTimestamp = this.getTimestamp(this.eYear,this.eMonth,new Date(this.eYear, this.eMonth, 0).getDate(),23,59,59);
									break;
								case 3:
									let sMonth="",eMonth="",eDay=""
									switch (this.sQuarter) {
										case 1:
											sMonth = 1
											break;
										case 2:
											sMonth = 4
											break;
										case 3:
											sMonth = 7
											break;
										case 4:
											sMonth = 10
											break;
										default:
											break;
									}
									switch (this.eQuarter) {
										case 1:
											eMonth = 3
											eDay=31
											break;
										case 2:
											eMonth = 6
											eDay=30
											break;
										case 3:
											eMonth = 9
											eDay=30
											break;
										case 4:
											eMonth = 12
											eDay=31
											break;
										default:
											break;
									}
									result.sTimestamp = this.getTimestamp(this.sYear,sMonth);
									result.eTimestamp = this.getTimestamp(this.eYear,eMonth,eDay,23,59,59);
									break;
								case 4:
									result.sTimestamp = this.getTimestamp(this.sYear);
									result.eTimestamp = this.getTimestamp(this.eYear,12,31,23,59,59);
									break;
								default:
									break;
							}
						}
						if (result.sTimestamp > result.eTimestamp) {
							uni.showToast({
								title: '结束时间必须大于等于开始时间',
								icon: 'none',
								mask: true,
								duration: 2000
							})
						}else {
							if (event) this.$emit(event, result);
							this.close();
						}
					}
				}
			}else {
				if (this.mode == 'time') {
					if (this.newParams.year) result.year = this.formatNumber(this.year || 0);
					if (this.newParams.quarter) result.quarter = this.quarter || 0;
					if (this.newParams.month) result.month = this.formatNumber(this.month || 0);
					if (this.newParams.day) result.day = this.formatNumber(this.day || 0);
					if (this.newParams.hour) result.hour = this.formatNumber(this.hour || 0);
					if (this.newParams.minute) result.minute = this.formatNumber(this.minute || 0);
					if (this.newParams.second) result.second = this.formatNumber(this.second || 0);
					if (this.newParams.timestamp) result.timestamp = this.getTimestamp(this.year,this.month,this.day,this.hour,this.minute,this.second);
				} else if (this.mode == 'region') {
					if (this.newParams.province) result.province = provinces[this.province];
					if (this.newParams.city) result.city = citys[this.province][this.city];
					if (this.newParams.area) result.area = areas[this.province][this.city][this.area];
				} else if (this.mode == 'selector') {
					result = this.valueArr;
				} else if (this.mode == 'multiSelector') {
					result = this.valueArr;
				}
				if (event) this.$emit(event, result);
				this.close();
			}
		},
		// 获取时间戳
		getTimestamp(year,month='1',day='1',hour='00',minute='00',second='00') {
			// yyyy-mm-dd为安卓写法，不支持iOS，需要使用"/"分隔，才能二者兼容
			let	time = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second;
			return new Date(time).getTime();
		},
		timechange(index) {
			this.current = index;
		},
		// 切换开始时间和结束时间
		timeRangechange(index){
			this.timeCurrent = index;
			// console.log(index);
		}
	}
};
</script>

<style lang="scss" scoped>
@import '../../libs/css/style.components.scss';
@include themify($themes) {

.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: 28rpx 0;
	box-sizing: border-box;
	// color: themed('font-size-16');
	background: #fff;
	position: relative;
	&-btn {
		@include vue-flex;
		justify-content: space-between;
		align-items: center;
	}
}

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

	&--tips {
		color: $u-tips-color;
	}
}

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

::v-deep .uni-picker-view-mask {
	background:-webkit-linear-gradient(top,hsla(0,0%,100%,.6),hsla(0,0%,100%,.6)),-webkit-linear-gradient(bottom,hsla(0,0%,100%,.6),hsla(0,0%,100%,.6));
	background:linear-gradient(180deg,hsla(0,0%,100%,0.6),hsla(0,0%,100%,.6)),linear-gradient(0deg,hsla(0,0%,100%,.6),hsla(0,0%,100%,.6));
	background-position: top,bottom;
    background-size: 100% 102px;
    background-repeat: no-repeat;
}

.uni-picker-view-indicator {
	height: 54px;
}

.uni-picker-view-content.picker-view-column>* {
	height: 54px;
}

.u-picker__title {
	color: themed('u-content-color');
}

.u-picker-body {
	width: 100%;
	height: 500rpx;
	overflow: hidden;
	background-color: themed('u-bg-color');
}

.u-column-item {
	@include vue-flex;
	align-items: center;
	justify-content: center;
	font-size: themed('font-size-14');
	color: #000;
	font-weight: 600;
	padding: 0 8rpx;
}

.u-text {
	font-size: themed('font-size-14');
	font-weight: 600;
	// padding-left: 8rpx;
}

.u-opacity {
	opacity: 0.5;
}

}
</style>
