dongzuo.vue 33.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 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
<template>
  <view class="action-container" @click="closeDifficulty">
    <view class="action-list" v-if="deleteActionShow === false">
      <view class="card" :class="{ 'unit-active': isUnitActive }">
        <view class="card-top" @click.stop="isExpanded = !isExpanded">
          <view v-if="type === 1">
            <image class="action-image" :src="actionDetail?.urlImage || lostImage" mode="aspectFill"></image>
          </view>
          <view v-if="type === 2">
            <image class="action-image"
              src="https://fitness-hcxtec-bucket.oss-cn-shenzhen.aliyuncs.com/20260507/超级组_1778117889451.png"
              mode="aspectFill"></image>
          </view>
          <view class="action-info">
            <text class="name">{{ actionDetail?.name }}</text>
            <text class="tags" v-if="type === 1">{{ actionDetail?.categoryDescription }} {{
              actionDetail?.equipmentDescription }}</text>
            <text class="tags" v-if="type === 2">超级组</text>
            <view class="dot-list" v-if="!isExpanded">
              <view class="dot" v-for="(item, index) in recordList" :key="'dot-' + index"></view>
            </view>
          </view>
          <view class="more-circle" @click.stop="toggleTips">
            <up-icon name="more-dot-fill" color="#fff" size="15" class="icon"></up-icon>
            <view class="tips" v-if="showTips">
              <view class="tip" @click="openBeizhu">文字备注</view>
              <view class="tip" @click="openAllQuickTimer">组间休息</view>
              <view class="tip" @click="handleReplaceAction">动作替换</view>
              <view class="tip" @click="deleteAction">删除动作</view>
            </view>
          </view>
        </view>

        <view class="main" v-if="isExpanded">
          <template v-if="type === 1">
            <view class="userWeight" v-if="[4, 5].includes(actionDetail.exerciseType)">
              <view class="row" hover-class="none" hover-stop-propagation="false">
                <text class="label">体重</text>
                <view class="userWeight-values" @click="openWeightPicker">
                  <text class="weight-text">{{ displayWeight }}</text>
                  <up-icon name="edit-pen" color="#8e8e93" size="20"></up-icon>
                </view>
              </view>
              <view class="explain" v-if="actionDetail?.exerciseType === 4">
                该动作为自重加重,根据你的体重加上辅助器械重量计算容量,下方的填写重量为辅助器械重量。
              </view>
              <view class="explain" v-if="actionDetail?.exerciseType === 5">
                该动作为自重减重,根据你的体重减去辅助器械重量计算容量,下方的填写重量为辅助器械重量。
              </view>
            </view>
            <action-set-input v-for="(item, index) in recordList" :key="index"
              :exercise-type="actionDetail.exerciseType" :record="item" :index="index" :is-editing="isEditing"
              @openPicker="openPicker" @openQuickTimer="openQuickTimer" @toggleActive="toggleActive" @addRow="addRow"
              @deleteRow="deleteRow" :user-weight="userWeight" @change-weight="userWeight = $event" :isTick="isTick"/>
          </template>

          <template v-else-if="type === 2">
            <view class="super-group">
              <view class="img-list" v-if="type === 2">
                <image v-for="item in (actionDetail?.exercises || [])" :key="item.id" :src="item?.urlImage || lostImage"
                  class="img"></image>
              </view>
              <view class="userWeight" v-if="hasWeightExercise">
                <view class="row">
                  <text class="label">体重</text>
                  <view class="userWeight-values" @click="openWeightPicker">
                    <text class="weight-text">{{ displayWeight }}</text>
                    <up-icon name="edit-pen" color="#8e8e93" size="20"></up-icon>
                  </view>
                </view>
              </view>
              <view class="set-group" v-for="(setItem, setIndex) in superTotalSets" :key="setIndex">
                <view class="set-header">
                  <view class="index-box">{{ setIndex + 1 }}</view>
                  <view class="set-action-names">
                    <text v-for="(sub, idx) in actionDetail.exercises" :key="sub.id">
                      {{ String.fromCharCode(65 + idx) }} {{ sub.name }}
                    </text>
                  </view>
                  <view class="timer-selector" @click.stop="openSuperQuickTimer(setIndex)" v-if="!isEditing">
                    <text class="text">{{ superGroupSetData(setIndex).quickTimeDisplay || '60s' }}</text>
                    <up-icon name="arrow-down" color="#8e8e93" size="10"></up-icon>
                  </view>
                  <view class="check-icon" @click.stop="toggleSuperSetActive(setIndex)"
                    :class="{ active: superGroupSetData(setIndex).isActive }" v-if="!isEditing">
                    <up-icon name="checkmark" :color="superGroupSetData(setIndex).isActive ? '#000' : '#919191'"
                      size="20" bold></up-icon>
                  </view>
                  <view class="action-icons" v-if="isEditing">
                    <view class="action-icon" @click.stop="addSuperSet">
                      <up-icon name="plus-circle" color="#fff" size="20" bold></up-icon>
                    </view>
                    <view class="action-icon icon-del" @click.stop="deleteSuperSet(setIndex)">
                      <up-icon name="trash" color="#e63e1e" size="20" bold></up-icon>
                    </view>
                  </view>
                </view>
                <super-set-input v-for="(sub, idx) in actionDetail.exercises" :key="sub.id"
                  :sub-exercise-type="sub.exerciseType" :set-index="setIndex" :sub-index="idx" :user-weight="userWeight"
                  :data="getSubActionData(setIndex, sub.id)" @open-time-picker="openSuperPicker(setIndex, sub.id)" :isTick="isTick"/>
              </view>
            </view>
          </template>
        </view>

        <view class="button-group" v-if="isExpanded">
          <view class="btn-item" @click.stop="addGroup">加一组</view>
          <view class="btn-item" @click="openHistory(props?.id)">历史</view>
          <actionHistory ref="historyPopupRef" :actionName="actionDetail.name" :historyType="props.type" />
          <view class="btn-item" @click.stop="showDifficulty = !showDifficulty">
            <text :style="{ color: currentDifficulty.color }">{{ currentDifficulty.label }}</text>
            <up-icon name="arrow-down" size="8" color="#fff"></up-icon>
            <view class="difficulty-pop" v-if="showDifficulty">
              <view class="difficulty-item" @click.stop="selectDifficulty('轻松', '#b2f055')">
                <text :style="{ color: '#b2f055' }">轻松</text>
                <up-icon v-if="currentDifficulty.label === '轻松'" name="checkmark" color="#b2f055" size="16"
                  bold></up-icon>
              </view>
              <view class="difficulty-item" @click.stop="selectDifficulty('正常', '#ffffff')">
                <text :style="{ color: '#ffffff' }">正常</text>
                <up-icon v-if="currentDifficulty.label === '正常'" name="checkmark" color="#ffffff" size="16"
                  bold></up-icon>
              </view>
              <view class="difficulty-item" @click.stop="selectDifficulty('困难', '#e26c2a')">
                <text :style="{ color: '#e26c2a' }">困难</text>
                <up-icon v-if="currentDifficulty.label === '困难'" name="checkmark" color="#e26c2a" size="16"
                  bold></up-icon>
              </view>
            </view>
          </view>
          <view class="btn-item" @click.stop="isEditing = !isEditing">
            {{ isEditing ? '完成' : '编辑' }}
          </view>
        </view>
      </view>
    </view>

    <up-picker :show="showPicker" :columns="timeColumns" :defaultIndex="defaultTimeIndex" title="请选择运动时长"
      @confirm="onTimeConfirm" @cancel="showPicker = false" closeOnClickOverlay popupClass="custom-picker"></up-picker>

    <up-picker :show="showQuickPicker" :columns="quickColumns" title="设置休息时长" @confirm="onQuickConfirm"
      @cancel="showQuickPicker = false" closeOnClickOverlay popupClass="custom-picker"></up-picker>

    <beizhu ref="showBeizhuRef" @saveSuccess="handleNoteSave" />
    <replaceActionPopup :show="replacePopupShow" :unitIndex="unitIndex" @close="replacePopupShow = false" />

    <up-picker :show="showWeightPicker" :columns="weightColumns" :defaultIndex="defaultWeightIndex" title="设置体重"
      @confirm="onWeightConfirm" @cancel="showWeightPicker = false" closeOnClickOverlay
      popupClass="custom-picker"></up-picker>
  </view>
