xunji-rili.vue 18 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 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
<template>
  <view class="calendar-page">
    <!-- 顶部操作栏 -->
    <view class="top-bar">
      <!-- 年月选择胶囊 -->
      <picker mode="date" fields="month" :value="currentMonth" @change="onMonthChange">
        <view class="month-picker-pill">
          <text class="month-text">{{ displayMonthText }}</text>
          <up-icon name="arrow-down-fill" color="#333333" size="10"></up-icon>
        </view>
      </picker>

      <!-- 说明按钮 -->
      <view class="action-buttons">
        <up-button text="说明" type="info" plain shape="circle" size="mini"
          customStyle="padding: 0 24rpx; height: 56rpx; font-size: 24rpx; border-color: #dcdfe6; color: #606266;"
          @click="showExplainPopup = true" />
      </view>
    </view>

    <!-- 日历卡片容器 -->
    <view class="calendar-card">
      <!-- 星期表头 -->
      <view class="week-header">
        <text v-for="(day, index) in weekDays" :key="index" class="week-day">
          {{ day }}
        </text>
      </view>

      <!-- 日期网格 (动态 5行 或 6行) -->

      <scroll-view class="scroll-view" scroll-y>
        <view class="date-grid">
          <view v-for="(date, index) in dates" :key="index" class="date-cell" :class="{

            'has-data': date.planList.length || date.noteList.length || (date.weight && date.weight > 0)
          }" :style="{ backgroundColor: getCellBgColor(date) }" @tap="selectDate(date)">
            <!-- 日期数字 / 今日徽章 -->
            <view class="date-header">
              <text v-if="date.today" class="today-badge">今</text>
              <text v-else class="date-number">
                {{ date.day }}
              </text>
            </view>

            <!-- 计划/容量数据列表 -->
            <view class="plan-list"
              v-if="date.planList.length || date.noteList.length || (date.weight && date.weight > 0)">
              <template v-for="(item, idx) in getCellVisibleItems(date).items" :key="idx">
                <view class="plan-tag" :class="`tag-type-${item.type}`"
                  :style="item.bg ? { backgroundColor: item.bg } : {}">
                  <text class="tag-text">{{ item.text }}</text>
                </view>
              </template>
              <!-- 溢出剩余条数 -->
              <view v-if="getCellVisibleItems(date).remaining > 0" class="plan-extra">
                +{{ getCellVisibleItems(date).remaining }}
              </view>
            </view>
          </view>
        </view>
      </scroll-view>



    </view>

    <!-- 单元格详情弹窗 -->
    <GridCellContentPopup ref="gridPopupRef" :date="selectedDate" @refreshCalendar="handleRefreshCalendar" />

    <!-- 日历图标说明弹窗 -->
    <up-popup :show="showExplainPopup" mode="bottom" round="24rpx" :safeAreaInsetBottom="true"
      @close="showExplainPopup = false">
      <view class="explain-popup-content">
        <view class="explain-header">
          <text class="explain-title">日历图标说明</text>
          <up-icon name="close" color="#909399" size="18" @click="showExplainPopup = false" />
        </view>

        <view class="explain-list">
          <view class="explain-item">
            <view class="explain-item-left">
              <view class="color-block yellow">
                
              </view>
              <view class="item-info">
                <text class="item-label">已完成</text>
                <text class="item-desc">已完成或已结课的训练记录</text>
              </view>
            </view>
          </view>

          <view class="explain-item">
            <view class="explain-item-left">
              <view class="color-block gray">
              
              </view>
              <view class="item-info">
                <text class="item-label">待训练</text>
                <text class="item-desc">已安排的待训练计划</text>
              </view>
            </view>
          </view>

          <view class="explain-item">
            <view class="explain-item-left">
              <view class="color-block green">
               
              </view>
              <view class="item-info">
                <text class="item-label">训练容量</text>
                <text class="item-desc">力量训练累计产生的总负重</text>
              </view>
            </view>
          </view>

          <view class="explain-item">
            <view class="explain-item-left">
              <view class="color-block blue">
               
              </view>
              <view class="item-info">
                <text class="item-label">日程备注</text>
                <text class="item-desc">相关日期的备注标记</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, watch, computed, nextTick, onMounted, onBeforeUnmount } from 'vue';
