xunji-shuju.vue 27.7 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 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
<template>
  <view class="training-data-page">
    <!-- 顶部时间范围选择器 -->
    <view class="top-time-picker">
      <timeSelect @dateTypeChange="handleTypeChange" @dateRangeChange="handleDateChange" />
    </view>

    <!-- 主体内容可滚动区域 -->
    <view class="main-content">
      <scroll-view scroll-y class="scroll-area" :show-scrollbar="false">
        <up-transition :show="true" mode="slide-right" duration="300">
          <view class="scroll-inner">
            <!-- 1. 肌肉部位数据区域 -->
            <view class="card-section">
              <view class="section-header">
                <text class="title">主训练肌肉数据</text>
              </view>

              <!-- 容量 / 组数 切换标签 -->
              <view class="tab-group">
                <view class="tab-item" :class="{ active: partTabIndex === 0 }" @click="partTabIndex = 0">
                  容量
                </view>
                <view class="tab-item" :class="{ active: partTabIndex === 1 }" @click="partTabIndex = 1">
                  组数
                </view>
              </view>
              <text class="tip-text">{{ TREND_TIPS[partTabIndex] }}</text>

              <!-- 肌肉部位网格(1行4格 + 正方形 + 总计自适应占格) -->
              <view class="muscle-grid">
                <view class="grid-item" v-for="item in detailPartOptions" :key="item.id"
                  @click="openMuscleDetail(item.id)">
                  <text class="item-name">{{ item.name }}</text>
                  <text class="item-value">{{ item.value }}</text>
                </view>

                <!-- 总计格子 -->
                <view class="grid-item total-item" :style="{ gridColumn: `span ${remainSpan}` }">
                  <text class="item-name">总计</text>
                  <text class="item-value highlight">{{ totalPartValue }}</text>
                </view>
              </view>
            </view>

            <!-- 2. 趋势图表区域 -->
            <view class="card-section">
              <view class="section-header space-between">
                <text class="title">趋势</text>
                <view class="part-select-wrapper">
                  <up-select v-model:current="partId"
                    :label="partOptions.find((item) => item.id === partId)?.name || '全部'" :options="partOptions"
                    @select="onPartChange"></up-select>
                </view>
              </view>

              <!-- 趋势维度切换 Tabs -->
              <view class="tab-group flex-wrap">
                <view class="tab-item" v-for="item in trendTabs" :key="item.id"
                  :class="{ active: NumberTabIndex === item.id }" @click="NumberTabIndex = item.id">
                  {{ item.name }}
                </view>
              </view>
              <text class="tip-text">{{ TREND_TIPS[NumberTabIndex] }}</text>

              <!-- 统计图表(根据 showLastPeriod 切换 柱状图 / 折线图) -->
              <view class="chart-container">
                <template v-if="!showLastPeriod">
                  <LineChart v-if="chartCategories.length > 0" :categories="chartCategories" :series="chartSeries"
                    chartType="column" :reshow="true" :extra="{ column: { width: trendChartColumnWidth } }" />
                </template>
                <template v-else>
                  <LineChart v-if="chartCategories.length > 0" :categories="chartCategories" :series="chartSeries"
                    chartType="line" :reshow="true" :extra="{ column: { width: trendChartColumnWidth } }" />
                </template>
              </view>

              <!-- 显示上周/上月数据勾选框 -->
              <view class="toggle-checkbox" @click="toggleLastWeek">
                <checkbox :checked="showLastPeriod" color="#10b981" style="transform: scale(0.8);" />
                <text class="toggle-label">
                  {{ MainCurrentDateType === 'week' ? '显示上周数据' : '显示上月数据' }}
                </text>
              </view>

              <!-- 3. 数据对比区域 -->
              <view class="compare-section">
                <view class="compare-header">
                  <text class="sub-title">对比</text>
                  <view class="legend-group">
                    <view class="legend-item">
                      <view class="dot blue"></view>
                      <text>{{ MainCurrentDateType === 'week' ? '上周' : '上月' }}</text>
                    </view>
                    <view class="legend-item">
                      <view class="dot yellow"></view>
                      <text>{{ MainCurrentDateType === 'week' ? '本周' : '本月' }}</text>
                    </view>
                    <view class="legend-item">
                      <text>对比</text>
                    </view>
                  </view>
                </view>

                <!-- 对比数据卡片 -->
                <view class="compare-card">
                  <view class="data-list">
                    <view v-for="(item, index) in listData" :key="index" class="data-row">
                      <view class="label">{{ item.label }}</view>
                      <view class="value text-secondary">{{ item.lastPeriod }}</view>
                      <view class="value text-main">{{ item.currPeriod }}</view>
                      <view class="value diff" :class="{ positive: item.diff > 0, negative: item.diff < 0 }">
                        {{ item.diff > 0 ? '+' + item.diff : item.diff }}
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </up-transition>

        <!-- 底部安全区域间距 -->
        <view class="bottom-spacer"></view>
      </scroll-view>
    </view>

    <!-- 肌肉详情弹窗 -->
    <up-popup :show="muscleShow" mode="top" round="24rpx" @close="closeMuscleDetail" safeAreaInsetTop>
      <view class="muscleShow-popup" :style="{ paddingTop: statusBarHeight + 'px' }">
        <timeSelect @dateTypeChange="handleTypeChange" @dateRangeChange="handleDateChange" />

        <view class="popup-body">
          <!-- 肌肉名称 -->
          <view class="muscle-name">
            {{ currentMuscleName }}
          </view>

          <!-- 容量/组数 切换标签 -->
          <view class="muscle-tabs">
            <view class="tab-item" :class="{ active: muscleTabIndex === 0 }" @click="muscleTabIndex = 0">
              容量
            </view>
            <view class="tab-item" :class="{ active: muscleTabIndex === 1 }" @click="muscleTabIndex = 1">
              组数
            </view>
          </view>
          <view class="tip">{{ TREND_TIPS[muscleTabIndex] }}</view>

          <!-- 图表区域 -->
          <view class="statistical">
            <LineChart v-if="muscleShow && muscleChartCategories.length"
              :key="`muscle-chart-${currentMuscleId}-${MainCurrentDateType}-${muscleTabIndex}`"
              :categories="muscleChartCategories" :series="muscleChartSeries" chartType="column" :reshow="true"
              :extra="{ column: { width: muscleChartColumnWidth } }" />
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import dayjs from 'dayjs';
import LineChart from './LineChart.vue';
import { ref, computed, onMounted } from 'vue';
import timeSelect from './time-select.vue';
import { getMenuButtonHeight } from '@/utils/safeArea';
import TrainingDataApi from '@/sheep/api/TrainingData/Data.js';
import LeftmotionApi from '@/sheep/api/motion/equipments';

