<!--时间选择器 年、月、日、周、季度-->
<template>
  <div>
    <van-field readonly
               clickable
               required
               name="datetimePicker"
               :value="dateParam"
               label="报告日期"
               placeholder="点击选择时间"
               input-align="right"
               @click="selectDate" />
    <van-popup v-if="showPickerDate"
               v-model="showPickerDate"
               position="bottom">
      <van-picker v-if="dateType === 'year' || dateType === 'season'"
                  show-toolbar
                  :title="yearOrQuarterTitle"
                  :columns="yearOrYqColumns"
                  @confirm="onConfirm"
                  @cancel="onCancel" />
      <van-datetime-picker v-if="dateType === 'month' || dateType === 'daily'"
                           v-model="currentTime"
                           :type="yearDatetype"
                           :title="yearDatetitle"
                           :min-date="minDate"
                           :max-date="maxDate"
                           :formatter="formatter"
                           @confirm="onConfirm"
                           @cancel="onCancel" />
      <van-picker v-if="dateType === 'week'"
                  show-toolbar
                  title="年-周"
                  :columns="yearWeekColumns"
                  @confirm="onConfirm"
                  :defaultIndex="weekDefaultIndex"
                  @cancel="onCancel" />
    </van-popup>

  </div>
</template>
<script>
import util from '../../../common/util'
export default {
  props: {
    dateType: String, // 日期类型 1.年(year)， 2.年月(month)， 3.年月日(daily)，4.周(week)，5.季度(season)
    initDateParam: String // 初始化时间
  },
  data () {
    return {
      dateParam: '',
      // 报告时间
      showPickerDate: false,
      // 根据年获取周
      years: [],
      yearWeekColumns: [],
      weekDefaultIndex: 0,
      // 年月日或者年月
      yearDatetype: '', // date为年月日，year-month为年-月
      minDate: new Date(2000, 0, 1),
      maxDate: new Date(2099, 10, 1),
      currentTime: '',
      yearDatetitle: '',
      // 年或年季
      yearOrYqColumns: [],
      yearOrQuarterTitle: ''
    }
  },
  watch: {
    initDateParam: {
      handler: function (val) {
        this.dateParam = val
      },
      deep: true
    },
    dateParam: {
      handler: function (val) {
        if (val !== '' && this.dateType !== '') {
          if (this.dateType === 'month' || this.dateType === 'daily') {
            let year = val.split('-')[0] || 2000
            let month = this.dateType === 'month' ? val.split('-')[1] : val.split('-')[1] - 1
            let day = val.split('-')[2] || 0
            this.currentTime = new Date(year, month, day)
          }
        }
      },
      deep: true
    },
    dateType: {
      handler: function (newType, oldType) {
        if (oldType !== '') {
          this.dateParam = ''
        }
        this.changeDate(newType)
        if (!this.dateParam || this.dateParam === '') {
          this.dateParam = this.initReportDate(newType)
          this.changeDate(newType)
          this.$emit('close', this.dateParam)
        }
      },
      deep: true
    }
  },
  created () {
    this.dateParam = this.initDateParam
  },
  mounted () {
    this.changeDate(this.dateType)
  },
  methods: {
    setTime (dateParam) {
      this.dateParam = dateParam
    },
    selectDate () {
      if (!this.dateType || this.dateType === '') {
        this.$toast('报告类型不能为空！')
        return false
      }
      this.showPickerDate = true
    },
    changeDate (dateType) {
      if (dateType === 'year' || dateType === 'season') {
        this.yearOrYearQuarter(dateType)
      } else if (dateType === 'month' || dateType === 'daily') {
        this.dateOrYearMonth(dateType)
      } else if (dateType === 'week') {
        this.yearAndWeek()
      }
    },
    // 年或年季
    yearOrYearQuarter (type) {
      let years = []
      for (let i = 2000; i < 3000; i++) {
        years.push(i.toString())
      }
      let yearOrYqColumns = [{ defaultIndex: 0, values: years }]
      if (type === 'season') {
        yearOrYqColumns.push({
          defaultIndex: 0,
          values: ['第1季度', '第2季度', '第3季度', '第4季度']
        })
        this.yearOrQuarterTitle = '年—季度'
      } else {
        this.yearOrQuarterTitle = '年'
      }
      if (this.dateParam !== '') {
        if (type === 'season') {
          this.dateParam = this.dateParam.split('-')[0] + ',第' + this.dateParam.split('-')[1] + '季度'
        }
        let array = this.dateParam.split(',')
        array.forEach((m, i) => {
          yearOrYqColumns[i].values.forEach((n, j) => {
            if (m === n.toString()) {
              yearOrYqColumns[i].defaultIndex = j
            }
          })
        })
      }
      this.yearOrYqColumns = yearOrYqColumns
    },
    // 年-周
    yearAndWeek () {
      let years = []
      for (let i = 2000; i < 2050; i++) {
        years.push(i)
      }
      let yearWeekColumns = []
      years.forEach((year) => {
        let obj = {
          text: year,
          children: []
        }
        let weeks = this.getYearWeek(year)
        weeks.forEach((v) => {
          obj.children.push({ text: v })
        })
        yearWeekColumns.push(obj)
      })
      this.years = years
      let array = this.dateParam.split('-')
      let newDateParam = array[0]
      yearWeekColumns.map((n, j) => {
        if (array[0] === n.text.toString()) {
          this.weekDefaultIndex = j
          n.children.map((z, k) => {
            if (z.text.split('周')[0] === '第' + array[1]) {
              n.defaultIndex = k
              newDateParam = newDateParam + ',' + z.text
            }
          })
        }
      })
      this.dateParam = newDateParam
      this.yearWeekColumns = yearWeekColumns
    },
    // 年月日或者年月
    dateOrYearMonth (type) {
      this.yearDatetype = type === 'month' ? 'year-month' : 'date'
      this.yearDatetitle = type === 'month' ? '年-月' : '年-月-日'
    },
    formatter (type, val) {
      if (type === 'year') {
        return `${val}年`
      } else if (type === 'month') {
        return `${val}月`
      }
      return val
    },

    getYearWeek (year) {
      // 计算出这年的周数
      let weekNum = util.getNumOfWeeks(year)
      // 首先算出这年的第一个星期日
      let firstSunday = new Date(year, 0, 1)
      let n = 6 - ((firstSunday.getDay() + 6) % 7)
      firstSunday.setDate(firstSunday.getDate() + n)
      // 根据年份设置周数
      let weekList = []
      for (let i = 1; i <= weekNum; i++) {
        if (i === 1) {
          // 计算这年第一个周一的日期
          let firstMonday = new Date(
            firstSunday.setDate(firstSunday.getDate() - 6)
          )
          firstSunday.setDate(firstSunday.getDate() + 6)
          let week =
            '第' +
            i +
            '周（' +
            util.getNowFormatDate(firstMonday) +
            '-' +
            util.getNowFormatDate(firstSunday) +
            '）'
          weekList.push(week)
        } else {
          let week = '第' + i + '周' + util.getDateRange(firstSunday)
          // 计算出下一个星期日，有个问题是上面调用getDateRange()已经firstSunday加了7天，这里就不需要重新firstSunday加7天
          weekList.push(week)
        }
      }

      return weekList
    },
    // 关闭日期选择
    onConfirm (value, index) {
      this.dateParam = this.format(this.dateType, value)
      this.$emit('close', this.dateParam)
      this.showPickerDate = false
      // this.clear()
    },

    // 选择的报告日期格式化成展示形式
    format (workType, date) {
      let dateString = ''
      switch (workType) {
        case 'daily':
          dateString = util.formatDate(date)
          break
        case 'week':
          dateString = date.join(',')
          break
        case 'month':
          dateString = util.formatDate(date, true)
          break
        case 'season':
          dateString = date.join(',')
          break
        case 'year':
          dateString = date.join(',')
          break
      }
      return dateString
    },
    // 根据报告类型取当前时间
    initReportDate (reportType) {
      let current = ''
      switch (reportType) {
        case 'daily': current = util.formatDate(new Date()); break
        case 'week': current = (new Date()).getFullYear() + '-' + util.getWeek(new Date()); break // current = (new Date()).getFullYear() + ',第' + util.getWeek(new Date()) + '周(' + util.getWeekStartDate(new Date()) + ')'; break
        case 'month': current = util.formatDate(new Date(), true); break
        case 'season': current = (new Date()).getFullYear() + '-' + util.getSesson(new Date()); break// current = (new Date()).getFullYear() + ',第' + util.getSesson(new Date()) + '季度'; break
        case 'year': current = (new Date()).getFullYear().toString(); break
      }
      return current
    },
    onCancel () {
      this.showPickerDate = false
      // this.clear()
    },
    clear () {
      let obj = {
        dateParam: '',
        // 报告时间
        showPickerDate: false,
        // 根据年获取周
        years: [],
        yearWeekColumns: [],
        // 年月日或者年月
        yearDatetype: '', // date为年月日，year-month为年-月
        minDate: new Date(2000, 0, 1),
        maxDate: new Date(2099, 10, 1),
        currentTime: '',
        yearDatetitle: '',
        // 年或年季
        yearOrYqColumns: [],
        yearOrQuarterTitle: ''
      }

      for (let key in obj) {
        this[key] = obj[key]
      }
    }
  }
}
</script>