import dayjs from 'dayjs';
import DailyTemplateApi from '@/sheep/api/calendar/date';
import GridCellContentPopup from '@/pages/xunji/components/rili-components/grid-cell-content-popup.vue';

// 常量定义
const MAX_CELL_LINES = 3;
const weekDays = ref(['一', '二', '三', '四', '五', '六', '日']);

// 响应式状态
const dates = ref([]);
const showExplainPopup = ref(false);
const selectedDate = ref('');
const gridPopupRef = ref(null);

const currentMonth = ref(dayjs().format('YYYY-MM-DD'));

// 顶部年月显示
const displayMonthText = computed(() => {
  return dayjs(currentMonth.value).format('YYYY年M月');
});

// 年月 Picker 触发
const onMonthChange = (e) => {
  if (e.detail && e.detail.value) {
    currentMonth.value = dayjs(e.detail.value).startOf('month').format('YYYY-MM-DD');
  }
};

// ====== 计算每个日期格子的背景颜色 ======
const getCellBgColor = (date) => {


  // 2. 如果存在训练计划/备注/重量,优先采用训练本身的背景色
  if (date.planList && date.planList.length > 0 && date.planList[0].bg) {
    return date.planList[0].bg;
  }
  if (date.noteList && date.noteList.length > 0 && date.noteList[0].backgroundColor) {
    return date.noteList[0].backgroundColor;
  }

  // 3. 有容量负重但无特定背景色:赋予柔和浅绿
  if (date.weight && date.weight > 0) {
    return '#f0fdf4';
  }

  // 4. 有计划但未指定背景色:赋予柔和浅黄
  if (date.planList && date.planList.length > 0) {
    return '#fefce8';
  }



  // 6. 普通无训练的本月休息日:基础卡片白色/浅灰
  return '#ededed';
};


const generateCalendar = (monthStr) => {
  const current = dayjs(monthStr);
  const startOfMonth = current.startOf('month');
  const daysInMonth = current.daysInMonth();

  const dayOfWeek = startOfMonth.day(); // 0 表示周日
  const startOffset = dayOfWeek === 0 ? 6 : dayOfWeek - 1;

  // 动态计算总单元格:35(5行)或 42(6行)
  const totalCellsNeeded = startOffset + daysInMonth;
  const totalGridSize = totalCellsNeeded > 35 ? 42 : 35;

  const gridStartDate = startOfMonth.subtract(startOffset, 'day');
  const todayStr = dayjs().format('YYYY-MM-DD');

  const calendarDates = [];
  for (let i = 0; i < totalGridSize; i++) {
    const cellDate = gridStartDate.add(i, 'day');
    const dateKey = cellDate.format('YYYY-MM-DD');

    calendarDates.push({
      day: cellDate.date(),
      today: dateKey === todayStr,
      isCurrentMonth: cellDate.month() === current.month(),
      dateKey,
    });
  }

  return calendarDates;
};