// ==================== 常量 ====================

const WEEKDAY_LABELS = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

/** 趋势维度文案 */
const TREND_DATA_KEYS = ['volume', 'setCount', 'duration', 'distance', 'count'];

const TREND_TIPS = [
  '重量X组数X次数,用来评估训练的整体强度(kg)',
  '该时间段内训练组数趋势(组)',
  '累计计时类动作的时长(min)',
  '累计距离类动作的距离(km)',
  '累计次数类动作的次数(次)',
];

// ==================== 日期工具函数 ====================

/** 格式化日期为 YYYY-MM-DD */
const formatDateKey = (date) => dayjs(date).format('YYYY-MM-DD');

/** 获取包含指定日期的完整周日期列表(周一~周日),返回 dayjs 实例数组 */
const getWeekFullDates = (baseDateStr) => {
  const d = dayjs(baseDateStr);
  const dayOfWeek = d.day(); // 0=周日, 1=周一, ...
  const monday = d.subtract(dayOfWeek === 0 ? 6 : dayOfWeek - 1, 'day').startOf('day');
  return Array.from({ length: 7 }, (_, i) => monday.add(i, 'day'));
};

/** 获取指定日期所在月份的全部日期列表,返回 dayjs 实例数组 */
const getMonthFullDates = (baseDateStr) => {
  const d = dayjs(baseDateStr);
  const daysInMonth = d.daysInMonth();
  return Array.from({ length: daysInMonth }, (_, i) =>
    d.date(i + 1).startOf('day')
  );
};

