Calendar_Function.js 13.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
const _CalendarObject_ = Symbol('_CalendarObject_')
const _nowDate_ = Symbol('_nowDate_')
const _separator_ = Symbol('_separator_')
class Calendar {
  [_CalendarObject_] = {};
  [_nowDate_] = new Date();
  [_separator_] = '-'
  constructor(calendarObject) {
    this[_CalendarObject_] = calendarObject
    this[_separator_] = calendarObject.data.separator
    this.setCalenderHeight()
    this.setMonthList()
    let { weekdays, firstDayOfWeek } = calendarObject.data
    let firstDay = weekdays[firstDayOfWeek - 1]
    let [last, first] = weekdays.join('').split(firstDay)
    calendarObject.setData({
      weekdays: [firstDay, ...first, ...last]
    })
  }
  /**设置日历高度 */
  setCalenderHeight() {
    let _this = this[_CalendarObject_]
    let { data: calenderHeight } = _this
    let height = '80%'
    if (typeof calenderHeight === 'number') {
      wx.$util.getSystemInfo(res => {
        let { windowHeight } = res
        if (calenderHeight > windowHeight) calenderHeight = windowHeight
        if (calenderHeight < windowHeight * 0.5) calenderHeight = windowHeight * 0.5
        height = `${calenderHeight}px`
      })
    }
    if (typeof calenderHeight === 'string') {
      if (calenderHeight.includes('%')) {
        height = calenderHeight
        let [num] = calenderHeight.split('%')
        if (num < 50) height = '50%'
        if (num > 100) height = '80%'
      } else {
        if (calenderHeight < 50) calenderHeight = '50'
        if (calenderHeight > 100) calenderHeight = '80'
        height = `${calenderHeight}%`
      }
    }
    _this.setData({
      isFullSucreen: wx.$util.isFullSucreen(_this.data.isComponents),
      height
    })
  }
  /**设置日期高度 */
  setCalenderBodyHeight() {
    let _this = this[_CalendarObject_]
    wx.$util.getViewInfo(
      '.calender-header',
      header => {
        wx.$util.getViewInfo(
          '.calender-footer',
          footer => {
            let headerHeight = header.height
            let footerHeight = (footer && footer.height) || 0
            _this.setData({
              calenderBodyHeight: `${headerHeight + footerHeight}px`
            })
          },
          _this
        )
      },
      _this
    )
  }
  /**设置日期列表 */
  setMonthList() {
    let { separator, previous, minDate, maxDate, next, MonthShowList, date } = this[_CalendarObject_].data
    if (maxDate || minDate) {
      if (!minDate) {
        let nowMonth = new Date().getMonth()
        minDate = new Date(new Date().setMonth(nowMonth - previous)).format(`yyyy${separator}MM${separator}dd`)
      }
      if (!maxDate) {
        maxDate = this[_nowDate_].format(`yyyy${separator}MM${separator}dd`)
      }
      previous = this.getMonthDifference(minDate, this[_nowDate_].format(`yyyy${separator}MM${separator}dd`))
      next = this.getMonthDifference(this[_nowDate_].format(`yyyy${separator}MM${separator}dd`), maxDate)
    } else {
      previous = previous < 0 ? 0 : previous
      next = next < 0 ? 0 : next
    }
    let nowMonth = this[_nowDate_].getMonth()
    let now = new Date().setDate(1)
    for (let i = nowMonth - previous; i <= nowMonth + next; i++) {
      // console.log(new Date(now).setMonth(i))
      this.init(new Date(now).setMonth(i))
    }

    // 处理按月份选择
    let _this = this[_CalendarObject_]
    let [minYear, minMonth] = minDate.split(separator)
    let [maxYear, maxMonth] = maxDate.split(separator)
    let yearList = []
    let now_Year = new Date().getFullYear()
    let now_Month = new Date().getMonth()
    // console.log(now_Month)
    for (let index = minYear; index <= maxYear; index++) {
      let mothObj = []
      for (let MonIndex = 0; MonIndex < 12; MonIndex++) {
        let month = MonIndex + 1 >= 10 ? MonIndex + 1 : `0${MonIndex + 1}`
        let obj = {
          label: `${MonIndex + 1}月`,
          disable: false,
          start: false,
          end: false,
          select: false,
          rangeDate: `${index}年${month + 1}月`,
          date: `${index}-${month}`
        }
        if ((MonIndex + 1 < minMonth && minYear == index) || (maxYear == index && maxMonth < MonIndex + 1)) {
          obj.disable = true
        }
        if (index == now_Year && MonIndex == now_Month) {
          obj.start = true
          obj.end = true
          obj.active = true
          date = obj
        }
        mothObj.push(obj)
      }
      yearList.unshift(mothObj)
    }
    // console.log(new Date().format(`yyyy${separator}MM`))

    _this.setData({
      yearList,
      rangeMonth: {
        start: new Date().format(`yyyy${separator}MM`),
        end: new Date().format(`yyyy${separator}MM`)
      },
      date
    })
    // console.log(yearList)
  }
  /**初始化日期 */
  init(date) {
    let _this = this[_CalendarObject_]
    let { firstDayOfWeek, allowSameDay, multipleDate, monthList, rangeDate, dateList, monPickList, dateType, current, minDate, maxDate, value } = _this.data
    // console.log(current)
    let separator = this[_separator_]
    let [year, month] = new Date(date).format(`yyyy${separator}MM`).split(separator)
    // console.log(year, month)
    let days = this.getDayNumber(year, Number(month))
    let week = new Date(year, Number(month) - 1, 1).getDay()
    let dateFormat = `yyyy${separator}MM${separator}dd`
    let today = value || this[_nowDate_].format(dateFormat)
    let nextDay = ''
    let arr = []
    dateList.push(`${year}${separator}${month}`)
    monPickList.unshift(year)
    monPickList = [...new Set(monPickList)]

    if (dateType === 'range') {
      nextDay = new Date(new Date().setDate(new Date(new Date(today)).getDate() + 1)).format(dateFormat)
    }
    let [now_year, now_month, now_day] = today.split(separator)
    let [next_year, next_month, next_day] = allowSameDay ? today.split(separator) : nextDay.split(separator)
    for (let i = 1; i <= days; i++) {
      let todayStr = `${year}${separator}${month}${separator}${now_day}`
      let dayStr = `${year}${separator}${month}${separator}${i < 10 ? `0${i}` : i}`
      let obj = {
        day: i,
        data: dayStr,
        active: now_year == year && now_month == month && i == Number(now_day)
      }
      if ((minDate && Date.parse(minDate) > Date.parse(dayStr)) || (maxDate && Date.parse(maxDate) < Date.parse(dayStr))) obj.disable = true
      if (dateType === 'multiple') multipleDate.push(todayStr)
      if (nextDay) {
        if (now_year == year && now_month == month && i == Number(now_day)) {
          obj.start = true
          rangeDate.start = todayStr
        }
        if (next_year == year && next_month == month && i == Number(next_day)) {
          obj.active = true
          obj.end = true
          rangeDate.end = `${year}${separator}${next_month}${separator}${next_day}`
        }
      }
      firstDayOfWeek = firstDayOfWeek == 7 ? 0 : firstDayOfWeek
      if (i === 1) obj.week = `week-${week - firstDayOfWeek}`
      arr.push(obj)
    }
    monthList.push({
      data: arr,
      mark: Number(month)
    })
    if (current <= 1) {
      let [nowYear, nowMonth] = today.split(separator)
      // console.log(dateList)
      // console.log(today.split(separator))
      current = dateList.findIndex(e => e === `${nowYear}${separator}${nowMonth}`)
    }
    _this.setData({
      multipleDate,
      // date: today,
      rangeDate,
      monthList,
      dateList,
      monPickList,
      current
    })
  }
  /**当设置最小日期或者最大日期时 自动设置前后月份 */
  getMonthDifference(date1, date2) {
    let separator = this[_separator_]
    //获取年,月数
    let [year1, month1] = date1.split(separator)
    let [year2, month2] = date2.split(separator)
    let months = (parseInt(year2) - parseInt(year1)) * 12 + (parseInt(month2) - parseInt(month1))
    return months
  }
  /**单选 */
  single(e) {
    let _this = this[_CalendarObject_]
    let { yearindex, index } = e.currentTarget.dataset
    console.log(yearindex, index)
    // console.log(index, data, ind);
    let { showConfirm, yearList } = _this.data
    yearList.map(x => {
      x.map(i => (i.active = false))
    })
    // monthList[index].data[ind].active = true
    yearList[yearindex][index].active = true
    _this.setData({
      yearList,
      date: yearList[yearindex][index]
    })
    if (!showConfirm) this.done()
  }
  /**多选 */
  multiple(e) {
    let _this = this[_CalendarObject_]
    let { index, ind } = e.currentTarget.dataset
    let { monthList } = _this.data
    let arr = []
    monthList[index].data[ind].active = !monthList[index].data[ind].active
    monthList.map(x =>
      x.data.map(i => {
        if (i.active) arr.push(i.data)
      })
    )
    _this.setData({
      [`monthList[${index}].data`]: monthList[index].data,
      multipleDate: arr
    })
  }
  /**范围选择 */
  range(e) {
    const _this = this[_CalendarObject_]
    let { index, data, ind } = e.currentTarget.dataset
    let { allowSameDay, showConfirm, monthList, rangeDate } = _this.data
    const start = Date.parse(rangeDate.start)
    if (rangeDate.end || start > Date.parse(data)) {
      monthList = this.clearStatus({
        monthList,
        index,
        ind
      })
      rangeDate.start = data
      rangeDate.end = ''
    } else {
      if (!allowSameDay && Date.parse(data) == Date.parse(rangeDate.start)) return
      monthList[index].data[ind].active = true
      monthList[index].data[ind].end = true
      rangeDate.end = data
      monthList.map(x => {
        x.data.map(i => {
          let day = Date.parse(i.data)
          i.middle = day > start && day < Date.parse(data)
        })
      })
    }
    _this.setData({
      monthList,
      rangeDate
    })
    if (!showConfirm && rangeDate.end) this.done()
  }