// ====== 加载计划数据 ======
const loadPlans = async (monthStr) => {
  try {
    const curr = dayjs(monthStr);
    const prev = curr.subtract(1, 'month');
    const next = curr.add(1, 'month');

    // 并行请求 3 个月数据
    const [prevRes, currRes, nextRes] = await Promise.all([
      DailyTemplateApi.getCalendarPlans(prev.year(), prev.month() + 1).catch(() => ({ data: [] })),
      DailyTemplateApi.getCalendarPlans(curr.year(), curr.month() + 1).catch(() => ({ data: [] })),
      DailyTemplateApi.getCalendarPlans(next.year(), next.month() + 1).catch(() => ({ data: [] })),
    ]);

    const allPlans = [
      ...(prevRes.data || []),
      ...(currRes.data || []),
      ...(nextRes.data || []),
    ];

    const planMap = {};
    const noteMap = {};
    const weightMap = {};

    allPlans.forEach((plan) => {
      let dateStr = null;
      if (Array.isArray(plan.trainDate)) {
        const [y, m, d] = plan.trainDate;
        dateStr = dayjs(`${y}-${m}-${d}`).format('YYYY-MM-DD');
      } else if (typeof plan.trainDate === 'string') {
        dateStr = dayjs(plan.trainDate).format('YYYY-MM-DD');
      }

      if (!dateStr || dateStr === 'Invalid Date') return;

      // 备注处理
      if (Array.isArray(plan.notes) && plan.notes.length > 0) {
        noteMap[dateStr] = plan.notes.map((note) => ({
          content: note.content || '',
          backgroundColor: note.backgroundColor || '#e2e8f0',
        }));
      }

      // 训练计划与容量处理
      planMap[dateStr] = planMap[dateStr] || [];
      if (Array.isArray(plan.templates)) {
        let totalWeightForDay = 0;
        // 按 sourceType + sourceName 分组
        const sourceMap = new Map();
        plan.templates.forEach((template) => {
          if (!template) return;
          const sourceKey = template.sourceType
            ? `src_${template.sourceType}_${template.sourceName || ''}`
            : `tpl_${template.dailyTemplateId}`;
          if (!sourceMap.has(sourceKey)) {
            sourceMap.set(sourceKey, {
              name: template.sourceName || template.name,
              bg: template.backgroundColor || '#fef08a',
              sourceType: template.sourceType || 4,
              sourceName: template.sourceName || template.name,
              dailyTemplateId: template.dailyTemplateId,
              totalWeight: 0,
            });
          }
          const group = sourceMap.get(sourceKey);
          if (template && typeof template.totalWeight === 'number') {
            group.totalWeight += template.totalWeight;
            totalWeightForDay += template.totalWeight;
          }
        });
        sourceMap.forEach((group) => {
          planMap[dateStr].push(group);
        });
        if (totalWeightForDay > 0) {
          weightMap[dateStr] = totalWeightForDay;
        }
      }
    });

    dates.value = generateCalendar(monthStr).map((date) => ({
      ...date,
      planList: planMap[date.dateKey] || [],
      noteList: noteMap[date.dateKey] || [],
      weight: weightMap[date.dateKey] || null,
    }));
  } catch (err) {
    console.error('加载日历数据失败:', err);
    dates.value = generateCalendar(monthStr);
  }
};

// ====== 视图格子显示控制 ======
const getCellVisibleItems = (date) => {
  const items = [];
  let remaining = 0;

  if (date.weight && date.weight > 0) {
    items.push({ type: 'weight', text: `${date.weight}kg` });
  }

  for (const plan of date.planList) {
    if (items.length < MAX_CELL_LINES) {
      items.push({ type: 'plan', text: plan.name, bg: plan.bg });
    } else {
      remaining++;
    }
  }

  for (const note of date.noteList) {
    if (items.length < MAX_CELL_LINES) {
      items.push({ type: 'note', text: note.content, bg: note.backgroundColor });
    } else {
      remaining++;
    }
  }

  return { items, remaining };
};

const handleRefreshCalendar = () => {
  loadPlans(currentMonth.value);
};

// 监听来自 xunji-moban-xiangqing 模板添加成功的刷新事件
onMounted(() => {
  uni.$on('calendarDataRefresh', handleRefreshCalendar);
});
onBeforeUnmount(() => {
  uni.$off('calendarDataRefresh', handleRefreshCalendar);
});

watch(
  currentMonth,
  (newVal) => {
    if (newVal) {
      loadPlans(newVal);
    }
  },
  { immediate: true }
);

const selectDate = async (date) => {
  selectedDate.value = date.dateKey;
  await nextTick();
  gridPopupRef.value?.openPopup();
};
</script>

