index.js 10.4 KB
Component({
  properties: {
    show: {
      type: Boolean,
      observer: function (n) {
        if (n) {
          this.initDate()
        }
      }
    },
    title: {
      type: String
    },
    defaultTime: {
      // 新增:传入默认时间
      type: String,
      value: ''
    },
    isStartTime: {
      // 新增:标识是否是开始时间选择器
      type: Boolean,
      value: true
    },
    endTime: {
      // 新增:结束时间(用于开始时间选择器验证)
      type: String,
      value: ''
    },
    startTime: {
      // 新增:开始时间(用于结束时间选择器验证)
      type: String,
      value: ''
    }
  },

  data: {
    hours: [],
    days: [],
    minutes: [],
    seconds: [],
    dateValues: [],
    hourValues: [],
    minuteValues: [],
    secondValues: [],
    loading: true,
    errorMsg: '' // 新增:错误提示信息
  },

  methods: {
    noScroll() {},
    hide(e) {
      let { name } = e.currentTarget.dataset
      let thisPage = wx.$router.getPageInstance()
      thisPage.setData({
        [name]: false
      })
      this.triggerEvent('close')
    },

    // 新增方法:解析默认时间
    parseDefaultTime() {
      const { defaultTime } = this.properties
      if (!defaultTime) {
        return this.getCurrentTimeData()
      }

      try {
        const date = new Date(defaultTime.replace(/-/g, '/'))
        if (isNaN(date.getTime())) {
          return this.getCurrentTimeData()
        }

        return {
          year: date.getFullYear(),
          month: date.getMonth() + 1,
          day: date.getDate(),
          hour: date.getHours(),
          minute: date.getMinutes(),
          second: date.getSeconds(),
          dateStr: date.format('yyyy-MM-dd')?.replace(/\//g, '-')
        }
      } catch (error) {
        return this.getCurrentTimeData()
      }
    },

    // 新增方法:获取当前时间数据
    getCurrentTimeData() {
      const today = new Date()
      return {
        year: today.getFullYear(),
        month: today.getMonth() + 1,
        day: today.getDate(),
        hour: today.getHours(),
        minute: today.getMinutes(),
        second: today.getSeconds(),
        dateStr: today.format('yyyy-MM-dd')?.replace(/\//g, '-')
      }
    },

    getDateList(starDay, endDay) {
      const arr = []
      const dates = []

      const db = new Date(starDay)
      const de = new Date(endDay)
      const s = db.getTime() - 24 * 60 * 60 * 1000
      const d = de.getTime() - 24 * 60 * 60 * 1000

      for (let i = s; i <= d; ) {
        i = i + 24 * 60 * 60 * 1000
        arr.push(parseInt(String(i)))
      }

      for (const j in arr) {
        const time = new Date(arr[j])
        const year = time.getFullYear()
        const mouth =
          time.getMonth() + 1 >= 10
            ? time.getMonth() + 1
            : '0' + (time.getMonth() + 1)
        const day = time.getDate() >= 10 ? time.getDate() : '0' + time.getDate()
        const YYMMDD = year + '-' + mouth + '-' + day
        dates.push(YYMMDD)
      }
      this.getHourList(dates)
    },

    getHourList(days) {
      const defaultTime = this.parseDefaultTime()
      const today = new Date()
      const hours = []

      // 根据是否是当前日期决定小时范围
      const isToday =
        defaultTime.dateStr === today.format('yyyy-MM-dd')?.replace(/\//g, '-')
      const hourLimit = isToday ? today.getHours() + 1 : 24
      for (let hour = 0; hour < hourLimit; hour++) {
        hours.push(hour.toString().padStart(2, '0'))
      }
      this.getMinuteList(days, hours, defaultTime)
    },

    getMinuteList(days, hours, defaultTime) {
      const today = new Date()
      const minutes = []
      const isToday =
        defaultTime.dateStr === today.format('yyyy-MM-dd')?.replace(/\//g, '-')
      const isCurrentHour = defaultTime.hour === today.getHours()
      const minuteLimit = isToday && isCurrentHour ? today.getMinutes() + 1 : 60
      for (let minute = 0; minute < minuteLimit; minute++) {
        minutes.push(minute.toString().padStart(2, '0'))
      }
      const seconds = ['00']
      this.setDefaultValues(days, hours, minutes, seconds, defaultTime)
    },

    // 新增方法:设置默认选中值
    setDefaultValues(days, hours, minutes, seconds, defaultTime) {
      // 查找日期索引
      const dateIndex = days.findIndex(day => day === defaultTime.dateStr)
      const hourIndex = hours.findIndex(
        hour => parseInt(hour) === defaultTime.hour
      )
      const minuteIndex = minutes.findIndex(
        minute => parseInt(minute) === defaultTime.minute
      )
      const secondIndex = seconds.findIndex(
        second => parseInt(second) === defaultTime.second
      )

      this.setData(
        {
          hours,
          days,
          minutes,
          seconds,
          dateValues: [dateIndex >= 0 ? dateIndex : days.length - 1],
          hourValues: [hourIndex >= 0 ? hourIndex : hours.length - 1],
          minuteValues: [minuteIndex >= 0 ? minuteIndex : minutes.length - 1],
          secondValues: [secondIndex >= 0 ? secondIndex : seconds.length - 1],
          loading: false
        },
        () => {
          wx.nextTick(() => {})
          setTimeout(() => {
            // 设置当前选中时间
            this.currentDate =
              days[dateIndex >= 0 ? dateIndex : days.length - 1]
            this.currentHour =
              hours[hourIndex >= 0 ? hourIndex : hours.length - 1]
            this.currentMinute =
              minutes[minuteIndex >= 0 ? minuteIndex : minutes.length - 1]
            this.currentSecond =
              seconds[secondIndex >= 0 ? secondIndex : seconds.length - 1]

            this.setData({
              minuteValues: [
                minuteIndex >= 0 ? minuteIndex : minutes.length - 1
              ],
              secondValues: [
                secondIndex >= 0 ? secondIndex : seconds.length - 1
              ],
              loading: false
            })
          }, 0)
        }
      )
    },

    changeDate(e) {
      const { days } = this.data
      const { value } = e.detail
      const index = value[0]
      this.currentDate = days[index]

      const today = new Date().format('yyyy-MM-dd')?.replace(/\//g, '-')
      const timeType = this.currentDate != today ? 1 : 0
      this.getAllTimeOrPartTime(timeType)
    },

    changeHour(e) {
      const { hours } = this.data
      const { value } = e.detail
      const index = value[0]
      this.currentHour = hours[index]
      const today = new Date().format('yyyy-MM-dd')?.replace(/\//g, '-')
      const timeType = this.currentDate != today ? 1 : 0
      this.getAllTimeOrPartTimeMinute(timeType)
    },

    changeMinutes(e) {
      const { minutes } = this.data
      const { value } = e.detail
      const index = value[0]
      this.currentMinute = minutes[index]
    },

    changeSeconds(e) {
      const { seconds } = this.data
      const { value } = e.detail
      const index = value[0]
      this.currentSecond = seconds[index]
    },

    // 新增方法:验证时间有效性
    validateTime() {
      const { isStartTime, endTime, startTime } = this.properties
      const selectedTimeStr = `${this.currentDate} ${this.currentHour}:${this.currentMinute}:00`
      const selectedTime = new Date(
        selectedTimeStr.replace(/-/g, '/')
      ).getTime()

      let errorMsg = ''

      if (isStartTime && endTime) {
        // 开始时间不能晚于结束时间
        const endTimeStamp = new Date(endTime.replace(/-/g, '/')).getTime()
        if (selectedTime > endTimeStamp) {
          errorMsg = '开始时间不能晚于结束时间'
        }
      } else if (!isStartTime && startTime) {
        // 结束时间不能早于开始时间
        const startTimeStamp = new Date(startTime.replace(/-/g, '/')).getTime()
        if (selectedTime < startTimeStamp) {
          errorMsg = '结束时间不能早于开始时间'
        }
      }

      this.setData({ errorMsg })
      return !errorMsg
    },

    confirm() {
      // 最终确认前再次验证
      if (!this.validateTime()) {
        wx.showToast({
          title: this.data.errorMsg,
          icon: 'none'
        })
        return
      }

      const str = `${this.currentDate} ${this.currentHour}:${this.currentMinute}:00`
      const result = new Date(str.replace(/-/g, '/'))
        .format('yyyy-MM-dd hh:mm:ss')
        ?.replace(/\//g, '-')
      this.triggerEvent('confirm', result)
      this.setData({ errorMsg: '' })
    },

    cancel() {
      this.triggerEvent('cancel')
    },

    initDate() {
      this.setData({
        dateValues: [],
        hourValues: [],
        minuteValues: [],
        secondValues: [],
        errorMsg: ''
      })
      const today = new Date()
      const defaultTime = this.parseDefaultTime()
      const todayEnd = new Date(today.getFullYear(), today.getMonth(), today.getDate())
      let endDay = todayEnd
      if (defaultTime?.year && defaultTime?.month && defaultTime?.day) {
        const defaultEnd = new Date(defaultTime.year, defaultTime.month - 1, defaultTime.day)
        if (!isNaN(defaultEnd.getTime()) && defaultEnd.getTime() > todayEnd.getTime()) {
          endDay = defaultEnd
        }
      }
      this.getDateList(
        '2019/01/01',
        endDay
      )
    },

    getAllTimeOrPartTime(type) {
      const today = new Date()
      const hours = [],
        minutes = []
      const hour_len = type == 1 ? 24 : today.getHours() + 1
      const minute_len = type == 1 ? 60 : today.getMinutes() + 1
      const second_len = 0

      for (let hour = 0; hour < hour_len; hour++) {
        hours.push(hour.toString().padStart(2, '0'))
      }
      for (let minute = 0; minute < minute_len; minute++) {
        minutes.push(minute.toString().padStart(2, '0'))
      }
      this.setData({ hours, minutes, seconds: ['00'], secondValues: [0] })
    },

    getAllTimeOrPartTimeMinute(type) {
      const today = new Date()
      const currentHour = today.getHours()
      const timeType = this.currentHour != currentHour ? 1 : 0
      const minutes = []
      const minute_len =
        type == 1 || timeType == 1 ? 60 : today.getMinutes() + 1
      const second_len = 0

      for (let minute = 0; minute < minute_len; minute++) {
        minutes.push(minute.toString().padStart(2, '0'))
      }
      this.setData({ minutes, seconds: ['00'], secondValues: [0] })
    },

    updateSecondsByMinute() {
      this.setData({ seconds: ['00'], secondValues: [0] })
    }
  },

  lifetimes: {
    attached: function () {
      this.initDate()
    }
  }
})