xunji-shuju.vue 30.9 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 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
<template>
  <view class="training-data-page">
    <timeSelect @dateTypeChange="handleTypeChange" @dateRangeChange="handleDateChange" />

    <!-- 过渡动画 -->
    <up-transition :show="true" mode="slide-right" duration="300">
      <view class="content-scroll">
        <!-- 肌肉部位数据区域 -->
        <view class="section">
          <view class="muscle-data">
            <view class="title">主训练肌肉数据</view>
            <view class="tabs">
              <view class="tab" :class="{ active: partTabIndex === 0 }" @click="partTabIndex = 0">容量</view>
              <view class="tab" :class="{ active: partTabIndex === 1 }" @click="partTabIndex = 1">组数</view>
            </view>
            <view class="tip">{{ tabTip[partTabIndex] }}</view>

            <!-- 网格布局:一行4格 + 正方形 + 总计自适应 -->
            <view class="detail-part" :style="`--remain-span: ${remainSpan}`">
              <view class="part-item" v-for="item in detailPartOptions" :key="item.id"
                @click="openMuscleDetail(item.id)">
                <text class=" txt">{{ item.name }}</text>
                <text class="num">{{ item.value }}</text>
              </view>
              <view class="part-item total-item">
                <text class="txt">总计</text>
                <text class="num">{{ totalPartValue }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 趋势图表区域 -->
        <view class="section">
          <view class="header">
            <view class="title">趋势</view>
            <view class="mean">
              <up-select v-model:current="partId" :label="partOptions.find(item => item.id === partId)?.name || '全部'"
                :options="partOptions" @select="onPartChange"></up-select>
            </view>
          </view>
          <view class="tabs">
            <view class="tab" v-for="item in trendTabs" :key="item.id" :class="{ active: NumberTabIndex === item.id }"
              @click="NumberTabIndex = item.id">
              {{ item.name }}
            </view>
          </view>
          <view class="tip">{{ tabTip[NumberTabIndex] }}</view>

          <view class="statistical">
            <template v-if="!showLastPeriod">
              <LineChart :categories="chartCategories" :series="chartSeries" chartType="column" :reshow="true"
                :extra="{ column: { width: trendChartColumnWidth } }" />
            </template>
            <template v-else>
              <LineChart :categories="chartCategories" :series="chartSeries" chartType="line" :reshow="true"
                :extra="{ column: { width: trendChartColumnWidth } }" />
            </template>
          </view>

          <view class="chose">
            <checkbox :checked="showLastPeriod" @click="toggleLastWeek" />
            {{ MainCurrentDateType === 'week' ? '显示上周数据' : '显示上月数据' }}
          </view>

          <!-- 数据对比 -->
          <view class="compare">
            <view class="header-row">
              <text class="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">{{ item.lastPeriod }}</view>
                  <view class="value">{{ item.currPeriod }}</view>
                  <view class="value diff" :class="{ negative: item.diff < 0 }">
                    {{ item.diff > 0 ? '+' + item.diff : item.diff }}
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </up-transition>

    <!-- 肌肉详情弹窗 -->
    <!-- <up-popup :show="muscleShow" mode="top" @close="muscleShow = false" safeAreaInsetTop>
      <view class="muscleShow-popup" :style="{ paddingTop: statusBarHeight + 'px' }">
        <timeSelect @dateTypeChange="handleTypeChange" @dateRangeChange="handleDateChange" />
        <view class="statistical">
          <LineChart v-if="muscleShow" @close="closeMuscleDetail" :categories="muscleChartCategories" :series="[
            { name: '容量', data: muscleVolumeArr },
            { name: '组数', data: muscleSetsArr }
          ]" chartType="column" />
        </view>
      </view>
    </up-popup> -->
    <up-popup :show="muscleShow" mode="top" @close="closeMuscleDetail" safeAreaInsetTop>
      <view class="muscleShow-popup" :style="{ paddingTop: statusBarHeight + 'px' }">
        <timeSelect @dateTypeChange="handleTypeChange" @dateRangeChange="handleDateChange" />

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

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

        <!-- 图表区域 -->
        <view class="statistical">
          <!-- <LineChart v-if="muscleShow" :categories="muscleChartCategories" :series="muscleChartSeries"
            chartType="column" /> -->
          <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>
    </up-popup>

  </view>
</template>

<script setup>
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 statusBarHeight = getMenuButtonHeight();

// 时间范围
const startDate = ref('')
const endDate = ref('')

