<template>
  <div>
    <!-- 时间选择组件 -->
    <van-row class="cgtime-choose">
      <van-col span="11" class="padding-10" style="padding-right: 3px">
        <van-field v-model="start" @click.stop="chooseTime('start')" :clickable="true" :readonly="true" placeholder="开始日期" />
      </van-col>
      <van-col span="2" class="to"> — </van-col>
      <van-col span="11" class="padding-10" style="padding-left: 3px">
        <van-field v-model="end" @click.stop="chooseTime('end')" :clickable="true" :readonly="true" placeholder="结束日期" />
      </van-col>
    </van-row>
    <van-popup
        v-model="showTimeDialog"
        get-container="body"
        close-icon="close"
        position="bottom"
    >
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          v-if="showTimeDialog"
          @confirm="confirm"
          @cancel="cancel"
          :min-date="minDate"
          :max-date="maxDate"
          :formatter="formatter"
        />
    </van-popup>
  </div>
</template>

<script>
import { getFormateDate, addDateStr } from '@/utils/common'

export default {
  name: 'CgTimeChoose',
  data() {
    return {
      selector: '',
      start: addDateStr(new Date(),0),
      end: addDateStr(new Date(),0),
      minDate: new Date(),
      maxDate: new Date(),
      showTimeDialog: false,
      currentDate: new Date(),
      startDate: new Date(),
      endDate: new Date(),
      maxDateNum: 30
    }
  },
  props: {
    /*
     * 时间选择器的可选最小时间
     */
    min: {
      type: Date,
      default: () => new Date(new Date().getFullYear() - 10, 0, 1)
    },
    /*
     * 时间选择器的可选最大时间
     */
    max: {
      type: Date,
      default: () => new Date()
    },
    /*
     * 时间选择器的重置开始时间
     */
    startTime: {
      type: String,
      default: ''
    },
    /*
     * 时间选择器的重置结束时间
     */
    endTime: {
      type: String,
      default: ''
    }
  },
  watch: {
    startTime (val) {
      if (!val) return false
      this.start = val
    },
    endTime (val) {
      if (!val) return false
      this.end = val
    }
  },
  mounted() {
    // console.log(this.min)
  },
  methods: {
    formatter(type, val) {
      if (type === 'year') {
        return `${val}年`
      } else if (type === 'month') {
        return `${val}月`
      } else if (type === 'day') {
        return `${val}日`
      }
      return val
    },
    confirm (data) {
      this.showTimeDialog = false
      let startTime = new Date();
      let endTime = new Date(); 
      if (this.selector === 'start') {
        startTime = data
        endTime = this.end
        this.startDate = data
      } else if (this.selector === 'end') {
        startTime = this.start
        endTime = data
        this.endDate = data
      }
      // console.log(this.selector,startTime,endTime)
      // console.log(this.timeIntervalNum(startTime,endTime))
      this.timeAction(startTime,endTime,data)
      this.$emit('confirm', {
        start: this.start,
        end: this.end
      })
    },
    // 时间处理
    timeAction(startTime,endTime,data) {
      if (this.selector == 'start'){
        if (this.timeIntervalNum(startTime,endTime) > (this.maxDateNum -1)) {
          this[this.selector] = getFormateDate(new Date(data), 'yyyy-MM-dd')
          this.end = this.addDateStr(startTime,this.maxDateNum)
          return
        } else if (this.timeIntervalNum(startTime,endTime) < 0) {
          this[this.selector] = getFormateDate(new Date(data), 'yyyy-MM-dd')
          this.end = getFormateDate(new Date(data), 'yyyy-MM-dd')
          return
        }
        // this.end = getFormateDate(new Date(data), 'yyyy-MM-dd')
      }
      this[this.selector] = getFormateDate(new Date(data), 'yyyy-MM-dd')
      return
    },
    addDateStr(startTime,AddDayCount) {   
      var dd = startTime;
      if (AddDayCount < 0) {
        dd.setDate(dd.getDate()-AddDayCount);//获取AddDayCount天后的日期
      } else {
        dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
      }
      var y = dd.getFullYear();   
      var m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);//获取当前月份的日期，不足10补0
      var d = dd.getDate()<10?"0"+dd.getDate():dd.getDate();//获取当前几号，不足10补0
      return y+"-"+m+"-"+d;   
    },
     getDay(time,day) {　　
        var today = new Date(time);
        var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;　　
        today.setTime(targetday_milliseconds); //注意，这行是关键代码
        　　
        var tYear = today.getFullYear();　　
        var tMonth = today.getMonth();　　
        var tDate = today.getDate();　　
        tMonth = this.doHandleMonth(tMonth + 1);　　
        tDate = this.doHandleMonth(tDate);　　
        return tYear + "-" + tMonth + "-" + tDate;
    },
    doHandleMonth(month) {　　
        var m = month;　　
        if (month.toString().length == 1) {　　
            m = "0" + month;　　
        }　　
        return m;
    },
    cancel () {
      this.showTimeDialog = false
    },
    chooseTime (type) {
      this.selector = type
      this.currentDate = new Date(this[type])
      this.showTimeDialog = true
      if (type === 'end') {
        let value = !this.start ? new Date() : new Date(this.start)
        // this.minDate = value
        if (this.start == getFormateDate(new Date(), 'yyyy-MM-dd')) {
          this.maxDate = value
          this.minDate = value
        } else {
          if (this.timeIntervalNum(this.start,this.end) > (this.maxDateNum - 1)) {
            this.maxDate = new Date(this.getDay(value,this.maxDateNum))
          } else if (this.timeIntervalNum(this.start,getFormateDate(new Date(), 'yyyy-MM-dd')) <= (this.maxDateNum - 1)) {
            this.maxDate = new Date()
          } else {
            this.maxDate = new Date(this.getDay(this.start,this.maxDateNum))
          }
          this.minDate = value
        }
      } else if (type === 'start') {
        // this.maxDate = !this.end ? new Date() : new Date(this.end)
        // this.minDate = this.min
        this.maxDate = this.max
        this.minDate = this.min
      }
      
    },
    // 判断间隔
    judgmentInterval(start,end) {
      let startTime = new Date(start); // 开始时间
      let endTime = new Date(end); // 结束时间
      let usedTime = endTime - startTime;
      let days = Math.floor(usedTime / (24 * 3600 * 1000));
      // console.log(days)
      if (days > 100) {
        this.$toast('时间间隔不能大于100天！')
        return true
      }
      return false
    },
    // 判断间隔
    timeIntervalNum(start,end) {
      let startTime = new Date(start); // 开始时间
      let endTime = new Date(end); // 结束时间
      let usedTime = endTime - startTime;
      let days = Math.floor(usedTime / (24 * 3600 * 1000));
      return days
    }
  }
}
</script>

<style lang="scss" scoped>
.cgtime-choose {
  .van-cell.van-field {
    padding: 5px 6px;
    background-color: #EFF5F9;
    /deep/ input {
      font-size: 14px;
      text-align: center;
    }
  }
  .to {
    text-align: center;
    line-height: 53px;
    color: #B9B9BB;
  }
}
</style>