  /** 月份选择 */
  month(e) {
    console.log(e)
    // return
    const _this = this[_CalendarObject_]
    let { rangeMonth, yearList, showConfirm } = _this.data
    let { index, yearindex, data } = e.currentTarget.dataset
    const start = Date.parse(rangeMonth.start)
    // console.log(start == Date.parse(data.data))
    let falseObj = {
      end: false,
      start: false,
      select: false
    }
    // console.log(e.currentTarget.dataset)
    console.log(rangeMonth.end || start > Date.parse(data.data))
    console.log(rangeMonth.end)
    console.log(start)
    console.log(data)
    console.log(Date.parse(data.date))
    if (rangeMonth.end || start > Date.parse(data.date)) {
      yearList = yearList.map(item => {
        return item.map(ele => {
          return {
            ...ele,
            ...falseObj
          }
        })
      })
      yearList[yearindex][index]['start'] = true
      // yearList[yearindex][index]['select'] = true
      rangeMonth.start = data.date
      rangeMonth.end = ''
      // console.log(yearList)
    } else {
      yearList[yearindex][index]['end'] = true
      // monthList[index].data[ind].active = true
      // monthList[index].data[ind].end = true
      rangeMonth.end = data.date
      yearList.map(x => {
        x.map(i => {
          // console.log(i.date)
          let day = Date.parse(i.date)
          // console.log(day > start && day < Date.parse(data.date))
          i.select = day > start && day < Date.parse(data.date)
        })
      })
    }

    _this.setData({
      yearList,
      rangeMonth
    })
    if (!showConfirm && rangeMonth.end) this.done()
  }