</template>

<script setup>
import { ref, reactive, watch, computed, nextTick, onMounted, getCurrentInstance } from 'vue';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { useTrainingStore } from '@/sheep/store/trainingStore'
import beizhu from '@/pages/xunji/components/beizhu.vue';
import actionHistory from '@/pages/xunji/components/dongzuo-lianxi/dongzuo-lianxi-history.vue'
import replaceActionPopup from '@/pages/xunji/components/dongzuo-lianxi/replace-action-popup.vue'
import actionSetInput from '@/pages/xunji/components/dongzuo-lianxi/action-set-input.vue'
import superSetInput from '@/pages/xunji/components/dongzuo-lianxi/super-set-input.vue'
import SupersetsApi from '@/sheep/api/motion/supersets';
import ExercisesApi from '@/sheep/api/motion/exercises';

// ===================== Props =====================
const props = defineProps({
  id: [Number, String],
  type: [Number, String],
  index: Number,
  unitIndex: Number,
  actionDetail: { type: Object, default: () => ({}) },
  isDailyTemplates: { type: Boolean, default: false },
  isUnitActive: { type: Boolean, default: false },
  isTick: { type: Boolean, default: true },
})

// ===================== Emits =====================
const emit = defineEmits(['register', 'update:groupCount', 'replace-action', 'deleteAction', 'replaceActionForSave', 'startRestTimer', 'cancelRestTimer', 'updateUnitActive'])