<style lang="scss" scoped>
.calendar-page {
  height: 100%;
  padding: 30rpx 15rpx 20rpx;
  background-color: #fff;
  box-sizing: border-box;

  .top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;

    .month-picker-pill {
      display: flex;
      align-items: center;
      gap: 12rpx;
      background-color: #ececec;
      padding: 12rpx 28rpx;
      border-radius: 40rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
      border: 1rpx solid #fff;

      .month-text {
        font-size: 30rpx;
        font-weight: 600;
        color: #1a1a1a;
      }
    }

    .action-buttons {
      display: flex;
      align-items: center;
    }
  }

  .calendar-card {
    background-color: #ffffff;
    border-radius: 24rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.03);

    .week-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;

      .week-day {
        flex: 1;
        text-align: center;
        font-size: 26rpx;
        font-weight: 550;

      }
    }

    .scroll-view {
      height: 100%;

      .date-grid {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: 10rpx;
        // #ifdef MP-WEIXIN
        padding-bottom: 100rpx;
        // #endif
        /* 日期格子基础样式:保证每个格子都有独立背景与微细边框 */
        .date-cell {
          min-width: 0;
          overflow: hidden;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: flex-start;
          border-radius: 12rpx;
          height: 200rpx;
          padding: 8rpx 4rpx;
          box-sizing: border-box;
          transition: all 0.2s ease;

          &:active {
            filter: brightness(0.96);
          }

          &.other-month {
            opacity: 0.5;
            border-color: #f9fafc;
          }

          &.is-today {
            border: 2rpx solid #3b82f6;
          }

          &.has-data {
            box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.02);
          }

          .date-header {
            height: 36rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 6rpx;

            .date-number {
              font-size: 26rpx;
              font-weight: 600;
              color: #1f2937;


            }

            .today-badge {

              font-weight: 600;

            }
          }

          .plan-list {
            width: 100%;
            display: flex;
            flex-direction: column;
            gap: 6rpx;

            .plan-tag {
              width: 100%;
              border-radius: 6rpx;
              padding: 2rpx 4rpx;
              box-sizing: border-box;
              display: flex;
              align-items: center;
              justify-content: center;
              background-color: rgba(255, 255, 255, 0.85);
              /* 使 Tag 悬浮于彩色格子之上 */

              .tag-text {
                font-size: 18rpx;
                line-height: 22rpx;
                color: #111827;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                text-align: center;
                width: 100%;
              }

              &.tag-type-weight {
                background-color: #bbf7d0 !important;

                .tag-text {
                  color: #14532d;
                  font-weight: 700;
                }
              }

              &.tag-type-note {
                background-color: #ffffff;

                .tag-text {
                  color: #374151;
                }
              }
            }

            .plan-extra {
              font-size: 16rpx;
              color: #4b5563;
              text-align: center;
              line-height: 20rpx;
              font-weight: 600;
            }
          }
        }
      }


    }


  }
}

.explain-popup-content {
  padding: 40rpx 32rpx 60rpx 32rpx;
  background-color: #f8f9fb;

  .explain-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 36rpx;

    .explain-title {
      font-size: 34rpx;
      font-weight: 700;
      color: #111827;
    }
  }

  .explain-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;

    .explain-item {
      background: #fff;
      border-radius: 20rpx;
      padding: 24rpx 24rpx 24rpx 20rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

      .explain-item-left {
        display: flex;
        align-items: center;
        gap: 20rpx;
      }

      .color-block {
        width: 100rpx;
        height: 92rpx;
        border-radius: 14rpx;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;

        &.yellow {
          background-color: #ffdd44;
        }

        &.gray {
          background-color: #e8e8e8;
        }

        &.green {
          background-color: #bbf7d0;
        }

        &.blue {
          background-color: #bae6fd;
        }

        .mini-cell-bg {
          width: 58rpx;
          height: 58rpx;
          background: rgba(255, 255, 255, 0.7);
          border-radius: 8rpx;
          display: flex;
          align-items: flex-end;
          justify-content: center;
          padding-bottom: 4rpx;
        }

        .mini-tag {
          font-size: 14rpx;
          font-weight: 600;
          border-radius: 4rpx;
          padding: 1rpx 6rpx;
          line-height: 20rpx;
          white-space: nowrap;

          &.yellow-tag {
            background: #fff3b0;
            color: #8b6914;
          }

          &.gray-tag {
            background: #f0f0f0;
            color: #555;
          }

          &.green-tag {
            background: #a7f3d0;
            color: #14532d;
          }

          &.blue-tag {
            background: #7dd3fc;
            color: #0c4a6e;
          }
        }
      }

      .item-info {
        display: flex;
        flex-direction: column;
        gap: 6rpx;
        flex: 1;
        min-width: 0;

        .item-label {
          font-size: 30rpx;
          font-weight: 600;
          color: #1f2937;
          line-height: 1.3;
        }

        .item-desc {
          font-size: 24rpx;
          color: #9ca3af;
          line-height: 1.4;
        }
      }
    }
  }
}
</style>