/** 解析 API 返回的日期数组 [year, month, day] 为 dayjs 实例 */
const parseApiDate = (apiDateArr) => {
  if (!Array.isArray(apiDateArr) || apiDateArr.length !== 3) return null;
  const [year, month, day] = apiDateArr;
  return dayjs(`${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
};

/** 趋势推荐维度按周/月数据加载 */
const loadCategoryData = (date) => {
  const loader = MainCurrentDateType.value === 'week'
    ? loadWeeklyByCategory
    : loadMonthlyByCategory;
  return loader(date);
};

/** 肌肉详情按周/月数据加载 */
const loadMuscleData = (muscleId, date) => {
  const isWeekly = MainCurrentDateType.value === 'week';
  return loadMuscleStats(muscleId, date, isWeekly);
};

// ==================== 响应式状态 ====================

const statusBarHeight = getMenuButtonHeight();

// --- 时间范围 ---
const startDate = ref('');
const endDate = ref('');
const MainCurrentDateType = ref('week'); // 'week' | 'month'

// --- 筛选状态 ---
const partId = ref('');
const partOptions = ref([]);
const showLastPeriod = ref(false);

// --- 趋势 Tab 状态 ---
const NumberTabIndex = ref(0);
const trendTabs = ref([
  { id: 0, name: '容量' },
  { id: 1, name: '组数' },
  { id: 2, name: '时长' },
  { id: 3, name: '距离' },
  { id: 4, name: '次数' },
]);

// --- 肌肉部位 Tab ---
const partTabIndex = ref(0);

// --- 加载锁 ---
const weeklyLoading = ref(false);
const trainingLoading = ref(false);
const muscleListLoading = ref(false);

// --- 数据 ---
const weeklyData = ref(null);
const subCategorieList = ref([]);
const trainingData = ref({ setCountMap: {}, totalVolumeMap: {} });

// --- 肌肉弹窗 ---
const muscleShow = ref(false);
const muscleTabIndex = ref(0);
const currentMuscleId = ref(null);
const currentMuscleName = ref('');
const muscleDetailData = ref({ muscleId: 0, dailyStatsList: [] });
const muscleFullDates = ref([]);
const muscleProcessedData = ref({ volumeArr: [], setsArr: [] });

// ==================== 计算属性 ====================

/** 肌肉部位数据列表(支持容量/组数切换) */
const detailPartOptions = computed(() => {
  if (!subCategorieList.value.length) return [];

  const isVolume = partTabIndex.value === 0;
  const dataMap = isVolume
    ? trainingData.value.totalVolumeMap
    : trainingData.value.setCountMap;

  return subCategorieList.value.map((item) => ({
    id: item.id,
    name: item.name,
    value: dataMap[item.id] ?? 0,
  }));
});

/** 肌肉部位总计 */
const totalPartValue = computed(() =>
  detailPartOptions.value.reduce((sum, item) => sum + (Number(item.value) || 0), 0)
);

/** 总计格子剩余 span(补齐最后一行) */
const remainSpan = computed(() => {
  const mod = detailPartOptions.value.length % 4;
  return mod === 0 ? 4 : 4 - mod;
});

/** 图表 X 轴日期标签 */
const chartCategories = computed(() => {
  if (!weeklyData.value) return [];

  const fullDates = MainCurrentDateType.value === 'week'
    ? getWeekFullDates(startDate.value)
    : getMonthFullDates(startDate.value);

  return MainCurrentDateType.value === 'week'
    ? fullDates.map((d) => d.format('M/D'))
    : fullDates.map((d) => d.format('D'));
});

/** 柱体宽度 */
const trendChartColumnWidth = computed(() =>
  MainCurrentDateType.value === 'week' ? 15 : 3
);

const muscleChartColumnWidth = computed(() =>
  MainCurrentDateType.value === 'week' ? 15 : 3
);

/** 趋势图 Series 数据 */
const chartSeries = computed(() => {
  if (!weeklyData.value) return [];

  const isWeekly = MainCurrentDateType.value === 'week';
  const fullDateList = isWeekly
    ? getWeekFullDates(startDate.value)
    : getMonthFullDates(startDate.value);

  const fullDateKeys = fullDateList.map((d) => formatDateKey(d));

  const currDataMap = isWeekly
    ? weeklyData.value.weeklyDataMap || {}
    : weeklyData.value.monthlyDataMap || {};

  const lastDataMap = isWeekly
    ? weeklyData.value.lastWeekDataMap || {}
    : weeklyData.value.lastMonthDataMap || {};

  const dataKey = TREND_DATA_KEYS[NumberTabIndex.value] || 'volume';

  // 当前周期数据
  const currData = fullDateKeys.map((dateStr) => convertUnit(currDataMap[dateStr]?.[dataKey], dataKey));

  // 上一周期数据(按日期偏移匹配)
  const lastData = fullDateKeys.map((dateStr) => {
    const targetKey = isWeekly
      ? dayjs(dateStr).subtract(7, 'day').format('YYYY-MM-DD')
      : dayjs(dateStr).subtract(1, 'month').format('YYYY-MM-DD');
    return convertUnit(lastDataMap[targetKey]?.[dataKey], dataKey);
  });

  const currName = isWeekly ? '本周' : '本月';
  const lastName = isWeekly ? '上周' : '上月';

  return showLastPeriod.value
    ? [
        { name: lastName, data: lastData, color: '#5b8ff9' },
        { name: currName, data: currData, color: '#ffc53d' },
      ]
    : [{ name: currName, data: currData, color: '#ffc53d' }];
});

/** 周期对比数据 */
const listData = computed(() => {
  if (!weeklyData.value) return [];

  const d = weeklyData.value;
  const fields = [
    { label: '容量', key: 'volume', last: d.lastWeekTotalVolume, curr: d.totalVolume },
    { label: '组数', key: 'setCount', last: d.lastWeekTotalSets, curr: d.totalSets },
    { label: '时长', key: 'duration', last: d.lastWeekTotalDuration, curr: d.totalDuration },
    { label: '距离', key: 'distance', last: d.lastWeekTotalDistance, curr: d.totalDistance },
    { label: '次数', key: 'count', last: d.lastWeekTotalCount, curr: d.totalCount },
  ];

  return fields.map(({ label, key, last, curr }) => {
    const lastVal = convertUnit(last, key);
    const currVal = convertUnit(curr, key);
    return {
      label,
      lastPeriod: lastVal,
      currPeriod: currVal,
      diff: Number((currVal - lastVal).toFixed(1)),
    };
  });
});

/**
 * 字段单位换算:API 返回秒/米等,UI 展示为分/km 等
 * duration(秒)→ 分钟
 * 其它字段(volume/setCount/distance/count)保持原值
 */
const convertUnit = (val, key) => {
  const v = Number(val) || 0;
  if (key === 'duration') {
    // 秒 → 分钟,保留 1 位小数(如 90s → 1.5)
    return Math.round((v / 60) * 10) / 10;
  }
  return v;
};

/** 肌肉弹窗图表 X 轴 */
const muscleChartCategories = computed(() => {
  if (MainCurrentDateType.value === 'week') {
    return WEEKDAY_LABELS;
  }
  if (!muscleFullDates.value.length) return [];
  return muscleFullDates.value.map((d) => dayjs(d).format('M/D'));
});

const muscleVolumeArr = computed(() => muscleProcessedData.value.volumeArr || []);
const muscleSetsArr = computed(() => muscleProcessedData.value.setsArr || []);

/** 肌肉弹窗图表 Series */
const muscleChartSeries = computed(() => {
  const data = muscleTabIndex.value === 0 ? muscleVolumeArr.value : muscleSetsArr.value;
  const name = muscleTabIndex.value === 0 ? '容量' : '组数';
  const color = muscleTabIndex.value === 0 ? '#ffc53d' : '#5b8ff9';

  return [{ name, data: data || [], color }];
});

// ==================== API 请求方法 ====================

/** 加载周分类趋势数据 */
const loadWeeklyByCategory = async (date) => {
  if (weeklyLoading.value || !date) return;
  weeklyLoading.value = true;
  try {
    const categoryId = (partId.value && partId.value !== '') ? partId.value : '0';
    const res = await TrainingDataApi.weeklyByCategory(
      date,
      categoryId,
      showLastPeriod.value ? 'true' : 'false',
    );
    weeklyData.value = res.data;
  } catch (err) {
    console.error('动作分类周数据加载失败', err);
  } finally {
    weeklyLoading.value = false;
  }
};

/** 加载月分类趋势数据 */
const loadMonthlyByCategory = async (date) => {
  if (weeklyLoading.value || !date) return;
  weeklyLoading.value = true;
  try {
    const categoryId = (partId.value && partId.value !== '') ? partId.value : '0';
    const res = await TrainingDataApi.monthlyByCategory(
      date,
      categoryId,
      showLastPeriod.value ? 'true' : 'false',
    );
    weeklyData.value = res.data;
  } catch (err) {
    console.error('动作分类月数据加载失败', err);
  } finally {
    weeklyLoading.value = false;
  }
};

/** 加载肌肉部位分类列表 */
const loadGetSubCategorieList = async () => {
  if (muscleListLoading.value) return;
  muscleListLoading.value = true;
  try {
    const res = await TrainingDataApi.GetSubCategorieList();
    subCategorieList.value = res.data || [];
  } catch (err) {
    console.error('加载失败:', err);
  } finally {
    muscleListLoading.value = false;
  }
};

/** 加载部位选项列表 */
const loadbodyPartOptions = async () => {
  const res = await LeftmotionApi.getAllCategories();
  partOptions.value = [
    { id: '0', name: '全部' },
    ...res.data.map((item) => ({ id: String(item.id), name: item.name })),
  ];
};

/** 加载肌肉部位训练数据(容量/组数分布) */
const loadTrainingData = async (sDate, eDate) => {
  if (trainingLoading.value) return;
  trainingLoading.value = true;
  const s = String(sDate);
  const e = String(eDate);
  if (!s || !e || s === 'undefined' || e === 'undefined') return;
  try {
    const res = await TrainingDataApi.mainDataAnalysis(s, e);
    if (res.data) {
      trainingData.value.setCountMap = res.data.setCountMap || {};
      trainingData.value.totalVolumeMap = res.data.totalVolumeMap || {};
    }
  } catch (err) {
    console.error('加载失败:', err);
  } finally {
    trainingLoading.value = false;
  }
};

/** 加载单肌肉统计数据(周/月通用) */
const loadMuscleStats = async (muscleId, date, isWeekly) => {
  try {
    const res = isWeekly
      ? await TrainingDataApi.weeklyMuscleStats(muscleId, date)
      : await TrainingDataApi.monthlyMuscleStats(muscleId, date);

    muscleDetailData.value = res.data || { muscleId: 0, dailyStatsList: [] };

    const fullDates = isWeekly ? getWeekFullDates(date) : getMonthFullDates(date);
    muscleFullDates.value = fullDates;

    // 将 API 返回的 dailyStatsList 按日期建立索引
    const dateMap = {};
    muscleDetailData.value.dailyStatsList.forEach((item) => {
      const d = parseApiDate(item.date);
      if (d) {
        dateMap[formatDateKey(d)] = { volume: item.volume, sets: item.sets };
      }
    });

    // 按完整日期列表填充数据,缺失的补 0
    const volumeArr = [];
    const setsArr = [];
    fullDates.forEach((d) => {
      const data = dateMap[formatDateKey(d)] || { volume: 0, sets: 0 };
      volumeArr.push(data.volume);
      setsArr.push(data.sets);
    });

    muscleProcessedData.value = { volumeArr, setsArr };
  } catch (err) {
    console.error('单肌肉数据加载失败', err);
  }
};

// ==================== 页面事件 ====================

/** 筛选部位切换 */
const onPartChange = (item) => {
  partId.value = item.id;
  loadCategoryData(startDate.value);
};

/** 时间类型切换(周/月) */
const handleTypeChange = async (type) => {
  MainCurrentDateType.value = type;
  showLastPeriod.value = false;
  loadTrainingData(startDate.value, endDate.value);

  if (startDate.value) {
    await loadCategoryData(startDate.value);
  }

  // 如果肌肉弹窗打开,同步刷新
  if (muscleShow.value && currentMuscleId.value) {
    await loadMuscleData(currentMuscleId.value, startDate.value);
  }
};

/** 日期范围变更 */
const handleDateChange = async (data) => {
  startDate.value = data.startDate;
  endDate.value = data.endDate;
  await loadTrainingData(startDate.value, endDate.value);
  loadCategoryData(startDate.value);

  if (muscleShow.value && currentMuscleId.value) {
    await loadMuscleData(currentMuscleId.value, startDate.value);
  }
};

/** 打开肌肉详情弹窗 */
const openMuscleDetail = async (muscleId) => {
  currentMuscleId.value = muscleId;
  muscleShow.value = true;
  muscleTabIndex.value = 0;

  const muscle = subCategorieList.value.find((item) => item.id === muscleId);
  currentMuscleName.value = muscle?.name || '';

  await loadMuscleData(muscleId, startDate.value);
};

/** 关闭肌肉详情弹窗 */
const closeMuscleDetail = () => {
  muscleShow.value = false;
  setTimeout(() => {
    currentMuscleId.value = null;
    currentMuscleName.value = '';
    muscleDetailData.value = { muscleId: 0, dailyStatsList: [] };
    muscleFullDates.value = [];
    muscleProcessedData.value = { volumeArr: [], setsArr: [] };
  }, 150);
};

/** 切换显示上一周期数据 */
const toggleLastWeek = () => {
  showLastPeriod.value = !showLastPeriod.value;
  if (startDate.value) {
    loadCategoryData(startDate.value);
  }
};

// ==================== 生命周期 ====================

onMounted(async () => {
  await loadbodyPartOptions();
  await loadGetSubCategorieList();
  if (startDate.value && endDate.value) {
    await loadTrainingData(startDate.value, endDate.value);
    await loadCategoryData(startDate.value);
  }
});
</script>

<style lang="scss" scoped>
// ==================== CSS 变量 ====================
$color-primary: #202932;
$color-bg: #f8fafc;
$color-card: #ffffff;
$color-border: #f1f5f9;
$color-text: #0f172a;
$color-sub: #475569;
$color-muted: #94a3b8;
$color-green: #10b981;
$color-green-bg: #ecfdf5;
$color-green-border: #a7f3d0;
$color-blue: #5b8ff9;
$color-yellow: #ffc53d;
$color-red: #ff7875;
$radius-card: 24rpx;
$radius-tab: 50rpx;
$radius-item: 12rpx;

// ==================== 公共 Tab 样式 ====================
.tab-group {
  display: flex;
  gap: 16rpx;
  margin-bottom: 12rpx;

  &.flex-wrap {
    flex-wrap: wrap;
  }
}

.tab-item {
  border: 1rpx solid #e2e8f0;
  border-radius: $radius-tab;
  background-color: $color-card;
  padding: 10rpx 24rpx;
  font-size: 24rpx;
  color: $color-sub;
  transition: all 0.2s ease;
  cursor: pointer;

  &.active {
    background-color: $color-primary;
    color: $color-card;
    border-color: $color-primary;
    font-weight: 600;
  }

  &:active {
    opacity: 0.8;
  }
}

.tip-text {
  font-size: 22rpx;
  color: $color-muted;
  margin-bottom: 20rpx;
  display: block;
}

// ==================== 页面主容器 ====================
.training-data-page {
  display: flex;
  flex-direction: column;
 
  width: 100vw;
  background-color: $color-bg;
  overflow: hidden;

  // 顶部固定时间选择栏
  .top-time-picker {
    padding: 20rpx 24rpx;
    box-sizing: border-box;
    background-color: $color-card;
    border-bottom: 1rpx solid $color-border;
    z-index: 10;
  }

  // 主体可滚动区域
  .main-content {
    flex: 1;
    height: 0;
    min-height: 0;
    overflow: hidden;

    .scroll-area {
      width: 100%;
      height: 100%;

      .scroll-inner {
        padding: 24rpx;
        display: flex;
        flex-direction: column;
        gap: 24rpx;
      }
    }
  }

  // 卡片通用容器
  .card-section {
    background-color: $color-card;
    border-radius: $radius-card;
    padding: 28rpx 24rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.02);
    border: 1rpx solid $color-border;

    .section-header {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      &.space-between {
        justify-content: space-between;
      }

      .title {
        font-size: 30rpx;
        font-weight: 700;
        color: $color-text;
      }

      .part-select-wrapper {
        min-width: 140rpx;
      }
    }

    // 肌肉部位网格
    .muscle-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 10rpx;

      .grid-item {
        width: 100%;
        height: 140rpx;
        background-color: $color-bg;
        border: 1rpx solid $color-border;
        border-radius: $radius-item;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 10rpx;
        transition: transform 0.15s, background-color 0.15s;

        &:active {
          transform: scale(0.96);
          background-color: #f1f5f9;
        }

        .item-name {
          font-size: 24rpx;
          color: $color-sub;
        }

        .item-value {
          font-size: 26rpx;
          font-weight: 700;
          color: #000000;

          &.highlight {
            color: $color-green;
          }
        }

        &.total-item {
          background-color: $color-green-bg;
          border-color: $color-green-border;

          .item-name {
            color: #047857;
            font-weight: 600;
          }
        }
      }
    }

    // 图表容器
    .chart-container {
      width: 100%;
      height: 400rpx;
    }

    // 显示上期数据勾选
    .toggle-checkbox {
      display: flex;
      align-items: center;
      margin-top: 20rpx;
      font-size: 24rpx;
      color: #333333;

      .toggle-label {
        margin-left: 8rpx;
      }
    }

    // 周期对比区域
    .compare-section {
      margin-top: 30rpx;

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

        .sub-title {
          font-size: 36rpx;
          font-weight: 700;
          color: #333333;
        }

        .legend-group {
          display: flex;
          gap: 32rpx;

          .legend-item {
            display: flex;
            align-items: center;
            font-size: 24rpx;
            color: #666666;

            .dot {
              width: 20rpx;
              height: 20rpx;
              border-radius: 4rpx;
              margin-right: 8rpx;

              &.blue { background-color: $color-blue; }
              &.yellow { background-color: $color-yellow; }
            }
          }
        }
      }

      .compare-card {
        background-color: $color-card;
        border-radius: 20rpx;
        border: 5rpx solid #efefef;
        overflow: hidden;

        .data-list {
          .data-row {
            display: flex;
            align-items: center;
            padding: 30rpx 0;
            border-bottom: 1rpx solid #f0f0f0;
            font-size: 26rpx;

            &:last-child { border-bottom: none; }
            &:nth-child(odd) { background-color: #f9fafc; }

            .label {
              flex: 1.5;
              color: #333333;
              text-align: center;
            }

            .value {
              flex: 1;
              text-align: center;
              color: #333333;

              &.diff {
                font-weight: 600;

                &.positive { color: $color-green; }
                &.negative { color: $color-red; }
              }
            }
          }
        }
      }
    }
  }

  // 底部安全间距
  .bottom-spacer {
    height: env(safe-area-inset-bottom);
    padding-bottom: 110rpx;
  }
}

// ==================== 肌肉弹窗样式 ====================
.muscleShow-popup {
  padding-bottom: 30rpx;

  /* #ifdef MP-WEIXIN */
  min-height: 40vh;
  /* #endif */

  /* #ifdef H5 */
  min-height: 55vh;
  /* #endif */

  .popup-body {
    .muscle-name {
      font-size: 32rpx;
      font-weight: bold;
      padding: 20rpx 20rpx 0;
    }

    .muscle-tabs {
      display: flex;
      gap: 20rpx;
      padding: 20rpx;
    }

    .tip {
      font-size: 22rpx;
      padding: 0 20rpx 20rpx;
      color: $color-muted;
    }

    .statistical {
      width: 100%;
      height: 400rpx;
      margin-top: 20rpx;
    }
  }
}
</style>