// ===================== 常量 =====================
dayjs.extend(duration)
const lostImage = 'https://fitness-hcxtec-bucket.oss-cn-shenzhen.aliyuncs.com/20260316/order-empty_1773628059920.png'

// ===================== Store =====================
const trainingStore = useTrainingStore()

// ===================== 基础状态 =====================
const deleteActionShow = ref(false)
const showTips = ref(false)
const isExpanded = ref(false)
const isEditing = ref(false)
const replacePopupShow = ref(false)
const historyPopupRef = ref(null)
const showBeizhuRef = ref(null)

// ===================== Picker 状态 =====================
const showPicker = ref(false)
const showQuickPicker = ref(false)
const activeIndex = ref(0)
const activeActionId = ref('')
const restEditMode = ref('single')

const timeColumns = reactive([
  Array.from({ length: 24 }, (_, i) => String(i).padStart(2, '0') + '时'),
  Array.from({ length: 60 }, (_, i) => String(i).padStart(2, '0') + '分'),
  Array.from({ length: 60 }, (_, i) => String(i).padStart(2, '0') + '秒'),
])
const defaultTimeIndex = ref([0, 0, 0])

const quickColumns = reactive([
  Array.from({ length: 60 }, (_, i) => String(i).padStart(2, '0') + '分'),
  Array.from({ length: 60 }, (_, i) => String(i).padStart(2, '0') + '秒'),
])

// ===================== 体重 =====================
const userWeight = ref(70)
const showWeightPicker = ref(false)
const weightColumns = reactive([
  Array.from({ length: 241 }, (_, i) => (i + 10).toString()),
  Array.from({ length: 10 }, (_, i) => i.toString()),
  ['千克(kg)']
])
const defaultWeightIndex = ref([60, 0, 0])

// ===================== 难度 =====================
const showDifficulty = ref(false)
const initialDifficulty = { label: '难度', color: '#ffffff' }
const currentDifficulty = ref({ ...initialDifficulty })

// ===================== 训练数据 =====================
const recordList = ref([{
  h: '00', m: '00', s: '00', quickTimeDisplay: formatQuickTime(60),
  distance: '', weight: '', reps: '', duration: '', restTime: '', isActive: false
}])

const superRecordMap = ref({})

// 向父组件注册组件实例引用
emit('register', props.index, getCurrentInstance()?.proxy)

// ===================== Computed =====================
const displayWeight = computed(() => `${userWeight.value}kg`)

const hasWeightExercise = computed(() => {
  if (props.type !== 2) return false
  return (props.actionDetail?.exercises || []).some(sub => [4, 5].includes(sub.exerciseType))
})

const superTotalSets = computed(() => {
  if (props.type !== 2) return 0
  const exercises = props.actionDetail?.exercises || []
  if (exercises.length === 0) return 0
  return superRecordMap.value[exercises[0].id]?.length || 0
})

