dateSearch.vue 14.8 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 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
<template>
  <div class="date-screen-wrapper">
    <div class="date-screen">
      <div
        v-if="showDateTypeFilter"
        class="tab-section"
        :class="{ isSticky }"
        :style="{ background: customBackground }"
      >
        <div
          v-for="item in dateList"
          :key="item.index"
          class="tab"
          :class="{ active: item.index === dateCurrent }"
          @click="selectDate(item.index)"
        >
          {{ item.title }}
        </div>
      </div>
      <div class="date-section">
        <div class="arrow left">
          <van-icon v-if="!leftCurrent" class="arrow-left" name="arrow-left" @click="last" />
        </div>
        <div class="date-text" @click="onDisplayDate">{{ date }}</div>
        <div class="arrow right">
          <van-icon v-if="!rightCurrent" class="arrow-right" name="arrow" @click="next" />
        </div>
      </div>
    </div>

    <!-- 年月日选择弹窗 -->
    <van-popup v-model="dateShow" position="bottom" round @closed="cancel">
      <!-- Date / Year-Month -->
      <van-datetime-picker
        v-if="timeType === 'date' || timeType === 'year-month'"
        v-model="currentDate"
        :type="timeType === 'date' ? 'date' : 'year-month'"
        :title="titleEnum[timeType]"
        :min-date="minDateObj"
        :max-date="maxDateObj"
        @confirm="onDatetimeConfirm"
        @cancel="cancel"
      />
      <!-- 周 -->
      <van-picker
        v-if="timeType === 'week'"
        ref="weekPicker"
        show-toolbar
        :title="titleEnum[timeType]"
        :columns="weekColumns"
        value-key="label"
        :default-index="defaultIndex"
        @confirm="onWeekConfirm"
        @cancel="cancel"
        @change="onWeekChange"
      />
    </van-popup>

    <!-- 日历(如果是自定义日期) -->
    <van-calendar
      v-model="show"
      ref="calendar"
      type="range"
      color="#2C66F7"
      :max-range="31"
      :min-date="minDateObj"
      :max-date="maxDateObj"
      @confirm="onConfirm"
      @close="onClose"
    />
  </div>
</template>

<script>
import dayjs from 'dayjs'
import api from '@/api/baseApi'

let weekColumnsCache = []
let weekColumnsPromise = null

