<template>
	<u-popup v-model="show"
					 mode="bottom"
					 :mask-close-able="false">
		<view style="">
			<text style="margin: 30upx;color: #1890FF;float: left;" @click="cancel">{{$i18n.locale=='zh'?'取消':'cancel'}}</text>
			<text style="margin: 30upx;color: #1890FF;float: right;" @click="btn">{{$i18n.locale=='zh'?'确定':'sure'}}</text>
			<view style="clear: both;"></view>
		</view>
		<view style="height: 600upx">
			<picker-view :indicator-style="'height: 50upx'" :value="initTimeValue" @change="bindChange" class="picker-view">
				<picker-view-column>
					<view class="item" v-for="(item,index) in startDateList" :key="index">{{item}}{{$i18n.locale=='zh'?'年':'year'}}</view>
				</picker-view-column>
				<picker-view-column v-if="range">
					<view class="item" v-for="(item,index) in endDateList" :key="index">{{item}}{{$i18n.locale=='zh'?'年':'year'}}</view>
				</picker-view-column>
			</picker-view>
		</view>
	</u-popup>
</template>

<script>
const date = new Date()
const year = date.getFullYear()
export default {
	name: "yearSelector",
	props: {
		range: {
			type: Boolean,
			default: true
		},
		show: {
			type: Boolean,
			default: false
		},
		startYear:{
			type: String | Number,
			default: 1950
		},
		endYear:{
			type: String | Number,
			default: 2050
		},
		defaultTimeValue:{
			type: Array,
			default: ()=>[2015,2025]
		},
	},
	computed:{
		nowYear(){
			return new Date().getFullYear()
		},
		initTimeValue(){
			let val0 = this.startDateList.indexOf(this.nowYear)
			let val1 = this.endDateList.indexOf(this.nowYear)
			if(this.defaultTimeValue){
				val0 = this.startDateList.indexOf(this.defaultTimeValue[0])
				val1 = this.endDateList.indexOf(this.defaultTimeValue[1])
			}
			return [val0,val1]
		},
		startDateList(){
			let arr = []
			for (let i = this.startYear; i <= this.endYear; i++) {
				arr.push(i)
			}
			return arr
		},
		endDateList(){
			let arr = []
			for (let i = this.flag; i <= this.endYear; i++) {
				arr.push(i)
			}
			return arr
		}
	},
	data(){
		return{
			flag:this.startYear,
			timeValue:this.defaultTimeValue,
		}
	},
	methods:{
		bindChange(e){
			const val = e.detail.value
			if(this.startDateList[val[1]] < this.endDateList[val[0]]){
				this.timeValue = [this.startDateList[val[1]],this.endDateList[val[0]]]
			}else{
				this.timeValue = [this.startDateList[val[0]],this.endDateList[val[1]]]
			}
			// 限制第二列不小于第一列选中值
			// this.flag = this.timeValue[0]
		},
		btn(){
      if(this.range){
        if(this.timeValue[1] - this.timeValue[0] > 7){
          this.$emit('cancel',true)
        }else{
          this.$emit('getTimeValue',this.timeValue)
        }
      }else{
        this.$emit('getTimeValue',this.timeValue)
      }
		},
		cancel(){
			this.$emit('cancel')
		}
	}
}
</script>

<style scoped>
.picker-view {
	width: 750rpx;
	height: 600rpx;
	margin-top: 20rpx;
}
.item {
	height: 50px;
	align-items: center;
	justify-content: center;
	text-align: center;
}
</style>