const exerciseNamesWithLabel = computed(() => {
  return (props.actionDetail?.exercises || []).map((item, index) => {
    const label = String.fromCharCode(65 + index)
    return `${label} ${item?.name || '未知动作'}`
  })
})

const exposeRecordList = computed(() => {
  // 每日模板编辑场景需要全量数据,不受 isActive 过滤影响
  if (props.isDailyTemplates) {
    return recordList.value.map(item => ({
      ...item,
      weight: getRealWeight(item)
    }))
  }
  return recordList.value.filter(item => item.isActive).map(item => ({
    ...item,
    weight: getRealWeight(item)
  }))
})

const exposeSuperRecordMap = computed(() => {
  const map = {}
  for (const key in superRecordMap.value) {
    const subExercise = props.actionDetail?.exercises?.find(s => s.id == key)
    // 每日模板编辑场景需要全量数据,不受 isActive 过滤影响
    const list = props.isDailyTemplates
      ? superRecordMap.value[key]
      : superRecordMap.value[key]?.filter(item => item.isActive)
    map[key] = (list || []).map(item => ({ ...item, weight: getRealWeight(item, subExercise?.exerciseType) }))
  }
  return map
})

const totalSetCount = computed(() => {
  if (props.type === 1) return recordList.value.length
  if (props.type === 2) {
    const exercises = props.actionDetail?.exercises || []
    if (exercises.length === 0) return 0
    return superRecordMap.value[exercises[0].id]?.length || 0
  }
  return 0
})

const checkedWeight = computed(() => {
  let sum = 0
  if (props.type === 1 && recordList.value) {
    recordList.value.forEach(item => {
      if (item.isActive) sum += getRealWeight(item) * (Number(item.reps) || 0)
    })
  }
  if (props.type === 2 && superRecordMap.value) {
    for (const actionId in superRecordMap.value) {
      const subExercise = props.actionDetail?.exercises?.find(s => s.id == actionId)
      superRecordMap.value[actionId].forEach(item => {
        if (item.isActive) sum += getRealWeight(item, subExercise?.exerciseType) * (Number(item.reps) || 0)
      })
    }
  }
  return sum
})

const totalWeight = computed(() => {
  let sum = 0
  if (props.type === 1 && recordList.value) {
    recordList.value.forEach(item => {
      sum += getRealWeight(item) * (Number(item.reps) || 0)
    })
  }
  if (props.type === 2 && superRecordMap.value) {
    for (const actionId in superRecordMap.value) {
      const subExercise = props.actionDetail?.exercises?.find(s => s.id == actionId)
      superRecordMap.value[actionId].forEach(item => {
        sum += getRealWeight(item, subExercise?.exerciseType) * (Number(item.reps) || 0)
      })
    }
  }
  return sum
})

// ===================== 工具函数 =====================
function getRealWeight(item, subExerciseType = null) {
  const userW = Number(userWeight.value) || 0
  const inputW = Number(item.weight) || 0
  const type = subExerciseType ?? props.actionDetail?.exerciseType

  if (type === 0) return inputW
  if (type === 4) return userW + inputW
  if (type === 5) return Math.max(0, userW - inputW)
  return 0
}

function superGroupSetData(setIndex) {
  const firstSub = props.actionDetail?.exercises?.[0]
  if (!firstSub) return {}
  return superRecordMap.value[firstSub.id]?.[setIndex] || {}
}

function getSubActionData(setIndex, actionId) {
  return superRecordMap.value[actionId]?.[setIndex] || {
    h: '00', m: '00', s: '00', quickTimeDisplay: formatQuickTime(60),
    distance: '', weight: '', reps: '', duration: '', restTime: '', isActive: false
  }
}

function formatQuickTime(totalSeconds) {
  const dur = dayjs.duration(totalSeconds * 1000)
  const minutes = Math.floor(dur.asMinutes())
  const seconds = dur.seconds()
  if (minutes > 0) return `${minutes}分${seconds > 0 ? seconds + '秒' : ''}`
  return `${seconds}s`
}

function parseQuickTime(display) {
  if (!display) return 60
  // 匹配 "X分Y秒" / "X分" / "Ys"
  const full = display.match(/^(\d+)分(\d+)秒$/)
  if (full) return parseInt(full[1]) * 60 + parseInt(full[2])
  const minOnly = display.match(/^(\d+)分$/)
  if (minOnly) return parseInt(minOnly[1]) * 60
  const secOnly = display.match(/^(\d+)s$/)
  if (secOnly) return parseInt(secOnly[1])
  return 60
}