// 肌肉弹窗
// 弹窗的容量/组数切换索引
const muscleTabIndex = ref(0)
const muscleShow = ref(false);
const currentMuscleName = ref('')
const selectLabel = ref('全部')
const partId = ref('');
const partOptions = ref([]);

const weeklyData = ref(null);

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

// 时间类型 week / month
const MainCurrentDateType = ref('week');

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

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

// 肌肉部位标签
const partTabIndex = ref(0);

// 核心:格式化肌肉部位数据,支持容量/组数切换
const detailPartOptions = computed(() => {
  // 没有肌肉数据时返回空数组
  if (!subCategorieList.value.length) return []

  // 根据当前选中的标签,决定取哪个数据
  const isVolume = partTabIndex.value === 0 // 0是容量,1是组数
  const dataMap = isVolume ? trainingData.value.totalVolumeMap : trainingData.value.setCountMap

  // 把 subCategorieList 里的每一项,加上对应的数据
  return subCategorieList.value.map(item => {
    return {
      id: item.id,
      name: item.name,
      // 从 dataMap 里取数据,没有的话默认0
      value: dataMap[item.id] ?? 0
    }
  })
})

const totalPartValue = computed(() => {
  return detailPartOptions.value.reduce((sum, item) => sum + (Number(item.value) || 0), 0)
})

// 弹窗用的完整日期列表(周/月模式下的所有日期)
const muscleFullDates = ref([])
const muscleProcessedData = ref({
  volumeArr: [],
  setsArr: []
})

// 核心:计算最后一行剩余格子数,用于总计自适应占格
const itemTotal = computed(() => detailPartOptions.value.length)
const remainSpan = computed(() => {
  const mod = itemTotal.value % 4
  return mod === 0 ? 4 : 4 - mod
})

const showLastPeriod = ref(false);

// 周/月 图表类目 & 数据
const weekCategories = ref(['周一', '周二', '周三', '周四', '周五', '周六', '周日']);

const lastMonthData = ref(Array(31).fill(0));

// ✅ 修复版:强制生成完整的周/月日期,就算没数据也要显示横轴
const chartCategories = computed(() => {
  if (!weeklyData.value) return []

  if (MainCurrentDateType.value === 'week') {
    // 周模式:生成周一到周日的完整日期(月/日格式)
    const weekDates = getWeekFullDates(startDate.value).map(d => {
      const month = d.getMonth() + 1
      const day = d.getDate()
      return `${month}/${day}`
    })
    return weekDates
  } else {
    // 月模式:生成当月1日到月底的完整日期(纯日期格式)
    const monthDates = getMonthFullDates(startDate.value).map(d => {
      return `${d.getDate()}`
    })
    return monthDates
  }
})

// 趋势图表动态柱子宽度:周20,月3
const trendChartColumnWidth = computed(() => {
  return MainCurrentDateType.value === 'week' ? 15 : 3
})



// 动态控制柱状图宽度:周15,月5
const muscleChartColumnWidth = computed(() => {
  return MainCurrentDateType.value === 'week' ? 15 : 3
})

const trendTabIndex = ref(0);

// ✅ 修复版:对比表数据,直接从接口取上周/上月总数据
const listData = computed(() => {
  if (!weeklyData.value) return []

  const curr = weeklyData.value
  // 上周/上月的总数据,接口里的字段名是 lastWeekTotalXXX
  const last = weeklyData.value

  return [
    {
      label: '容量',
      lastPeriod: last.lastWeekTotalVolume ?? 0,
      currPeriod: curr.totalVolume ?? 0,
      diff: (curr.totalVolume ?? 0) - (last.lastWeekTotalVolume ?? 0)
    },
    {
      label: '组数',
      lastPeriod: last.lastWeekTotalSets ?? 0,
      currPeriod: curr.totalSets ?? 0,
      diff: (curr.totalSets ?? 0) - (last.lastWeekTotalSets ?? 0)
    },
    {
      label: '时长',
      lastPeriod: last.lastWeekTotalDuration ?? 0,
      currPeriod: curr.totalDuration ?? 0,
      diff: (curr.totalDuration ?? 0) - (last.lastWeekTotalDuration ?? 0)
    },
    {
      label: '距离',
      lastPeriod: last.lastWeekTotalDistance ?? 0,
      currPeriod: curr.totalDistance ?? 0,
      diff: (curr.totalDistance ?? 0) - (last.lastWeekTotalDistance ?? 0)
    },
    {
      label: '次数',
      lastPeriod: last.lastWeekTotalCount ?? 0,
      currPeriod: curr.totalCount ?? 0,
      diff: (curr.totalCount ?? 0) - (last.lastWeekTotalCount ?? 0)
    }
  ]
})