export default {
  name: 'DateSearch',
  props: {
    showDateTypeFilter: { type: Boolean, default: false }, // 是否显示 日/周/月 类型过滤切换
    tabSelected: { type: Number },
    initTimeDimension: { type: Number, default: -1 },
    initStartDate: { type: String, default: '' },
    initEndDate: { type: String, default: '' },
    isSticky: Boolean,
    customBackground: String,
    setTrackData: Boolean
  },
  data() {
    return {
      date: '',
      minDate: dayjs().subtract(3, 'year').valueOf(),
      maxDate: dayjs().valueOf(),
      dateCurrent: 0,
      titleEnum: {
        date: '选择日期',
        week: '选择周',
        'year-month': '选择年月'
      },
      timeType: 'date',
      weekColumns: [],
      dateList: [
        { title: '日', index: 0 },
        { title: '周', index: 1 },
        { title: '月', index: 2 }
      ],
      timeTypeEnum: { 0: 'date', 1: 'week', 2: 'year-month' },
      selectedDate: null,
      currentDate: new Date(),
      currentWeek: null,
      defaultIndex: 0,
      leftCurrent: false,
      rightCurrent: true,
      dateShow: false,
      show: false
    }
  },
  computed: {
    minDateObj() { return new Date(this.minDate) },
    maxDateObj() { return new Date(this.maxDate) }
  },
  watch: {
    tabSelected(n) {
      if (n !== undefined && n !== null && n !== '') {
        const timeTypeEnum = this.timeTypeEnum
        if ([1, 2].includes(n)) {
          this.dateCurrent = n
          this.timeType = timeTypeEnum[n]
          this.rightCurrent = true
          this.leftCurrent = false
          this.initDate(timeTypeEnum[n])
        } else {
          this.dateCurrent = 0
          this.timeType = timeTypeEnum[0]
          this.rightCurrent = true
          this.leftCurrent = false
          this.initDate(timeTypeEnum[0])
        }
      }
    }
  },
  created() {
    this._hasAppliedInit = false
    if (this._hasInitConfig()) {
      const dim = Number(this.initTimeDimension)
      if (dim === 1) {
        this.getWeeklyData().then(() => this._tryApplyInitConfig())
      } else {
        this._tryApplyInitConfig()
        this.getWeeklyData()
      }
    } else {
      this.initDate()
      this.getWeeklyData()
    }
  },
  methods: {
    async getWeeklyData() {
      if (weekColumnsCache.length) {
        this.weekColumns = weekColumnsCache
        return
      }
      if (!weekColumnsPromise) {
        weekColumnsPromise = api.getWeekSelectData().then((result) => {
          const cols = result?.map((item, index) => ({
            label: `${dayjs(item.startDate).format('YYYY/MM/DD')}-${dayjs(item.endDate).format('YYYY/MM/DD')}`,
            startDate: dayjs(item.startDate).format('YYYY/MM/DD'),
            endDate: dayjs(item.endDate).format('YYYY/MM/DD'),
            index
          })) || []
          weekColumnsCache = cols
          return cols
        }).catch(() => []).finally(() => weekColumnsPromise = null)
      }
      this.weekColumns = await weekColumnsPromise
    },
    selectDate(index) {
      this.dateCurrent = index
      this.timeType = this.timeTypeEnum[index]
      this.rightCurrent = true
      this.leftCurrent = false
      this.initDate(this.timeType)
    },
    getParams() {
      const { dateCurrent, date, currentWeek } = this
      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
      }
      obj.timeDimension = dateCurrent
      return obj
    },
    initLoad() {
      this.dateCurrent = 0
      this.leftCurrent = false
      this.rightCurrent = true
      this.initDate('date')
    },
    initDate(type = 'date') {
      const now = dayjs()
      const setData = (payload) => {
        Object.assign(this, payload)
        this.$emit('search', this.getParams())
      }
      if (type === 'date') {
        setData({ date: now.format('YYYY/MM/DD'), currentDate: now.toDate() })
      } else if (type === 'year-month') {
        setData({ date: now.format('YYYY/MM'), currentDate: now.toDate() })
      } else if (type === 'week') {
        const firstWeek = this.weekColumns[0]
        if (firstWeek) {
          setData({ currentWeek: firstWeek, date: `${firstWeek.startDate}-${firstWeek.endDate}`, defaultIndex: firstWeek.index })
        }
      }
    },
    _hasInitConfig() {
      return [0, 1, 2].includes(Number(this.initTimeDimension))
    },
    _normalizeDateStr(input) {
      if (!input) return ''
      const str = String(input).trim().split(' ')[0]
      const d = dayjs(str.replace(/-/g, '/'))
      return d.isValid() ? d.format('YYYY/MM/DD') : ''
    },
    _tryApplyInitConfig() {
      if (this._hasAppliedInit) return
      const dim = Number(this.initTimeDimension)
      if (![0, 1, 2].includes(dim)) return

      const start = this._normalizeDateStr(this.initStartDate)
      const end = this._normalizeDateStr(this.initEndDate)
      if (dim === 1 && !this.weekColumns.length) return

      const nextData = { dateCurrent: dim, timeType: this.timeTypeEnum[dim] || 'date' }
      if (dim === 0) {
        const base = start || end
        const d = base ? dayjs(base) : dayjs()
        nextData.date = d.format('YYYY/MM/DD')
        nextData.currentDate = d.toDate()
        nextData.rightCurrent = d.startOf('day').isSame(dayjs().startOf('day'))
        nextData.leftCurrent = d.startOf('day').isSame(dayjs(this.minDate).startOf('day'))
      } else if (dim === 2) {
        const base = start || end
        const d = base ? dayjs(base) : dayjs()
        nextData.date = d.format('YYYY/MM')
        nextData.currentDate = d.toDate()
        nextData.rightCurrent = d.startOf('month').isSame(dayjs().startOf('month'))
        nextData.leftCurrent = d.startOf('month').isSame(dayjs(this.minDate).startOf('month'))
      } else if (dim === 1) {
        const target = this.weekColumns.find(i => i.startDate === start && i.endDate === end) || this.weekColumns[0]
        if (target) {
          nextData.currentWeek = target
          nextData.date = `${target.startDate}-${target.endDate}`
          nextData.defaultIndex = target.index
          nextData.rightCurrent = target.index === 0
          nextData.leftCurrent = target.index === this.weekColumns.length - 1
        }
      }
      this._hasAppliedInit = true
      Object.assign(this, nextData)
      this.$emit('search', this.getParams())
    },
    onDisplayDate() {
      if (this.timeType === 'custom') {
        this.show = true
        this.$emit('popupvisible', { visible: true })
      } else {
        this.dateShow = true
        this.$emit('popupvisible', { visible: true })
        this.$nextTick(() => {
          if (this.timeType === 'week') {
            const index = this.weekColumns.findIndex(i => i.label === this.date)
            this.defaultIndex = Math.max(0, index)
            if (this.$refs.weekPicker) this.$refs.weekPicker.setColumnIndex(0, this.defaultIndex)
          } else {
            this.currentDate = dayjs(this.date.replace(/-/g, '/')).toDate()
          }
        })
      }
    },
    cancel() {
      this.dateShow = false
      this.$emit('popupvisible', { visible: false })
    },
    onDatetimeConfirm(value) {
      this.selectedDate = value
      this.handleConfirm()
    },
    onWeekConfirm(value) {
      this.currentWeek = value
      this.handleConfirm()
    },
    onWeekChange(picker, value, index) {
      // nothing needed for change unless we want to track it
    },
    handleConfirm() {
      const { timeType, selectedDate, currentWeek } = this
      let rightCurrent = false; let leftCurrent = false
      if (timeType === 'date') {
        const sel = dayjs(selectedDate).startOf('day')
        rightCurrent = sel.isSame(dayjs().startOf('day'), 'day')
        leftCurrent = sel.isSame(dayjs(this.minDate).startOf('day'), 'day')
        this.date = dayjs(selectedDate).format('YYYY/MM/DD')
      } else if (timeType === 'year-month') {
        const sel = dayjs(selectedDate)
        rightCurrent = sel.isSame(dayjs().startOf('month'), 'month')
        leftCurrent = sel.isSame(dayjs(this.minDate).startOf('month'), 'month')
        this.date = dayjs(selectedDate).format('YYYY/MM')
      } else if (timeType === 'week') {
        rightCurrent = currentWeek.index === 0
        leftCurrent = currentWeek.index === this.weekColumns.length - 1
        this.date = `${currentWeek.startDate}-${currentWeek.endDate}`
      }
      this.rightCurrent = rightCurrent
      this.leftCurrent = leftCurrent
      this.dateShow = false
      this.currentDate = timeType === 'week' ? null : selectedDate
      this.$emit('popupvisible', { visible: false })
      this.$emit('search', this.getParams())
    },
    onConfirm(dateRange) {
      const [start, end] = dateRange
      this.show = false
      this.date = `${dayjs(start).format('YYYY/MM/DD')} - ${dayjs(end).format('YYYY/MM/DD')}`
      this.$emit('popupvisible', { visible: false })
    },
    onClose() {
      this.show = false
      this.$emit('popupvisible', { visible: false })
    },
    last() {
      if (this.timeType === 'year-month') {
        const prevMonth = dayjs(this.date, 'YYYY/MM').subtract(1, 'month')
        this.date = prevMonth.format('YYYY/MM')
        this.currentDate = prevMonth.toDate()
        this.rightCurrent = false
        this.leftCurrent = prevMonth.isSame(dayjs(this.minDate), 'month')
      } else if (this.timeType === 'date') {
        const prevDate = dayjs(this.date, 'YYYY/MM/DD').subtract(1, 'day')
        this.date = prevDate.format('YYYY/MM/DD')
        this.currentDate = prevDate.toDate()
        this.rightCurrent = false
        this.leftCurrent = prevDate.isSame(dayjs(this.minDate), 'day')
      } else if (this.timeType === 'week') {
        if (this.currentWeek.index < this.weekColumns.length - 1) {
          const prevWeek = this.weekColumns[this.currentWeek.index + 1]
          this.date = `${prevWeek.startDate}-${prevWeek.endDate}`
          this.currentDate = dayjs(prevWeek.startDate, 'YYYY/MM/DD').toDate()
          this.defaultIndex = prevWeek.index
          this.currentWeek = prevWeek
          this.leftCurrent = prevWeek.index === this.weekColumns.length - 1
          this.rightCurrent = false
        }
      }
      this.$emit('search', this.getParams())
    },
    next() {
      if (this.timeType === 'year-month') {
        const nextMonth = dayjs(this.date, 'YYYY/MM').add(1, 'month')
        this.date = nextMonth.format('YYYY/MM')
        this.currentDate = nextMonth.toDate()
        this.leftCurrent = false
        this.rightCurrent = nextMonth.isSame(dayjs(), 'month')
      } else if (this.timeType === 'date') {
        const nextDate = dayjs(this.date, 'YYYY/MM/DD').add(1, 'day')
        this.date = nextDate.format('YYYY/MM/DD')
        this.currentDate = nextDate.toDate()
        this.rightCurrent = nextDate.isSame(dayjs(), 'day')
        this.leftCurrent = false
      } else if (this.timeType === 'week') {
        if (this.currentWeek.index > 0) {
          const nextWeek = this.weekColumns[this.currentWeek.index - 1]
          this.date = `${nextWeek.startDate}-${nextWeek.endDate}`
          this.currentDate = dayjs(nextWeek.startDate, 'YYYY/MM/DD').toDate()
          this.defaultIndex = nextWeek.index
          this.currentWeek = nextWeek
          this.rightCurrent = nextWeek.index === 0
          this.leftCurrent = false
        }
      }
      this.$emit('search', this.getParams())
    }
  }
}
</script>

<style lang="scss" scoped>
.date-screen {
  display: flex;
  align-items: center;
  justify-content: center;

  .tab-section {
    box-sizing: border-box;
    width: 139px;
    height: 28px;
    display: flex;
    align-items: center;
    background: #FFFFFF;
    border-radius: 28px;
    font-size: 13px;
    color: #999999;
    padding: 2px;

    &.isSticky {
      background: #F7F8FA;
    }

    .tab {
      flex: 1;
      text-align: center;
      height: 24px;
      line-height: 24px;
      border-radius: 24px;

      &.active {
        color: #2C66F7;
        font-weight: 500;
        background: #2c66f71a;
      }
    }
  }

  .date-section {
    box-sizing: border-box;
    height: 28px;
    flex: 1;
    // max-width: calc(100% - 139px);
    display: flex;
    align-items: center;
    justify-content: space-between;

    .date-text {
      font-family: 'numberNor';
      font-size: 13px;
      text-align: center;
      width: 160px;
      flex-shrink: 0;
    }

    .arrow {
      width: 16px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>