function saveToStore() {
  let records = {}
  if (props.type === 1) {
    records[props.actionDetail.id] = recordList.value
  } else if (props.type === 2) {
    records = superRecordMap.value
  }
  trainingStore.saveUnitRecord(props.unitIndex, { records, userWeight: userWeight.value })
}

// ===================== UI 交互 =====================
function toggleTips() {
  showTips.value = !showTips.value
}

function closeDifficulty() {
  showDifficulty.value = false
  showTips.value = false
}

function selectDifficulty(label, color) {
  if (currentDifficulty.value.label === label) {
    currentDifficulty.value = { ...initialDifficulty }
  } else {
    currentDifficulty.value = { label, color }
  }
  showDifficulty.value = false
}

function toggleActive(index) {
  const wasActive = recordList.value[index].isActive
  // 在状态改变前获取当前组的休息秒数,用于取消时传递给父组件
  const seconds = parseQuickTime(recordList.value[index].quickTimeDisplay)
  recordList.value[index].isActive = !recordList.value[index].isActive
  const hasAnyActive = recordList.value.some(item => item.isActive)
  emit('updateUnitActive', hasAnyActive)
  if (recordList.value[index].isActive) {
    emit('startRestTimer', seconds, props.unitIndex)
  } else if (wasActive) {
    emit('cancelRestTimer', seconds, props.unitIndex)
  }
}

function toggleSuperSetActive(setIndex) {
  const wasActive = superGroupSetData(setIndex).isActive
  // 在状态改变前获取当前组的休息秒数,用于取消时传递给父组件
  const restSeconds = parseQuickTime(superGroupSetData(setIndex).quickTimeDisplay)
  props.actionDetail.exercises.forEach(sub => {
    const list = superRecordMap.value[sub.id]
    if (list?.[setIndex]) list[setIndex].isActive = !list[setIndex].isActive
  })
  const hasAnyActive = props.actionDetail.exercises.some(sub =>
    superRecordMap.value[sub.id]?.some(item => item.isActive)
  )
  emit('updateUnitActive', hasAnyActive)
  if (!wasActive) {
    emit('startRestTimer', restSeconds, props.unitIndex)
  } else {
    emit('cancelRestTimer', restSeconds, props.unitIndex)
  }
}

// 供父组件调用:取消该组件内所有勾选
function resetActiveSets() {
  recordList.value.forEach(item => { item.isActive = false })
  for (const key in superRecordMap.value) {
    superRecordMap.value[key]?.forEach(item => { item.isActive = false })
  }
  emit('updateUnitActive', false)
}

// ===================== 体重选择器 =====================
function openWeightPicker() {
  const num = userWeight.value
  const intIndex = Math.max(0, Math.min(Math.floor(num) - 10, 240))
  const decPart = Math.round((num - Math.floor(num)) * 10)
  defaultWeightIndex.value = [intIndex, decPart, 0]
  showWeightPicker.value = true
}

function onWeightConfirm(e) {
  userWeight.value = parseFloat(`${e.value[0]}.${e.value[1]}`)
  showWeightPicker.value = false
}

// ===================== 备注 =====================
function openBeizhu() {
  nextTick(() => {
    if (showBeizhuRef.value) showBeizhuRef.value.open(props.actionDetail.id)
  })
}

async function handleNoteSave(content) {
  try {
    if (props.type == 2) {
      await SupersetsApi.addNotes({ supersetsId: props.id, content })
    } else {
      await ExercisesApi.addNotes({ exerciseId: props.id, content })
    }
    props.actionDetail.userNote = content
  } catch (e) {
    // 静默处理
  }
}

// ===================== 替换/删除动作 =====================
function handleReplaceAction() {
  showTips.value = false
  replacePopupShow.value = true
}

function deleteAction() {
  if (props.isDailyTemplates) {
    showTips.value = false
    emit('deleteAction')
    return
  }
  trainingStore.deleteUnitRecord(props.unitIndex)
  deleteActionShow.value = true
  if (trainingStore.type === 3) {
    trainingStore.actionDetail.units.splice(props.unitIndex, 1)
  } else {
    trainingStore.clearTrainingStore()
  }
  showTips.value = false
}

