DatePicker.nvue 14.2 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 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
<template>
  <view class="d_select" v-if="isHome">
    <!--  首页样式 -->
    <view class="d_select_display">
      <uv-icon name="clock" size="24rpx" class="d_select_display_time_icon" v-if="showIcon" color="#202328"></uv-icon>
      <text class="d_select_display_text" :style="{color:'#202328'}"
        @tap="handleTapDisplayText">{{timeVal.displayValue}}</text>
      <uv-icon v-if="showArrowIcon" name="arrow-down-fill" size="12rpx" style="margin-left: 8rpx;"
        :color="typeColor?typeColor:'#202328'"></uv-icon>
      <!-- <image src="/static/tabbar/arrow-down.png" v-if="showArrowIcon" class="d_select_display_icon" mode=""></image> -->
    </view>
    <view class="d_select_type" @tap="handleSelectType"
      :style="{'background-color': typeBgColor?typeBgColor:'#387CF5'}">
      <image src="@/static/tabbar/date.png" class="d_select_type_icon" mode=""></image>
      <text class="d_select_type_text">{{ t(selectText) }}</text>
    </view>
  </view>
  <!-- 非首页样式 -->
  <view class="no-home-select" v-else>
    <view class="picker_type" @tap="handleSelectType">
      <image src="@/static/tabbar/date-b.png" class="d_select_type_icon" mode=""></image>
      <text class="picker_type_text">{{ t(selectText) }}</text>
    </view>
    <view class="split-line"></view>
    <view class="picker_date" :class="{'picker_date_filter':!slots.filter}">
      <text class="picker_date_text" v-if="slots.filter" @tap="handleTapDisplayText">{{timeVal.range.join(t('maintenance.common.splitDate'))}}</text>
      <view v-else class="picker_date_detail" @tap="handleTapDisplayText">
        <uv-icon name="clock" size="24rpx" color="#202328"></uv-icon>
        <view class="c-date">
          <text class="c-date_text">{{timeVal.range?.[0]}}</text>
        </view>
        <text class="c-date_text">{{ t('maintenance.common.splitDate') }}</text>
        <view class="c-date">
          <text class="c-date_text">{{timeVal.range?.[1]}}</text>
        </view>
      </view>
      <!-- 			<uv-icon v-if="showArrowIcon" name="arrow-down-fill" size="12rpx" style="margin-left: 8rpx;"
				:color="typeColor?typeColor:'#202328'"></uv-icon> -->
      <!-- <image src="/static/tabbar/arrow-down.png" v-if="showArrowIcon" class="d_select_display_icon" mode=""></image> -->
    </view>
    <slot name="filter" v-if="slots.filter"></slot>
  </view>
  <DatePicker
    :type="selectType"
    ref="datePickerRef"
    :is-monday="true"
    @change="(val)=>handlePickerChange(val)"
    @modalChange="handleModalChange"
   />
  <uv-popup ref="typePopRef"  @change="handleModalChange">
    <view class="pop_header" @touchmove.stop.prevent>
      <view style="width: 22px;"></view>
      <text class="pop_header_text">{{ t('app.title.timeSelect') }}</text>
      <uv-icon name="close" size="22" class="pop_header_icon" @tap="handleCloseTypeSelect"></uv-icon>
    </view>
    <view class="l_type" @touchmove.stop.prevent>
      <view class="l_type_item" v-for="item in selectList" :key="item.value"
        :class="{'l_type_item_active':item.value === checkedType}" @tap="handleChangeCheckType(item)">
        <text class="l_type_item_text"
          :class="{'l_type_item_active_text':item.value === checkedType}">{{ t(item.label) }}</text>
      </view>
    </view>
    <view class="uni-date-changed uni-date-btn--ok" @touchmove.stop.prevent>
      <view class="uni-datetime-picker--btn" @tap="handleConfirmSelectType">
        <text class="confirm-btn">{{ t('message.confirm') }}</text>
      </view>
    </view>
  </uv-popup>
</template>