const chartSeries = computed(() => {
  if (!weeklyData.value) return []

  // 1. 获取当前周/月完整日期列表
  let fullDateList = MainCurrentDateType.value === 'week'
    ? getWeekFullDates(startDate.value)
    : getMonthFullDates(startDate.value)

  // 转成 YYYY-MM-DD
  const fullDateKeys = fullDateList.map(d => {
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${y}-${m}-${day}`
  })
  // weeklyData是周/月返回的数据
  const currDataMap = MainCurrentDateType.value === 'week'
    ? weeklyData.value.weeklyDataMap || {}
    : weeklyData.value.monthlyDataMap || {};

  const lastDataMap = MainCurrentDateType.value === 'week'
    ? weeklyData.value.lastWeekDataMap || {}
    : weeklyData.value.lastMonthDataMap || {};
  const keyMap = ['volume', 'setCount', 'duration', 'distance', 'count']
  const dataKey = keyMap[NumberTabIndex.value] || 'volume'

  // 本周/本月数据
  const currData = fullDateKeys.map(dateStr => currDataMap[dateStr]?.[dataKey] ?? 0)

  // ✅ 加这行,看控制台打印的 currData 数组
  console.log('【月数据数组 currData】', currData);
  console.log('【当前选中的 dataKey】', dataKey);
  console.log('【接口返回的 monthlyDataMap】', weeklyData.value.monthlyDataMap);

  // ==========================================
  // 核心:周减7天 / 月减1个月(自动适配大小月)
  // ==========================================
  const lastData = fullDateKeys.map(dateStr => {
    const now = new Date(dateStr)
    const target = new Date(now)

    if (MainCurrentDateType.value === 'week') {
      target.setDate(target.getDate() - 7)
    } else {
      target.setMonth(target.getMonth() - 1) // ✅ JS自动处理大小月
    }

    const y = target.getFullYear()
    const m = String(target.getMonth() + 1).padStart(2, '0')
    const day = String(target.getDate()).padStart(2, '0')
    const key = `${y}-${m}-${day}`

    return lastDataMap[key]?.[dataKey] ?? 0
  })

  const currName = MainCurrentDateType.value === 'week' ? '本周' : '本月'
  const lastName = MainCurrentDateType.value === 'week' ? '上周' : '上月'

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

// 处理肌肉弹窗的图标坐标数据
// 1. 根据当前日期,生成周模式的完整日期列表(周一到周日)
const getWeekFullDates = (baseDateStr) => {
  const date = new Date(baseDateStr)
  const day = date.getDay() // 0=周日, 1=周一...
  const monday = new Date(date)
  monday.setDate(date.getDate() - (day === 0 ? 6 : day - 1))

  const dates = []
  for (let i = 0; i < 7; i++) {
    const d = new Date(monday)
    d.setDate(monday.getDate() + i)
    dates.push(d)
  }
  return dates
}

// 2. 根据当前日期,生成月模式的完整日期列表(当月1日到月底)
const getMonthFullDates = (baseDateStr) => {
  const date = new Date(baseDateStr)
  const year = date.getFullYear()
  const month = date.getMonth()
  const daysInMonth = new Date(year, month + 1, 0).getDate()

  const dates = []
  for (let i = 1; i <= daysInMonth; i++) {
    dates.push(new Date(year, month, i))
  }
  return dates
}

// 3. 接口返回的 date 数组 [年,月,日] 转成 Date 对象
const parseApiDate = (apiDateArr) => {
  // apiDateArr 格式: [2026, 6, 1]
  if (!Array.isArray(apiDateArr) || apiDateArr.length !== 3) return null
  const [year, month, day] = apiDateArr
  return new Date(year, month - 1, day) // 注意: 月份是0-11
}

// 接口请求方法
// 根据动作分类获取指定日期所在周训练数据
const loadWeeklyByCategory = async (date) => {
  if (weeklyLoading.value) return;
  if (!date) return;
  weeklyLoading.value = true;
  try {
    let categoryId = '0'
    if (partId.value && partId.value !== '') {
      categoryId = partId.value
    }
    const res = await TrainingDataApi.weeklyByCategory(date, categoryId, showLastPeriod.value ? 'true' : 'false');
    console.log('===== 周数据接口完整返回 =====');
    console.log(res.data);
    console.log('本周weeklyDataMap:', res.data.weeklyDataMap);
    console.log('上周lastWeekDataMap:', res.data.lastWeekDataMap);
    console.log('上周总数据(lastWeekTotalXXX):', {
      volume: res.data.lastWeekTotalVolume,
      sets: res.data.lastWeekTotalSets,
      duration: res.data.lastWeekTotalDuration,
      distance: res.data.lastWeekTotalDistance,
      count: res.data.lastWeekTotalCount
    });
    weeklyData.value = res.data;
  } catch (err) {
    console.error('动作分类周数据加载失败', err);
  } finally {
    weeklyLoading.value = false;
  }
};

// 根据动作分类获取指定日期所在月训练数据(可选择包含上月数据)
const loadMonthlyByCategory = async (date) => {
  if (weeklyLoading.value) return;
  if (!date) return;
  weeklyLoading.value = true;
  try {
    let categoryId = '0'
    if (partId.value && partId.value !== '') {
      categoryId = partId.value
    }
    console.log('是否返回上个的数据:', showLastPeriod.value);
    const res = await TrainingDataApi.monthlyByCategory(date, categoryId, showLastPeriod.value ? 'true' : 'false');
    console.log('【动作分类月数据接口返回】', res.data);
    weeklyData.value = res.data;
  } catch (err) {
    console.error('动作分类月数据加载失败', err);
  } finally {
    weeklyLoading.value = false;
  }
};

// 加载部位/动作分类
const loadbodyPartOptions = async () => {
  const res = await LeftmotionApi.getAllCategories();
  partOptions.value = [
    { id: '0', name: '全部' },
    ...res.data.map(item => {
      return {
        id: String(item.id),
        name: item.name
      }
    })
  ]
  console.log('部位列表:', partOptions.value);
};
const currentMuscleId = ref(null) // 当前点击的肌肉ID
// 加载肌肉数据
const subCategorieList = ref([])
// 训练数据(来自 loadTrainingData 接口)
const trainingData = ref({
  setCountMap: {}, // 组数数据 { id: count }
  totalVolumeMap: {} // 容量数据 { id: volume }
})
const loadGetSubCategorieList = async () => {
  if (muscleListLoading.value) return;
  muscleListLoading.value = true;
  try {
    const res = await TrainingDataApi.GetSubCategorieList();
    subCategorieList.value = res.data;
    console.log('肌肉数据:', subCategorieList.value);
  } catch (err) {
    console.error('加载失败:', err);
  } finally {
    muscleListLoading.value = false;
  }
};
// 加载肌肉表格数据表格
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);
    console.log('训练数据:', res.data);
    if (res.data) {
      trainingData.value.setCountMap = res.data.setCountMap || {}
      trainingData.value.totalVolumeMap = res.data.totalVolumeMap || {}
      console.log('trainingData.value', trainingData.value);

    }
  } catch (err) {
    console.error('加载失败:', err);
  } finally {
    trainingLoading.value = false;
  }
};
// 打开肌肉弹窗需要的数据
const openMuscleDetail = async (muscleId) => {
  console.log('点击了肌肉ID:', muscleId)
  currentMuscleId.value = muscleId
  muscleShow.value = true
  // 默认选中容量
  muscleTabIndex.value = 0

  // 从 subCategorieList 里找到肌肉名称
  const muscle = subCategorieList.value.find(item => item.id === muscleId)
  currentMuscleName.value = muscle?.name || ''

  // 根据当前是周/月模式,加载对应接口
  if (MainCurrentDateType.value === 'week') {
    await loadWeeklyMuscleStats(muscleId, startDate.value)
  } else {
    await loadMonthlyMuscleStats(muscleId, startDate.value)
  }
}

const muscleDetailData = ref({
  muscleId: 0,
  dailyStatsList: []
})

// 加载 单肌肉-周统计
const loadWeeklyMuscleStats = async (muscleId, date) => {
  try {
    const res = await TrainingDataApi.weeklyMuscleStats(muscleId, date)
    console.log('单肌肉周数据:', res.data)
    muscleDetailData.value = res.data || { muscleId: 0, dailyStatsList: [] }

    // --- 核心:数据对齐处理 ---
    // 1. 生成本周完整日期列表
    const fullDates = getWeekFullDates(date)
    muscleFullDates.value = fullDates

    // 2. 把接口数据按日期存成映射表
    const dateMap = {}
    muscleDetailData.value.dailyStatsList.forEach(item => {
      const d = parseApiDate(item.date)
      if (d) {
        // 转成 YYYY-MM-DD 字符串当key
        const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
        dateMap[key] = {
          volume: item.volume,
          sets: item.sets
        }
      }
    })

    // 3. 按完整日期列表填充数据,没有数据填0
    const volumeArr = []
    const setsArr = []
    fullDates.forEach(d => {
      const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
      const data = dateMap[key] || { volume: 0, sets: 0 }
      volumeArr.push(data.volume)
      setsArr.push(data.sets)
    })

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

// 加载 单肌肉-月统计
const loadMonthlyMuscleStats = async (muscleId, date) => {
  try {
    const res = await TrainingDataApi.monthlyMuscleStats(muscleId, date)
    console.log('单肌肉月数据:', res.data)
    muscleDetailData.value = res.data || { muscleId: 0, dailyStatsList: [] }

    // --- 核心:数据对齐处理 ---
    // 1. 生成本月完整日期列表
    const fullDates = getMonthFullDates(date)
    muscleFullDates.value = fullDates

    // 2. 把接口数据按日期存成映射表
    const dateMap = {}
    muscleDetailData.value.dailyStatsList.forEach(item => {
      const d = parseApiDate(item.date)
      if (d) {
        const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
        dateMap[key] = {
          volume: item.volume,
          sets: item.sets
        }
      }
    })

    // 3. 按完整日期列表填充数据,没有数据填0
    const volumeArr = []
    const setsArr = []
    fullDates.forEach(d => {
      const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
      const data = dateMap[key] || { volume: 0, sets: 0 }
      volumeArr.push(data.volume)
      setsArr.push(data.sets)
    })

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

const closeMuscleDetail = () => {

  muscleShow.value = false
  // currentMuscleId.value = null
  // currentMuscleName.value = ''
  // muscleTabIndex.value = 0
  // muscleDetailData.value = { muscleId: 0, dailyStatsList: [] }
  // muscleFullDates.value = []
  // muscleProcessedData.value = { volumeArr: [], setsArr: [] }
  setTimeout(() => {
    currentMuscleId.value = null;
    currentMuscleName.value = '';
    muscleDetailData.value = { muscleId: 0, dailyStatsList: [] };
    muscleFullDates.value = [];
    muscleProcessedData.value = { volumeArr: [], setsArr: [] };
  }, 150);
}

// 处理好的容量数组(已对齐完整日期)
const muscleVolumeArr = computed(() => {
  return muscleProcessedData.value.volumeArr || []
})

// 处理好的组数数组(已对齐完整日期)
const muscleSetsArr = computed(() => {
  return muscleProcessedData.value.setsArr || []
})

// 弹窗图表的类目(周:周一到周日 / 月:具体日期)
const muscleChartCategories = computed(() => {
  if (MainCurrentDateType.value === 'week') {
    return ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  } else {
    // 月模式:如果日期列表为空,返回空数组避免报错
    if (!muscleFullDates.value.length) return []
    return muscleFullDates.value.map(d => `${d.getMonth() + 1}/${d.getDate()}`)
  }
})

// 弹窗图表数据:根据 muscleTabIndex 只显示容量或组数
const muscleChartSeries = computed(() => {
  const data = muscleTabIndex.value === 0
    ? muscleVolumeArr.value
    : muscleSetsArr.value

  // 兜底:如果数据为空,返回空数组
  if (!data || !data.length) {
    return [{
      name: muscleTabIndex.value === 0 ? '容量' : '组数',
      data: [],
      color: muscleTabIndex.value === 0 ? '#ffc53d' : '#5b8ff9'
    }]
  }

  return [{
    name: muscleTabIndex.value === 0 ? '容量' : '组数',
    data: data,
    color: muscleTabIndex.value === 0 ? '#ffc53d' : '#5b8ff9'
  }]
})


// 事件方法
const onPartChange = (item) => {
  console.log('选中的项:', item);
  partId.value = item.id;
  if (MainCurrentDateType.value === 'week') {
    loadWeeklyByCategory(startDate.value);
  } else {
    loadMonthlyByCategory(startDate.value);
  }
};

// 当前的日期类型周/月
const handleTypeChange = async (type) => {
  MainCurrentDateType.value = type;
  showLastPeriod.value = false;
  loadTrainingData(startDate.value, endDate.value)

  if (startDate.value) {
    if (type === 'week') {
      await loadWeeklyByCategory(startDate.value)
    } else {
      await loadMonthlyByCategory(startDate.value)
    }
  }

  // 如果弹窗打开,自动刷新肌肉数据
  if (muscleShow.value && currentMuscleId.value) {
    if (type === 'week') {
      await loadWeeklyMuscleStats(currentMuscleId.value, startDate.value)
    } else {
      await loadMonthlyMuscleStats(currentMuscleId.value, startDate.value)
    }
  }
};
// 处理日期改变
const handleDateChange = async (data) => {
  console.log(data.startDate, data.endDate);
  startDate.value = data.startDate;
  endDate.value = data.endDate;
  await loadTrainingData(startDate.value, endDate.value)
  if (MainCurrentDateType.value === 'week') {
    loadWeeklyByCategory(startDate.value);
  } else {
    loadMonthlyByCategory(startDate.value);
  }
  // 弹窗打开 → 刷新肌肉详情
  if (muscleShow.value && currentMuscleId.value) {
    if (MainCurrentDateType.value === 'week') {
      await loadWeeklyMuscleStats(currentMuscleId.value, startDate.value)
    } else {
      await loadMonthlyMuscleStats(currentMuscleId.value, startDate.value)
    }
  }
};
// 处理是否返回上周/月
const toggleLastWeek = () => {
  showLastPeriod.value = !showLastPeriod.value
  if (startDate.value) {
    if (MainCurrentDateType.value === 'week') {
      loadWeeklyByCategory(startDate.value)
    } else {
      loadMonthlyByCategory(startDate.value)
    }
  }
}

onMounted(async () => {
  await loadbodyPartOptions();
  await loadGetSubCategorieList();
  if (startDate.value && endDate.value) {
    await loadTrainingData(startDate.value, endDate.value)
    if (MainCurrentDateType.value === 'week') {
      await loadWeeklyByCategory(startDate.value)
    } else {
      await loadMonthlyByCategory(startDate.value)
    }
  }

});
</script>

<style lang="scss" scoped>
.training-data-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 30rpx 24rpx 0;
  box-sizing: border-box;
  overflow: auto;

  .content-scroll {
    height: calc(100vh - 400rpx);
    width: 100%;
    box-sizing: border-box;
    overflow: auto;
  }

  .section {
    padding: 30rpx 20rpx;
    box-sizing: border-box;
    background-color: #fff;
    border-radius: 15rpx;
    margin-top: 20rpx;

    &:last-child {
      padding-bottom: env(safe-area-inset-bottom);
      margin-bottom: 110rpx;
    }

    .title {
      font-size: 30rpx;
      font-weight: bold;
      margin-bottom: 20rpx;
    }

    .tip {
      font-size: 22rpx;
      margin-bottom: 20rpx;
    }

    .img {
      width: 100%;
      height: 400rpx;
    }

    .tabs {
      display: flex;
      gap: 20rpx;

      .tab {
        border: 1rpx solid #eee;
        border-radius: 50rpx;
        background-color: #fff;
        padding: 10rpx 20rpx;
        font-size: 24rpx;
        margin-bottom: 20rpx;

        &.active {
          background-color: #202932;
          color: #fff;
          border: none;
        }
      }
    }

    /* ========== 核心网格布局 已修复 ========== */
    .detail-part {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 5rpx;

      .part-item {
        width: 100%;
        height: 140rpx;
        // aspect-ratio: 1 / 1;
        /* 强制正方形 */
        background-color: #eee;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        font-size: 24rpx;
        gap: 10rpx;
        border-radius: 5rpx;

        .num {
          font-weight: bold;
          color: #000;
        }
      }

      /* 总计自适应占格 */
      .total-item {
        grid-column: span var(--remain-span);
        height: 140rpx;
      }
    }

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .statistical {
      width: 100%;
      height: 400rpx;
    }

    .chose {
      font-size: 24rpx;
    }

    .compare {
      margin-top: 30rpx;

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

        .title {
          font-size: 36rpx;
          font-weight: bold;
          color: #333;
        }

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

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

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

              &.blue {
                background-color: #5b8ff9;
              }

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

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

        .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: #333;
              text-align: center;
            }

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

              &.diff {
                color: #666;
              }

              &.negative {
                color: #ff7875;
              }
            }
          }
        }
      }
    }
  }

  .muscleShow-popup {
    min-height: 40vh;
    background-color: #fff;

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

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

      .tab {
        border: 1rpx solid #eee;
        border-radius: 50rpx;
        background-color: #fff;
        padding: 10rpx 20rpx;
        font-size: 24rpx;

        &.active {
          background-color: #202932;
          color: #fff;
          border: none;
        }
      }
    }

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

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