// ===================== 时间选择器 =====================
function openPicker(index) {
  activeIndex.value = index
  const item = recordList.value[index]
  defaultTimeIndex.value = [
    timeColumns[0].indexOf(item.h + '时'),
    timeColumns[1].indexOf(item.m + '分'),
    timeColumns[2].indexOf(item.s + '秒')
  ]
  showPicker.value = true
}

function openQuickTimer(index) {
  activeIndex.value = index
  showQuickPicker.value = true
}

function openAllQuickTimer() {
  restEditMode.value = 'all'
  showQuickPicker.value = true
}

function openSuperPicker(setIndex, actionId) {
  activeIndex.value = setIndex
  activeActionId.value = actionId
  showPicker.value = true
}

function openSuperQuickTimer(setIndex) {
  activeIndex.value = setIndex
  showQuickPicker.value = true
}

function onTimeConfirm(e) {
  const rawValues = e.value.map(val => String(val).replace(/[时分秒]/g, ''))
  const setIdx = activeIndex.value

  if (props.type === 1) {
    const item = recordList.value[setIdx]
    item.h = rawValues[0]; item.m = rawValues[1]; item.s = rawValues[2]
  } else if (props.type === 2) {
    const list = superRecordMap.value[activeActionId.value]
    if (list?.[setIdx]) {
      list[setIdx].h = rawValues[0]; list[setIdx].m = rawValues[1]; list[setIdx].s = rawValues[2]
    }
  }
  showPicker.value = false
}

function onQuickConfirm(e) {
  const totalSeconds = dayjs.duration({
    minutes: parseInt(e.value[0]) || 0,
    seconds: parseInt(e.value[1]) || 0
  }).asSeconds()
  const setIdx = activeIndex.value

  if (restEditMode.value === 'all') {
    if (props.type === 1) {
      recordList.value.forEach(item => { item.quickTimeDisplay = formatQuickTime(totalSeconds) })
    } else if (props.type === 2) {
      const firstSub = props.actionDetail?.exercises?.[0]
      if (firstSub) {
        superRecordMap.value[firstSub.id]?.forEach(set => { set.quickTimeDisplay = formatQuickTime(totalSeconds) })
      }
    }
  } else {
    if (props.type === 1) {
      recordList.value[setIdx].quickTimeDisplay = formatQuickTime(totalSeconds)
    } else if (props.type === 2) {
      props.actionDetail.exercises.forEach(sub => {
        const list = superRecordMap.value[sub.id]
        if (list?.[setIdx]) list[setIdx].quickTimeDisplay = formatQuickTime(totalSeconds)
      })
    }
  }
  restEditMode.value = 'single'
  showQuickPicker.value = false
}

// ===================== 增删行/组 =====================
function addRow() {
  const last = recordList.value[recordList.value.length - 1]
  const newItem = last ? JSON.parse(JSON.stringify(last)) : {
    h: '00', m: '00', s: '00', quickTimeDisplay: formatQuickTime(60),
    distance: '', weight: '', reps: '', duration: '', restTime: '', isActive: false
  }
  newItem.isActive = false
  recordList.value.push(newItem)
}

function deleteRow(index) {
  if (recordList.value.length > 1) {
    recordList.value.splice(index, 1)
  } else {
    uni.showToast({ title: '至少保留一行数据', icon: 'none' })
  }
}

function addSuperSet() {
  (props.actionDetail?.exercises || []).forEach(sub => {
    if (superRecordMap.value[sub.id]) {
      const list = superRecordMap.value[sub.id]
      const last = list[list.length - 1]
      const newItem = last ? JSON.parse(JSON.stringify(last)) : {
        h: '00', m: '00', s: '00', quickTimeDisplay: formatQuickTime(60),
        distance: '', weight: '', reps: '', duration: '', restTime: '', isActive: false
      }
      newItem.isActive = false
      list.push(newItem)
    }
  })
}

function deleteSuperSet(setIndex) {
  const exercises = props.actionDetail?.exercises || []
  if (!exercises.length) return
  const list = superRecordMap.value[exercises[0].id] || []
  if (list.length <= 1) {
    uni.showToast({ title: '至少保留一组数据', icon: 'none' })
    return
  }
  exercises.forEach(sub => {
    const list = superRecordMap.value[sub.id]
    if (list && list.length > 1) list.splice(setIndex, 1)
  })
}