  /**点击完成 */
  done() {
    let _this = this[_CalendarObject_]
    let { multipleDate, rangeDate, dateType, date, rangeMonth, dayType } = _this.data
    let targer = {
      single: date,
      multiple: multipleDate,
      range: rangeDate
      // month: rangeMonth
    }
    _this.triggerEvent('select', {
      date: date
      // type: 'dayType'
    })
    // 月份
    // if (!dayType) {
    //   if (!rangeMonth.end) return
    //   _this.triggerEvent('select', {
    //     date: rangeMonth,
    //     type: 'dayType'
    //   })
    // } else {
    //   // 日期
    //   if ((dateType === 'multiple' && multipleDate.length < 1) || (dateType === 'range' && !rangeDate.end)) return
    //   _this.triggerEvent('select', {
    //     date: targer[dateType]
    //   })
    // }

    _this.showCalendar()
  }

  /**清空范围选择状态 */
  clearStatus(params) {
    let { monthList, index, ind } = params
    monthList.map(x =>
      x.data.map(i => {
        i.active = false
        i.start = false
        i.end = false
        i.middle = false
      })
    )
    monthList[index].data[ind].active = true
    monthList[index].data[ind].start = true
    return monthList
  }
  /**
   * 获取月份天数
   */
  getDayNumber(year, month) {
    let days = 31
    switch (month) {
      case 2:
        days = (year % 4 == 0 && year % 100 !== 0) || year % 400 == 0 ? 29 : 28
        break
      case 4:
      case 6:
      case 9:
      case 11:
        days = 30
        break
    }
    return days
  }
  /**日期范围 点击全选 */
  chooseAll() {
    let _this = this[_CalendarObject_]
    let { monthList, minDate, maxDate } = _this.data
    monthList.map((e, index) => {
      e.data.map((i, ind) => {
        let obj = {
          currentTarget: {
            dataset: {
              index,
              ind,
              data: i.data
            }
          }
        }
        if (i.data == minDate) this.range(obj)
        if (i.data == maxDate) this.range(obj)
      })
    })
  }
}

export default Calendar