dateScreen.js 11.5 KB
// components/dateScreen/dateScreen.js
import dayjs from 'dayjs'
let currentObj
Component({

  /**
   * 组件的属性列表
   */
  properties: {
		tabSelected: {
			type: Number,
			observer: function (n, o) {
        if (!((n ?? '') === '')) {
					let { timeTypeEnum } = this.data
					if ([1, 2].includes(n)) {
						this.setData({
							dateCurrent: n,
							timeType: timeTypeEnum[n],
							rightCurrent: true,
							leftCurrent: false
						})
						this.initDate(timeTypeEnum[n])
					} else {
						this.setData({
							dateCurrent: 0,
							timeType: timeTypeEnum[0],
							rightCurrent: true,
							leftCurrent: false
						})
						this.initDate(timeTypeEnum[0])
					}
        }
      }
		},
		isSticky: Boolean,
		customBackground: String,
		setTrackData: Boolean
	},
	
	lifetimes: {
		attached: function () {
			this.initDate()
			// 周数据
      // this.getWeeklyData()
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
		// 默认展示今天日期,格式为 月/日
		date: '',
		minDate: dayjs().subtract(1, 'year').valueOf(),
    maxDate: dayjs().valueOf(),
		dateCurrent: 0,
		titleEnum: {
      date: '选择日期',
      week: '选择周',
      'year-month': '选择年月'
		},
		timeType: 'date',
		weekList: [],
    weekColumns: [],
		dateList: [{
      title: '日',
      index: 0
    },
    {
      title: '周',
      index: 1
    },
    {
      title: '月',
      index: 2
		}],
		timeTypeEnum: {
      0: 'date',
      1: 'week',
      2: 'year-month'
		},
		selectedDate: '',
		leftCurrent: false,
		rightCurrent: true
  },

  /**
   * 组件的方法列表
   */
  methods: {
		// 切换日期类型
    selectDate(event) {
      const { index } = event.currentTarget.dataset
			const {timeTypeEnum} = this.data
			let eventCode = ['supervisor_dayTime_tab', 'supervisor_weekTime_tab', 'supervisor_monthTime_tab']
			if (this.data.setTrackData) {
				// wx.$track.setTrackData(0, eventCode[index], {}, '')
			}
      this.setData({
        dateCurrent: index,
        timeType: timeTypeEnum[index],
        rightCurrent: true,
        leftCurrent: false
      })
      this.initDate(timeTypeEnum[index])
		},
		getParams() {
      let { dateCurrent, date, currentWeek } = this.data
      const obj = {}
      switch (dateCurrent) {
        case 0:
          obj.startDay = obj.endDay = dayjs(date).format('YYYY/MM/DD')
          break;
        case 1:
          obj.startDay = dayjs(currentWeek.startDate).format('YYYY/MM/DD')
          obj.endDay   = dayjs(currentWeek.endDate).format('YYYY/MM/DD')
          break;
        case 2:
          obj.startDay = dayjs(date).startOf('month').format('YYYY/MM/DD')
          obj.endDay   = dayjs(date).endOf('month').format('YYYY/MM/DD')
          break;
        default:
          console.warn('[getUsedCarBusinessData] 未知 timeType:', timeType)
      }
      return obj
    },
		initDate(type = 'date') {
      const now = dayjs();
      const setData = (payload) => {
        this.setData(payload)
				this.triggerEvent('search', this.getParams())
      }

      switch (type) {
        case 'date': {
					const yesterday = now.subtract(1, 'day');
          setData({
            date: now.format('YYYY/MM/DD'),
            currentDate: now.valueOf(),
          });
          break;
        }
        case 'year-month': {
          const lastMonth = now.subtract(1, 'month');
          setData({
            date: now.format('YYYY/MM'),
            currentDate: now.valueOf(),
          });
          break;
        }
        case 'week': {
					// const secondWeek = this.data.weekColumns[1];
					const firstWeek = this.data.weekColumns[0]
          if (firstWeek) {
            setData({
              currentWeek: firstWeek,
              date: `${firstWeek.startDate}至${firstWeek.endDate}`,
            });
          }
          break;
        }
        default:
          console.warn('[initDate] 未知 type:', type);
      }
		},
		onDisplayDate() {
      const { timeType, date, currentDate } = this.data
      if (timeType == 'custom') {
        this.setData({
          show: true
        })
        const calendar = this.selectComponent("#calendar")
        if (calendar && calendar.__data__ && calendar.__data__.currentDate) {
          const _calendar = calendar.__data__.currentDate.map(item => dayjs(item).format('YYYY/MM/DD'))
          const _value = date.split('至')
          if (_value[0] != _calendar[0] || _value[1] != _calendar[1]) {
            calendar.reset()
          }
        }
      } else {
        this.setData({
          dateShow: true
        })
        if (timeType == 'date' && currentObj) {
          const c_value = currentObj.getValues()
          const _date = date.split('-')
          if (c_value[0] != _date[0] || c_value[1] != _date[1] || c_value[2] != _date[2]) {
            const picker = this.selectComponent("#datePicker")
            this.setData({
              minDate: dayjs().subtract(1, 'year').valueOf(),
              maxDate: dayjs().valueOf(),
            },
          () => {
            picker.picker.setValues(_date)
          })
          }
        } else if (timeType == 'year-month'&& currentObj) {
          const c_value = currentObj.getValues()
          const _date = date.split('-')
          if (c_value[0] != _date[0] || c_value[1] != _date[1]) {
            const picker = this.selectComponent("#datePicker")
            this.setData({
              minDate: dayjs().subtract(1, 'year').valueOf(),
              maxDate: dayjs().valueOf(),
            },
          () => {
            picker.picker.setValues(_date)
          })
          }
        } else if (timeType == 'week') {
          const { date, weekColumns} = this.data
          const picker = this.selectComponent("#weekPicker")
          const label = date
          const index = weekColumns.findIndex(i => i.label == label)
          setTimeout(() => {
            picker.setColumnIndex(0, index)
          }, 0)
        }
      }
		},
		// 取消
    cancel() {
      this.setData({
        dateShow: false
      })
    },
    // 年月日确认
    confirm() {
      const { selectedDate, timeType, currentWeek, current } = this.data;
      const formatMap = {
        date: () => dayjs(selectedDate).format('YYYY/MM/DD'),
        'year-month': () => dayjs(selectedDate).format('YYYY/MM'),
        week: () => `${currentWeek.startDate}至${currentWeek.endDate}`
      };
      // 边界状态统一计算
      const calcBoundary = () => {
        const { timeType, selectedDate, currentWeek, weekColumns, minDate } = this.data;
        let rightCurrent = false;
        let leftCurrent  = false;

        switch (timeType) {
          case 'date': {
            const today = dayjs().startOf('day');
            const min   = dayjs(minDate).startOf('day');
            const sel   = dayjs(selectedDate).startOf('day');
            rightCurrent = sel.isSame(today, 'day');
            leftCurrent  = sel.isSame(min, 'day');
            break;
          }
          case 'year-month': {
            const current = dayjs().startOf('month');
            const min     = dayjs(minDate).startOf('month');
            const sel     = dayjs(selectedDate);
            rightCurrent = sel.isSame(current, 'month');
            leftCurrent  = sel.isSame(min, 'month');
            break;
          }
          case 'week':
            if (currentWeek.index === 0) rightCurrent = true;
            if (currentWeek.index === weekColumns.length - 1) leftCurrent  = true;
            break;
          default:
            console.warn('[confirm] 未知 timeType:', timeType);
        }

        this.setData({ rightCurrent, leftCurrent });
      };

      calcBoundary();
      this.setData({
        dateShow: false,
        date: (formatMap[timeType] || (() => ''))()
      });
      this.triggerEvent('search', this.getParams())
    },
    onChange(e) {
      currentObj = e.detail
    },
    // 日选择
    onInput(event) {
      // 防止选择之后,取消选择,导致日期不变
      this.setData({
        selectedDate: event.detail
      })
    },
    // 周选择
    onWeekChange(event) {
      const {value} = event.detail
      const currentWeek = value
      this.setData({
        currentWeek,
      })
    },
    // 上一个月
    last() {
      const {timeType, merchantId, date, minDate, current} = this.data
      if (timeType == 'year-month') {
        // 使用 dayjs 处理年月逻辑
        const currentDisplayDate = dayjs(date);
        const prevMonth = currentDisplayDate.subtract(1, 'month');
        const leftCurrent = prevMonth.isSame(dayjs(minDate), 'month');
        this.setData({
          date: prevMonth.format('YYYY/MM'),
          currentDate: prevMonth.valueOf(),
          rightCurrent: false,
          leftCurrent
        });
      } else if (timeType == 'date') {
        // 日选择:使用 dayjs 处理日期减一天
        const currentDisplayDate = dayjs(date);
        const prevDate = currentDisplayDate.subtract(1, 'day');
        const leftCurrent = prevDate.isSame(dayjs(minDate), 'day');
        this.setData({
          date: prevDate.format('YYYY/MM/DD'),
          currentDate: prevDate.valueOf(),
          rightCurrent: false,
          leftCurrent
        });
      } else if (timeType == 'week') {
        const {currentWeek, weekColumns} = this.data;
        if (currentWeek.index > -1) {
          const prevWeek = weekColumns[currentWeek.index + 1];
          const prevDate = dayjs(prevWeek.startDate, 'YYYY/MM/DD');
          this.setData({
            date: `${prevWeek.startDate}至${prevWeek.endDate}`,
            currentDate: prevDate.valueOf(),
            defaultIndex: currentWeek.index + 1,
            currentWeek: prevWeek,
            leftCurrent: prevWeek.index === weekColumns.length - 1,
            rightCurrent: false
          });
        }
      }
      this.triggerEvent('search', this.getParams())
    },
    // 下一个月
    next() {
      const {timeType, merchantId, date, current} = this.data
      if (timeType == 'year-month') {
        // 获取当前显示的日期
        const currentDisplayDate = dayjs(date);
        // 设置为上一个月
        const nextMonth = currentDisplayDate.add(1, 'month');
        const rightCurrent = nextMonth.isSame(dayjs(), 'month');
        this.setData({
          date: nextMonth.format('YYYY/MM'),
          currentDate: nextMonth.valueOf(),
          leftCurrent: false,
          rightCurrent
        });
      } else if (timeType == 'date') {
        // 日选择
        // 获取当前显示的日期
        const currentDisplayDate = dayjs(date, 'YYYY/MM/DD');
        // 设置为下一个月
        const nextDate = currentDisplayDate.add(1, 'day');
        const _date = nextDate.format('YYYY/MM/DD');
        const _currentDate = dayjs().format('YYYY/MM/DD');
        const rightCurrent = _date == _currentDate
        this.setData({
          date: _date,
          currentDate: nextDate.valueOf(),
          rightCurrent,
          leftCurrent: false
        });
      } else if (timeType == 'week') {
        const {currentWeek, weekColumns} = this.data
        if (currentWeek.index < weekColumns.length) {
          const nextWeek = weekColumns[currentWeek.index - 1]
          const nextDate = dayjs(nextWeek.startDate, 'YYYY/MM/DD');
          this.setData({
            date: `${nextWeek.startDate}至${nextWeek.endDate}`,
            currentDate: nextDate.valueOf(),
            defaultIndex: currentWeek.index - 1,
            currentWeek: nextWeek,
            rightCurrent: nextWeek.index == 0,
            leftCurrent: false
          })
        }
      }
      this.triggerEvent('search', this.getParams())
    }
  }
})