function addGroup() {
  if (props.type === 1) addRow()
  else if (props.type === 2) addSuperSet()
}

// ===================== 历史 =====================
function openHistory(id) {
  if (historyPopupRef.value?.openHistoryPopup) {
    historyPopupRef.value.openHistoryPopup(id)
  }
}

// ===================== Watchers =====================
watch(recordList, () => {
  emit('update:groupCount', recordList.value.length)
}, { deep: true, immediate: true })

watch([recordList, superRecordMap, userWeight], saveToStore, { deep: true })

watch(
  () => [recordList.value, superRecordMap.value],
  () => {
    const userW = userWeight.value || 0
    if (props.type === 1 && props.actionDetail?.exerciseType === 5) {
      recordList.value.forEach(item => {
        if ((Number(item.weight) || 0) > userW) {
          item.weight = ''
          uni.showToast({ title: '辅助重量不能超过体重', icon: 'none', duration: 2000 })
        }
      })
    }
    if (props.type === 2) {
      props.actionDetail?.exercises?.forEach(sub => {
        if (sub.exerciseType === 5) {
          (superRecordMap.value[sub.id] || []).forEach(item => {
            if ((Number(item.weight) || 0) > userW) {
              item.weight = ''
              uni.showToast({ title: '辅助重量不能超过体重', icon: 'none', duration: 2000 })
            }
          })
        }
      })
    }
  },
  { deep: true }
)

// ===================== Lifecycle =====================
onMounted(() => {
  const savedData = trainingStore.getUnitRecord(props.unitIndex)
  userWeight.value = savedData.userWeight || 70

  if (props.type === 1) {
    if (savedData.records?.[props.actionDetail.id]) {
      recordList.value = [...savedData.records[props.actionDetail.id]]
    }
  } else if (props.type === 2) {
    if (savedData.records && Object.keys(savedData.records).length > 0) {
      superRecordMap.value = { ...savedData.records }
    }
  }

  // 超级组兜底初始化
  if (props.type === 2 && props.actionDetail?.exercises?.length) {
    const exercises = props.actionDetail.exercises
    if (!superRecordMap.value[exercises[0].id]) {
      const map = {}
      exercises.forEach(item => {
        map[item.id] = [{
          h: '00', m: '00', s: '00', quickTimeDisplay: formatQuickTime(60),
          distance: '', weight: '', reps: '', duration: '', restTime: '', isActive: false
        }]
      })
      superRecordMap.value = map
    }
  }

  nextTick(() => {
    emit('register', props.index, {
      recordList: recordList.value,
      superRecordMap: superRecordMap.value
    })
  })
})

// ===================== Expose =====================
defineExpose({
  recordList: exposeRecordList,
  superRecordMap: exposeSuperRecordMap,
  totalSetCount,
  checkedWeight,
  totalWeight,
  resetActiveSets
})
</script>

<style lang="scss" scoped>
// ===================== 变量 =====================
$bg-black: #303030;
$card-bg: #1c1c1e;
$item-bg: #2c2c2e;
$input-bg: #1f1f1f;
$popup-bg: #3e3e3e;
$text-main: #ffffff;
$text-gray: #8e8e93;
$text-dim: #929292;
$theme-yellow: #f8d714;

// ===================== 公共:序号框 =====================
@mixin index-box {
  width: 50rpx;
  height: 70rpx;
  background: $input-bg;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
  color: $text-main;
}

// ===================== 公共:计时选择器 =====================
@mixin timer-selector {
  width: 75rpx;
  height: 75rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  border: 1rpx solid #a4a4a4;

  .text {
    font-size: 20rpx;
    color: $text-gray;
  }
}

// ===================== 公共:操作图标按钮 =====================
@mixin action-icon-base {
  width: 70rpx;
  height: 70rpx;
  background-color: $input-bg;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  &.active {
    background-color: $theme-yellow;
  }
}