<script setup>
  import {
    computed,
    onMounted,
    ref,
    useSlots,
    watch,
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import time from '@/static/tabbar/time.png'
  import DatePicker from '@/uni_modules/zxz-uni-datetime-picker/components/zxz-uni-datetime-picker/zxz-uni-datetime-picker.vue'
  import {
    timeFormat
  } from '@/uni_modules/uv-ui-tools/libs/function/index.js';
  import {
    t, initI18n
  } from '@/plugins/index.js'
  
  onLoad(()=>{
    initI18n()
  })

  const slots = useSlots()
  const props = defineProps({
    showIcon: {
      type: Boolean,
      default: false
    },
    isHome: {
      type: Boolean,
      default: false
    },
    typeBgColor: {
      type: String,
      default: '#387CF5'
    },
    typeColor: {
      type: String,
      default: '#202328'
    },
    hasToday: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'last7days'
      // default: 'yearMonth',
    }
  })

  // 返回的数据
  const emit = defineEmits(['change','modalChange'])
  const handleModalChange = (e) => {
    console.log(e);
    emit('modalChange',e.show)
  }
  const emitData = (type = "reload") => {
    // 下面的几种情况是hour
    // 1、type: yesterday
    // 2、type: day
    // 3、type: daterange 并且开始时间等于结束时间

    // 下面是month的情况
    // 1. type: year

    let unit = 'day'
    const unitType = timeVal.value.type
    if (unitType === 'year') {
      unit = 'month'
    } else if (unitType === 'day' || unitType === 'yesterday' || (unitType === 'dayrange' && timeVal.value
        .startDate === timeVal
        .value.endDate)) {
      unit = 'hour'
    }

    emit('change', {
      ...timeVal.value,
      unit
    }, type)
  }

  // 默认值
  const timeVal = ref({
    type: props.type,
    displayValue: '',
    range: []
  })

watch(() => props.type, (newVal) => {
    console.log('监听---type', newVal);
    
    selectType.value = newVal
    const item = selectList.find(item => item.value === newVal)
    timeVal.value.type = newVal
    selectText.value = item?.label
  })

  // 默认值
  // const selectText = ref('自然月')
  const selectText = ref('iPage.nearly7')
  // 页面加载前传递默认数据
  onLoad(() => {
    const timeStamp = Date.now()
    // checkedType.value = 'last7days'
    timeVal.value = getNoSelectText()

    // timeVal.value = getDefaultDateRange()
    // 设置默认


    emitData('init')
    // selectText.value = '自然月'
    const selectText = ref('iPage.nearly7')

    // 没有选中日历时,恢复当前选中
    uni.$on('no-check-calendar', () => {
      selectType.value = timeVal.value.type
    })
  })

  // 初始化默认值,默认当月,当为1号的时候选上月,当为其他天,选从1号到前一天
  function getDefaultDateRange() {
    const now = new Date();
    const isFirstDay = now.getDate() === 1;

    let startDate, endDate;

    if (isFirstDay) {
      // 如果是1号,获取上个月的第一天和最后一天
      startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      endDate = new Date(now.getFullYear(), now.getMonth(), 0);
    } else {
      // 如果是其他日期,获取当月第一天和前一天
      startDate = new Date(now.getFullYear(), now.getMonth(), 1);
      endDate = new Date(now);
      endDate.setDate(now.getDate() - 1);
    }

    // 日期格式化函数
    const format = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    const startStr = format(startDate);
    const endStr = format(endDate);

    return {
      type: props.type,
      displayValue: `${startStr} ${t('maintenance.common.splitDate')} ${endStr}`,
      range: [startStr, endStr]
    };
  }
  // 是否显示箭头图标(是否可选)
  const showArrowIcon = computed(() => {
    return datePickerPopTypeList.includes(timeVal.value.type)
  })
  // 需要打开二级弹窗的类型
  const datePickerPopTypeList = ['date', 'week', 'yearMonth', 'year', 'daterange']

  // 一级弹窗
  const typePopRef = ref(null)
  const handleSelectType = () => {
    checkedType.value = timeVal.value.type
    typePopRef.value?.open('bottom')
  }
  const handleCloseTypeSelect = () => {
    typePopRef.value?.close()
  }
  const handleTapDisplayText = () => {
    if (!showArrowIcon.value) {
      return
    }
    datePickerRef.value?.show()
  }

  // 二级弹窗
  const datePickerRef = ref(null)
  const handlePickerChange = (e) => {
    // 如果当天在月、年的range之中,拦截掉 hasToday
    const timestamp = props.hasToday ? Date.now() : Date.now() - 24 * 60 * 60 * 1000
    const dayStr = timeFormat(timestamp, 'yyyy-mm-dd')
    if (['yearMonth', 'year'].includes(e.type)) {
      if (dayStr >= e.range[0] && dayStr <= e.range[1]) {
        e.range = [e.range[0], dayStr]
      }
    }

    const item = selectList.find(item => item.value === e.type)
    timeVal.value = e
    selectText.value = item?.label
    // 通知父组件
    emitData()
    datePickerRef.value?.close()
  }


  const handleConfirmSelectType = () => {
    // 需要打开二级弹窗的类型
    if (datePickerPopTypeList.includes(checkedType.value)) {
      // 关闭一级
      typePopRef.value?.close()
      // 打开二级
      selectType.value = checkedType.value
      console.log(selectType.value, '===');
      datePickerRef.value?.show()
      return
    }
    

    // 更新timeVal并触发数据变化
    timeVal.value = getNoSelectText(checkedType.value);

    // 通知父组件并关闭弹窗
    emitData();
    typePopRef.value?.close();
  }




  // 昨日,今日,近7天,近30天,自然日,自然周,自然月,自然年,自定义
  const selectType = ref(props.type)
  const checkedType = ref(props.type)
  const handleChangeCheckType = (item) => {
    checkedType.value = item.value
  }
  const selectList = [{
    'label': 'DateType.yesterday',
    value: 'yesterday'
  }, {
    'label': 'iPage.nearly7',
    value: 'last7days'
  }, {
    'label': 'iPage.nearly30',
    value: 'last30days'
  }, {
    'label': 'iPage.naturalDay',
    value: 'date'
  }, {
    'label': 'iPage.naturalWeek',
    value: 'week'
  }, {
    'label': 'iPage.naturalMonth',
    value: 'yearMonth'
  }, {
    'label': 'iPage.naturalYear',
    value: 'year'
  }, {
    'label': 'maintenance.monitor.agent.custom',
    value: 'daterange'
  }]

  function getNoSelectText(type = 'last7days') {
    let start, end;
    const today = new Date();
    const formatDate = (date) => timeFormat(date, 'yyyy-mm-dd');
    const yesterday = new Date(today);
    yesterday.setDate(props.hasToday ? today.getDate() : (today.getDate() - 1));

    const trueYesterday = new Date(today);
    trueYesterday.setDate(today.getDate() - 1);

    // switch (checkedType.value) {
    switch (type) {
      case 'yesterday':
        start = formatDate(trueYesterday);
        end = start;
        selectText.value = 'DateType.yesterday';
        break;
      case 'last7days':
        const last7Days = new Date(yesterday);
        last7Days.setDate(yesterday.getDate() - 6);
        start = formatDate(last7Days);
        end = formatDate(yesterday);
        selectText.value = 'iPage.nearly7';
        break;
      case 'last30days':
        const last30Days = new Date(yesterday);
        last30Days.setDate(yesterday.getDate() - 30);
        start = formatDate(last30Days);
        end = formatDate(yesterday);
        selectText.value = 'iPage.nearly30';

        break;
    }
    return {
      // type: checkedType.value,
      type,
      // displayValue: checkedType.value === 'yesterday' ? `${start}` : `${start} 至 ${end}`,
      displayValue: type === 'yesterday' ? `${start}` : `${start} 至 ${end}`,
      range: [start, end]
    }
  }

// 暴露方法给父组件使用
defineExpose({
  handleSelectType,
  setDateType: (type, date) => {
    // 设置日期类型
    checkedType.value = type;
    selectType.value = type;
    
    // 如果是date类型且有日期参数,设置日期
    if (type === 'date' && date) {
      timeVal.value = {
        type: 'date',
        displayValue: date,
        range: [date, date]
      };
      selectText.value = 'iPage.naturalDay';
      emitData();
    }
    
    // 打开日期选择器
    if (datePickerPopTypeList.includes(type)) {
      // datePickerRef.value?.show();
    }
  }
});
</script>

<style lang="scss" scoped>
  @import '@/styles/normal.scss';

  .d_select {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    &_display {
      display: flex;
      flex-direction: row;
      align-items: center;

      &_icon {
        width: 14rpx;
        height: 14rpx;
        margin-left: 5rpx;
      }

      &_time_icon {
        width: 28rpx;
        margin-right: 10rpx;
      }

      &_text {
        font-weight: 400;
        font-size: 26rpx;
        color: #202328;
      }
    }


    &_type {
      width: 148rpx;
      height: 50rpx;
      border-radius: 25rpx;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;

      &_icon {
        width: 32rpx;
        height: 32rpx;
        margin-right: 8rpx;
      }

      &_text {
        line-height: 50rpx;
        color: #fff;
        font-size: 24rpx;
      }
    }
  }

  .no-home-select {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    border-radius: 12rpx;
    .split-line{
      width: 2rpx;
      height: 24rpx;
      margin: 0 16rpx;
      background-color: #e1e4ea;
    }

    .picker_type {
      padding-left: 10rpx;
      height: 60rpx;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      // background-color: #FFFFFF;

      &_text {
        color: #202328;
        font-size: 26rpx;
      }
    }

    .picker_date {
      flex: 1;
      height: 60rpx;
      min-width: 0;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;


      &_text {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        color: #202328;
        font-size: 26rpx;
      }
    }
  }

  .no-home-select .picker_date_filter {
    justify-content: flex-start;

    .picker_date_detail {
      flex: 1;
      height: 100%;
      display: flex;
      flex-direction: row;
      align-items: center;

      .c-date {
        flex: 1;
        // width: 200px;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .c-date_text {
        white-space: nowrap;
        font-size: 26rpx;
        color: #202328;
      }
    }
  }
</style>