// ===================== 容器 =====================
.action-container {
  width: 100%;
  background-color: $bg-black;



  .action-list {
    width: 100%;

    .card {
      border-radius: 24rpx;
      margin-bottom: 20rpx;
      padding-bottom: 20rpx;

      &.unit-active {
        background-color: #4c4d3b;
      }

      .card-top {
        display: flex;
        align-items: center;
        padding: 20rpx 30rpx 0;
        box-sizing: border-box;

        .action-image {
          width: 110rpx;
          height: 110rpx;
          border-radius: 16rpx;
          background-color: #3a3a3c;
        }

        .action-info {
          flex: 1;
          margin-left: 24rpx;

          .name {
            font-size: 34rpx;
            font-weight: 600;
            color: $text-main;
          }

          .tags {
            font-size: 24rpx;
            color: $text-gray;
            margin-top: 6rpx;
            margin-left: 6rpx;
          }

          .dot-list {
            display: flex;
            gap: 10rpx;
            margin-top: 8rpx;

            .dot {
              width: 10rpx;
              height: 10rpx;
              border-radius: 50%;
              background-color: $text-main;
            }
          }
        }

        .more-circle {
          width: 60rpx;
          height: 60rpx;
          background: $item-bg;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 1rpx solid #a4a4a4;
          position: relative;

          .icon {
            transform: rotate(90deg);
          }

          .tips {
            position: absolute;
            color: #fff;
            background-color: $popup-bg;
            z-index: 6;
            right: 10rpx;
            top: 20rpx;
            border-radius: 10rpx;

            .tip {
              width: 120rpx;
              height: 40rpx;
              padding: 20rpx 30rpx;
              text-align: center;
              font-size: 24rpx;
              line-height: 40rpx;
            }
          }
        }
      }

      .main {
        width: 100%;
        margin-top: 20rpx;

        .img-list {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          gap: 20rpx;
          padding: 20rpx;
          box-sizing: border-box;

          .img {
            width: 120rpx;
            height: 120rpx;
            border-radius: 10rpx;
          }
        }

        .userWeight {
          padding: 16rpx 32rpx;
          gap: 16rpx;

          .row {
            display: flex;
            align-items: center;
            gap: 16rpx;

            .label {
              font-size: 20rpx;
              color: $text-main;
              font-weight: 500;
            }

            .userWeight-values {
              display: flex;
              align-items: center;
              gap: 8rpx;
              padding: 8rpx;

              .weight-text {
                color: #fadc00;
                font-size: 20rpx;
              }
            }
          }

          .explain {
            font-size: 20rpx;
            color: $text-main;
          }
        }

        .super-group {
          width: 100%;
        }
      }

      // 超级组:每组标题行
      .set-group {
        margin-bottom: 30rpx;
      }

      .set-header {
        display: flex;
        align-items: center;
        padding: 10rpx 30rpx;
        gap: 20rpx;

        .index-box {
          @include index-box;
        }

        .set-action-names {
          flex: 1;
          display: flex;
          flex-direction: column;
          gap: 4rpx;

          text {
            font-size: 26rpx;
            color: $text-main;
          }
        }

        .timer-selector {
          @include timer-selector;
        }

        .check-icon {
          @include action-icon-base;
        }

        .action-icons {
          display: flex;
          gap: 20rpx;

          .action-icon {
            @include action-icon-base;

            &.icon-del {
              background-color: #58372d;
            }
          }
        }
      }

      // 按钮组
      .button-group {
        display: flex;
        justify-content: space-between;
        padding: 30rpx;
        box-sizing: border-box;
        gap: 10rpx;

        .btn-item {
          background-color: $input-bg;
          font-size: 26rpx;
          color: $text-main;
          padding: 15rpx 35rpx;
          border-radius: 50rpx;
          display: flex;
          align-items: center;
          gap: 10rpx;
          position: relative;

          .difficulty-pop {
            position: absolute;
            bottom: 80rpx;
            left: 50%;
            transform: translateX(-50%);
            background-color: $popup-bg;
            border-radius: 16rpx;
            overflow: hidden;
            z-index: 99;
            box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.5);

            .difficulty-item {
              width: 180rpx;
              height: 80rpx;
              padding: 0 25rpx;
              box-sizing: border-box;
              display: flex;
              align-items: center;
              justify-content: space-between;
              font-size: 26rpx;
              border-bottom: 1rpx solid #4e4e4e;

              &:last-child {
                border-bottom: none;
              }

              &:active {
                background-color: #4e4e4e;
              }
            }
          }
        }
      }
    }
  }
}
</style>