xunji-dongzuo-xinzeng.vue 30 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 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
<template>
  <view class="add-custom-exercise-page">
    <!-- 肌肉部位图 -->
    <view class="muscle-area" @click="openMusclePicker">
      <image src="https://fitness-hcxtec-bucket.oss-cn-shenzhen.aliyuncs.com/20260424/muscle_back_1777018976173.png"
        class="muscle-image-front" mode="aspectFill" />
    </view>
    <!-- 肌肉部位选择弹窗 - 美化版 -->
    <view v-if="showMusclePicker" class="popup-overlay" @click="closeAllPopups">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <view class="close-btn" @click="closeAllPopups">x</view>
          <view class="title">选择训练部位</view>
          <view class="confirm-btn" @click="confirmMuscleSelection">完成</view>
        </view>
        <view class="muscle-list-beautified">
          <view v-for="group in muscleGroups" :key="group.id" class="muscle-item-beautified">
            <text class="muscle-name">{{ group.name }}</text>
            <!-- 主要部位按钮 -->
            <view class="selector-btn primary" :class="{ active: primaryMuscles.includes(group.id) }"
              @click.stop="togglePrimary(group.id)">
              <view class="selector-dot primary"></view>
              <text class="selector-label">主要</text>
            </view>
            <!-- 次要部位按钮 -->
            <view class="selector-btn secondary" :class="{ active: secondaryMuscles.includes(group.id) }"
              @click.stop="toggleSecondary(group.id)">
              <view class="selector-dot secondary"></view>
              <text class="selector-label">次要</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 动作名称 -->
      <view class="form-item">
        <!-- <view class="label">动作名称</view>
        <view class="input-group">
          <input v-model="exerciseName" class="input-field" placeholder="点击此处填写动作名称"
            placeholder-class="input-placeholder" />
        </view> -->
        <view class="action-name">
          <view class="label">动作名称</view>
          <view class="input-group">
            <input v-model="exerciseName" class="input-field" placeholder="点击此处填写动作名称"
              placeholder-class="input-placeholder" />
          </view>
        </view>

        <view class="upload-btn" @click="openCoverSelector">
          <image :src="coverImagePath" class="preview-media" mode="aspectFill" />
          <text class="btn-text">更换封面</text>
        </view>
      </view>
      <!--  新增:训练部位 -->
      <view class="form-item" @click="openMusclePicker">
        <view class="label">训练部位</view>
        <view class="value-wrapper">
          <text class="value">{{ selectedMusclesDisplay }}</text>
          <up-icon name="arrow-right" color="#333" size="16"></up-icon>
        </view>
      </view>

      <!-- 动作类型 -->
      <view class="form-item" @click="openActionTypePicker">
        <view class="label">动作类型</view>
        <view class="value-wrapper">
          <text class="value">{{ actionType || '请选择' }}</text>
          <!-- <image src="https://fitness-hcxtec-bucket.oss-cn-shenzhen.aliyuncs.com/20260316/order-empty_1773628059920.png"
            class="arrow-icon" mode="aspectFill" /> -->
          <up-icon v-if="!isEdit" name="arrow-right" color="#333" size="16"></up-icon>
        </view>
      </view>

      <!-- 目录管理 -->
      <view class="form-item" @click="openDirectoryPicker">
        <view class="label">目录管理</view>
        <view class="value-wrapper">
          <text class="value">{{ directoryName || '请选择' }}</text>
          <up-icon name="arrow-right" color="#333" size="16"></up-icon>
        </view>
      </view>

      <!-- 动作视频 -->
      <view class="form-item">
        <view class="label">动作视频</view>
        <view class="value-wrapper">
          <text class="value">(非必填)</text>
        </view>
        <view class="upload-btn" @click="openVideoSelector">
          <!-- <image src="https://fitness-hcxtec-bucket.oss-cn-shenzhen.aliyuncs.com/20260316/order-empty_1773628059920.png"
            class="camera-icon" mode="aspectFill" />videoFilePath.value -->
          <template v-if="videoFilePath">
            <video v-if="isVideoFile" :src="videoFilePath" class="preview-media" :controls="false"
              :show-fullscreen-btn="false" :enable-progress-gesture="false"></video>
            <!-- 图片类型 -->
            <image v-else :src="videoFilePath" class="preview-media" mode="aspectFill" />
          </template>
          <template v-else>
            <up-icon name="camera" color="#333" size="16"></up-icon>
            <text class="btn-text">图片/视频</text>
          </template>

        </view>
      </view>

      <!-- 视频详解 -->
      <view class="form-item" @click="chooseTutorialVideo">
        <view class="label">视频详解</view>
        <view class="value-wrapper">
          <text class="value">{{ videoDetailName || '上传详解视频(非必填)' }}</text>
          <view class="upload-btn">
            <template v-if="urlTutorial">
              <video :src="urlTutorial" class="preview-media" :controls="false" :show-fullscreen-btn="false"
                :enable-progress-gesture="false"></video>
            </template>
            <template v-else>
              <up-icon name="camera" color="#333" size="16" />
              <text class="btn-text">添加视频</text>
            </template>
          </view>
        </view>
      </view>

      <view class="form-item" v-if="isEdit" @click="deleteAction">
        <view class="center-label">删除动作</view>
      </view>

      <!-- 保存按钮 -->
      <view class="save-button">
        <button class="btn-save" :disabled="!exerciseName.trim()" @click="saveExercise">保存</button>
      </view>
    </view>

    <!-- 动作类型选择弹窗 -->
    <view v-if="showActionTypePicker" class="popup-overlay" @click="closeAllPopups">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <view class="close-btn" @click="closeAllPopups">×</view>
          <view class="title">选择动作类型</view>
          <view class="confirm-btn" @click="confirmActionType">确定</view>
        </view>
        <picker-view :value="[actionTypeIndex]" @change="onActionTypeChange" class="picker-view">
          <picker-view-column>
            <view class="picker-item" v-for="item in actionTypeOptions" :key="item">{{
              item.name
              }}</view>
          </picker-view-column>
        </picker-view>
      </view>
    </view>

    <!-- 目录管理弹窗 -->
    <view v-if="showDirectoryPicker" class="popup-overlay" @click="closeAllPopups">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <view class="close-btn" @click="closeAllPopups">×</view>
          <view class="title">目录管理</view>
          <view class="confirm-btn" @click="confirmDirectory">确定</view>
        </view>
        <view class="double-picker">
          <picker-view :value="[bodyPartIndex]" @change="onBodyPartChange" class="picker-view half">
            <picker-view-column>
              <view class="picker-item" v-for="item in bodyPartOptions" :key="item">{{
                item.name
                }}</view>
            </picker-view-column>
          </picker-view>
          <picker-view :value="[equipmentIndex]" @change="onEquipmentChange" class="picker-view half">
            <picker-view-column>
              <view class="picker-item" v-for="item in equipmentOptions" :key="item">{{
                item.name
                }}</view>
            </picker-view-column>
          </picker-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import ExercisesApi from '@/sheep/api/motion/exercises';
import LeftmotionApi from '@/sheep/api/motion/equipments';
import EquipmentListApi from '@/sheep/api/motion/motionequipments';
import FileApi from '@/sheep/api/infra/file';
// 表单数据
const exerciseName = ref('');
const actionType = ref();
const directoryName = ref();
const selectedMusclesDisplay = ref('未选择');
const editActionId = ref(null)

// 选中索引
const actionTypeIndex = ref(0);
const bodyPartIndex = ref(0);
const equipmentIndex = ref(0);

// 这是后端固定写死的,不要改
const actionTypeOptions = ref([
  { id: 0, name: '无氧运动' },
  { id: 1, name: '有氧运动' },
  { id: 2, name: '记次训练' },
  { id: 3, name: '计时训练' },
  { id: 4, name: '自重加重' },
  { id: 5, name: '自重减重' },
  { id: 6, name: '间歇训练' },
])
// // 加载动作分类(类型)
// const loadexercisesGroups = async () => {
//   try {
//     const res = await ExercisesApi.getAllMotionCategories();
//     actionTypeOptions.value = res.data;
//     console.log('加载动作分类', actionTypeOptions.value)
//   } catch (err) {
//     console.error('加载部位失败', err);
//   }
// };

const resetForm = () => {
  exerciseName.value = ''
  actionType.value = ''
  actionTypeIndex.value = 0
  directoryName.value = ''
  bodyPartIndex.value = 0
  equipmentIndex.value = 0
  selectedMusclesDisplay.value = '未选择'
  primaryMuscles.value = []
  secondaryMuscles.value = []
  coverImagePath.value = 'https://fitness-hcxtec-bucket.oss-cn-shenzhen.aliyuncs.com/20260316/order-empty_1773628059920.png'
  coverUploaded.value = false
  videoFilePath.value = ''
  videoUploaded.value = false
  isVideoFile.value = false
  urlTutorial.value = ''
  videoDetailName.value = ''
  // 同时关闭所有弹窗,防止上次弹窗残留
  closeAllPopups()
}

const isEdit = ref(false)
const actionDetail = ref({});

onLoad(async (options) => {

  isEdit.value = options.isEdit === 'true'
  const editId = Number(options.id)
  editActionId.value = editId
  console.log('编辑状态', isEdit, '编辑动作ID', editId)
  // 清空表单状态
  resetForm()

  await Promise.all([
    loadbodyPartOptions(),
    loadequipmentOptions(),
    loadMuscleGroups()
  ])
  if (isEdit.value) {
    loadexercisedetail(editId)
  }

})

// 加载单个动作详情
// const loadexercisedetail = async (id) => {
//   if (!id || !Number(id)) return
//   try {
//     const response = await ExercisesApi.getExerciseById(id);
//     actionDetail.value = response.data;
//     console.log('打印动作详情', actionDetail.value);
//   } catch (err) {
//     console.error('加载动作详情失败:', err)
//     actionDetail.value = {}
//   }
// };

// 加载单个动作详情并回显表单
const loadexercisedetail = async (id) => {
  if (!id || !Number(id)) return
  try {
    const response = await ExercisesApi.getExerciseById(id);
    actionDetail.value = response.data;
    const detail = actionDetail.value
    console.log('打印动作详情', detail);

    // 1. 动作名称
    exerciseName.value = detail.name || ''

    // 2. 动作类型回显(id匹配,编辑只读)
    const targetType = actionTypeOptions.value.find(item => item.id === detail.exerciseType)
    if (targetType) {
      actionTypeIndex.value = actionTypeOptions.value.findIndex(item => item.id === detail.exerciseType)
      actionType.value = targetType.name
    }

    // 3. 目录:身体部位categoryId + 器械equipmentId 匹配下标
    const bodyIdx = bodyPartOptions.value.findIndex(item => item.id === detail.categoryId)
    if (bodyIdx > -1) bodyPartIndex.value = bodyIdx

    const equipIdx = equipmentOptions.value.findIndex(item => item.id === detail.equipmentId)
    if (equipIdx > -1) equipmentIndex.value = equipIdx
    // 拼接目录展示文字
    const selBody = bodyPartOptions.value[bodyIdx]
    const selEquip = equipmentOptions.value[equipIdx]
    if (selBody && selEquip) {
      directoryName.value = ` ${selBody.name}( ${selEquip.name})`
    }

    // 4. 肌肉部位:后端返回字符串 "[30,28,29]" 转数字数组
    if (detail.primaryMuscles) {
      primaryMuscles.value = JSON.parse(detail.primaryMuscles)
    } else {
      primaryMuscles.value = []
    }
    if (detail.secondaryMuscles) {
      secondaryMuscles.value = JSON.parse(detail.secondaryMuscles)
    } else {
      secondaryMuscles.value = []
    }
    // 直接使用后端返回的拼接好的肌肉名称展示文本,不用重新拼接
    const primaryStr = detail.primaryMuscleNames?.length ? detail.primaryMuscleNames.join('、') + '(主)' : ''
    const secondaryStr = detail.secondaryMuscleNames?.length ? detail.secondaryMuscleNames.join('、') + '(次)' : ''
    let display = ''
    if (primaryStr) display += primaryStr
    if (secondaryStr) {
      if (display) display += ', '
      display += secondaryStr
    }
    selectedMusclesDisplay.value = display || '未选择'

    // 5. 封面图 url3dAnimation
    if (detail.url3dAnimation) {
      coverImagePath.value = detail.url3dAnimation
      coverUploaded.value = true // 标记已有封面,跳过新增封面校验
    }

    // 6. 动作实拍视频/图片 urlRealPerson
    if (detail.urlRealPerson) {
      videoFilePath.value = detail.urlRealPerson
      videoUploaded.value = true
      // 简单判断是否视频(后端返回mp4则标记video)
      isVideoFile.value = detail.urlRealPerson.includes('.mp4')
    }

    // 7. 详解视频 urlTutorial
    if (detail.urlTutorial) {
      urlTutorial.value = detail.urlTutorial
      videoDetailName.value = '已选择详解视频'
    }

  } catch (err) {
    console.error('加载动作详情失败:', err)
    actionDetail.value = {}
  }
};


// 肌肉部位列表(从接口获取)
const muscleGroups = ref([]);
// 加载肌肉部位
const loadMuscleGroups = async () => {
  try {
    const res = await ExercisesApi.getMotionPartPage();
    muscleGroups.value = res.data;
    console.log('加载部位分类:', muscleGroups.value)
  } catch (err) {
    console.error('加载部位失败', err);
  }
};

// 主要和次要部位(存储 ID 数组)
const primaryMuscles = ref([]); // 主要部位 ID 列表
const secondaryMuscles = ref([]); // 次要部位 ID 列表

// 弹窗控制
const showMusclePicker = ref(false);

// 部位分类
const bodyPartOptions = ref([]);
const loadbodyPartOptions = async () => {
  const res = await LeftmotionApi.getAllCategories();
  bodyPartOptions.value = res.data;
};

// 用具分类
const equipmentOptions = ref([]);
const loadequipmentOptions = async () => {
  const res = await EquipmentListApi.Getallequipments();
  equipmentOptions.value = res.data;
};

// 弹窗状态
const showActionTypePicker = ref(false);
const showDirectoryPicker = ref(false);
const showCoverSelector = ref(false);
const showVideoSelector = ref(false);

// 弹窗控制
const openActionTypePicker = () => {
  if (isEdit.value) return;
  showActionTypePicker.value = true;
};
const openDirectoryPicker = () => {
  showDirectoryPicker.value = true;
};

// 封面图片路径
const coverImagePath = ref('https://fitness-hcxtec-bucket.oss-cn-shenzhen.aliyuncs.com/20260316/order-empty_1773628059920.png');
// 视频路径(可选)
const videoFilePath = ref('');
// ✅ 新增:标记是否上传成功(用于判断)
const coverUploaded = ref(false);
const videoUploaded = ref(false);
// 视频详解
const urlTutorial = ref('');
const videoDetailName = ref('');

// ==================== 视频详解(上传组件)====================
const chooseTutorialVideo = () => {
  uni.chooseMedia({
    count: 1,
    mediaType: ['video'],  // 只允许选视频
    success: async (res) => {
      const file = res.tempFiles[0];
      const result = await FileApi.uploadFile(file.tempFilePath);
      urlTutorial.value = result.data;
      videoDetailName.value = '已选择详解视频';
      uni.showToast({ title: '选择成功', icon: 'success' });
    },
    fail: () => {
      uni.showToast({ title: '选择失败', icon: 'none' });
    }
  })
};
const isVideoFile = ref(false)
// 打开视频/图片选择器 + 上传成功判断  这里上传的是3D的那个字段
const openVideoSelector = () => {
  uni.chooseMedia({
    count: 1,
    mediaType: ['image', 'video'],
    success: async (res) => {
      const file = res.tempFiles[0];
      console.log('选择的文件类型:', file.fileType);
      isVideoFile.value = file.fileType === 'video';
      // 上传到服务器
      const result = await FileApi.uploadFile(file.tempFilePath);
      videoFilePath.value = result.data;
      videoUploaded.value = true; //  标记视频上传成功
      uni.showToast({
        title: file.fileType === 'video' ? '视频选择成功' : '图片选择成功',
        icon: "success"
      });
    },
    fail: () => {
      videoUploaded.value = false; // ❌ 选择失败
      uni.showToast({ title: "选择失败", icon: "none" });
    }
  })
};

// 封面选择 + 真实上传
const openCoverSelector = () => {
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      const path = res.tempFilePaths[0];
      uni.showLoading({ title: "上传中..." });
      // 封面上传
      try {
        const result = await FileApi.uploadFile(path);
        console.log(res, 'res');

        coverImagePath.value = result.data;
        console.log('coverImagePath', coverImagePath.value);

        coverUploaded.value = true;
        uni.showToast({
          title: "封面上传成功",
          icon: "success"
        });
      } catch (err) {
        uni.showToast({
          title: "上传失败",
          icon: "none"
        });
      } finally {
        uni.hideLoading();
      }
    },
    fail: () => {
      coverUploaded.value = false;
      uni.showToast({
        title: "封面选择失败",
        icon: "none"
      });
    }
  });
};

const closeAllPopups = () => {
  showActionTypePicker.value = false;
  showDirectoryPicker.value = false;
  showCoverSelector.value = false;
  showVideoSelector.value = false;
  showMusclePicker.value = false;
  // showVideoDetailPicker.value = false;
};

// 动作类型
const onActionTypeChange = (e) => {
  actionTypeIndex.value = e.detail.value[0];
};
// 动作分类列表
const confirmActionType = () => {
  const actionstype = actionTypeOptions.value[actionTypeIndex.value];
  actionType.value = `${actionstype.name}`;
  closeAllPopups();
};

// 目录管理
const onBodyPartChange = (e) => {
  bodyPartIndex.value = e.detail.value[0];
};
const onEquipmentChange = (e) => {
  equipmentIndex.value = e.detail.value[0];
};
const confirmDirectory = () => {
  const selectedBodyPart = bodyPartOptions.value[bodyPartIndex.value];
  const selectedEquipment = equipmentOptions.value[equipmentIndex.value];
  directoryName.value = ` ${selectedBodyPart.name}( ${selectedEquipment.name})`;
  closeAllPopups();
};


// =================================保存动作====================
const saveExercise = async () => {
  if (!exerciseName.value.trim()) {
    uni.showToast({ title: '请输入动作名称', icon: 'none' });
    return;
  }

  console.log('--', equipmentOptions.value[equipmentIndex.value]);
  console.log('--', bodyPartOptions.value[bodyPartIndex.value]);
  // 获取 categoryId 和 equipmentId
  const selectedBodyPart = bodyPartOptions.value[bodyPartIndex.value];
  const selectedEquipment = equipmentOptions.value[equipmentIndex.value];
  if (!selectedBodyPart || !selectedEquipment) {
    uni.showToast({ title: '请选择目录分类', icon: 'none' });
    return;
  }

  // 动作类型映射:label -> value
  const selectedActionType = actionTypeOptions.value[actionTypeIndex.value];
  if (!selectedActionType) {
    uni.showToast({ title: '请选择动作类型', icon: 'none' });
    return;
  }
  // 提示选择封面
  if (!coverUploaded.value) {
    uni.showToast({ title: '请选择封面', icon: 'none' });
    return;
  }

  // 视频非必填,所以不强制,但可以提示
  if (videoFilePath.value && !videoUploaded.value) {
    uni.showToast({ title: '视频未选择成功', icon: 'none' });
    return;
  }
  // 构建请求参数
  const payload = {
    name: exerciseName.value.trim(),
    categoryId: selectedBodyPart.id, // 注意:必须是 id,不是 name
    equipmentId: selectedEquipment.id, // 同上
    exerciseType: selectedActionType.id, // 这里传数字 1/2/3
    primaryMuscles: JSON.stringify(primaryMuscles.value), //后端要求改json格式
    secondaryMuscles: JSON.stringify(secondaryMuscles.value),
    // urlImage: coverImagePath.value, //  封面地址
    url3dAnimation: coverImagePath.value,
    urlRealPerson: videoFilePath.value,      //真人实拍视频
    urlTutorial: urlTutorial.value, // 详解视频
  };
  // 编辑追加id
  if (isEdit.value) {
    payload.id = editActionId.value
  }
  console.log('【发送的 payload】', payload);
  let res;
  try {
    if (isEdit.value) {
      res = await ExercisesApi.updateexercises(payload);
      console.log('【更新接口返回】', res);
    } else {
      res = await ExercisesApi.createExercise(payload);
      console.log('【创建接口返回】', res);
    }

    if (res.code === 0) {
      uni.showToast({ title: isEdit.value ? '编辑成功' : '保存成功', icon: 'success' });
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    } else {
      uni.showToast({ title: res.msg || '保存失败', icon: 'none' });
    }
  } catch (error) {
    console.error('创建动作失败:', error);
    uni.showToast({ title: '网络错误,请重试', icon: 'none' });
  }
};

// 删除动作
const deleteAction = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该动作吗?删除后无法恢复',
    success: async (res) => {
      if (res.confirm) {
        try {
          const delRes = await ExercisesApi.deleteexercises(editActionId.value)
          if (delRes.code === 0) {
            uni.showToast({ title: '删除成功', icon: 'success' })
            setTimeout(() => uni.navigateBack(), 1000)
          } else {
            uni.showToast({ title: delRes.msg || '删除失败', icon: 'none' })
          }
        } catch (err) {
          uni.showToast({ title: '删除请求失败', icon: 'none' })
        }
      }
    }
  })
}

const openMusclePicker = () => {
  showMusclePicker.value = true;
};

const togglePrimary = (id) => {
  if (primaryMuscles.value.includes(id)) {
    primaryMuscles.value = primaryMuscles.value.filter((i) => i !== id);
  } else {
    primaryMuscles.value.push(id);
    // 自动取消次要
    secondaryMuscles.value = secondaryMuscles.value.filter((i) => i !== id);
  }
};

const toggleSecondary = (id) => {
  if (secondaryMuscles.value.includes(id)) {
    secondaryMuscles.value = secondaryMuscles.value.filter((i) => i !== id);
  } else {
    secondaryMuscles.value.push(id);
    // 自动取消主要
    primaryMuscles.value = primaryMuscles.value.filter((i) => i !== id);
  }
};

const confirmMuscleSelection = () => {
  // 构建显示文本,例如:“胸部(主), 背部(次)”
  const primaryNames = primaryMuscles.value
    .map((id) => muscleGroups.value.find((g) => g.id === id)?.name || '')
    .filter(Boolean);
  const secondaryNames = secondaryMuscles.value
    .map((id) => muscleGroups.value.find((g) => g.id === id)?.name || '')
    .filter(Boolean);

  let displayText = '';
  if (primaryNames.length) {
    displayText += primaryNames.join('、') + '(主)';
  }
  if (secondaryNames.length) {
    if (displayText) displayText += ', ';
    displayText += secondaryNames.join('、') + '(次)';
  }

  // 可以存到一个新字段,比如 selectedMusclesDisplay
  selectedMusclesDisplay.value = displayText || '未选择';

  closeAllPopups();
};

onMounted(() => {
  // loadbodyPartOptions();
  // loadequipmentOptions();
  // loadMuscleGroups();
  // loadexercisesGroups();
});
</script>


<style scoped>
.add-custom-exercise-page {
  background-color: #1a1a1a;
  min-height: 100vh;
  padding: 20rpx;
  color: white;
}

/* 肌肉部位图 */

.muscle-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 40rpx;
}

/* 肌肉部位图容器 - 占满红色框,无多余内边距 */
.muscle-area {
  background: #1a1a1a;
  border-radius: 20rpx;
  /* 移除原有padding,让容器完全贴合红色框 */
  padding: 0;
  margin: 20rpx;
  position: relative;
  /* 固定容器高度,适配移动端,可根据需求调整 */
  height: 500rpx;
  overflow: hidden;
}

/* 肌肉图样式 - 100%占满容器,保持比例不拉伸 */
.muscle-image-front {
  width: 100%;
  height: 100%;
  /* aspectFill:保持比例,裁剪超出部分,完美占满容器 */
  /* 若要完整显示图片,改为 mode="aspectFit",同时调整容器高度 */
  object-fit: cover;
  opacity: 1;
  /* 移除原有半透明,清晰显示 */
}

.muscle-image-back {
  transform: rotateY(180deg);
}

.legend {
  display: flex;
  justify-content: center;
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #ccc;
}

.legend-item {
  display: flex;
  align-items: center;
  margin: 0 20rpx;
}

.dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  margin-right: 10rpx;
}

.primary {
  background-color: #ff9900;
}

.secondary {
  background-color: #66ccff;
}

/* 表单区域 */
.form-section {
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  margin-top: 20rpx;
}

.form-item {
  display: flex;
  flex-direction: column;
  padding: 30rpx 30rpx 30rpx 40rpx;
  border-bottom: 1rpx solid #eee;
  position: relative;
}

.action-name {
  width: 285rpx;
}

.label {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.center-label {
  text-align: center;
  color: #c44b4b;
}

.input-group {
  display: flex;
  align-items: center;
  position: relative;
}

.input-field {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  padding: 0;
  background: none;
  border: none;
  outline: none;
}

.input-placeholder {
  color: #999;
}

.icon-wrapper {
  width: 40rpx;
  height: 40rpx;
  margin-left: 10rpx;
}

.edit-icon {
  width: 24rpx;
  height: 24rpx;
}

.cover-btn {
  position: absolute;
  right: 30rpx;
  top: 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100rpx;
  height: 100rpx;
  background: #f0f0f0;
  border-radius: 10rpx;
  padding: 10rpx;
}

.cover-icon {
  width: 40rpx;
  height: 40rpx;
}

.btn-text {
  font-size: 20rpx;
  color: #333;
  margin-top: 5rpx;
}

.value-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  margin-top: 10rpx;
}

.value {
  color: #28c76f;
  font-weight: bold;
}

.arrow-icon {
  width: 20rpx;
  height: 20rpx;
  transform: rotate(90deg);
}

.upload-btn {
  position: absolute;
  right: 30rpx;
  top: 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100rpx;
  height: 100rpx;
  background: #f0f0f0;
  border-radius: 10rpx;
  padding: 10rpx;
}

.preview-media {
  width: 100rpx;
  height: 100rpx;
  border-radius: 10rpx;
  object-fit: cover;
}

/* 隐藏视频默认控制条(可选) */
.upload-btn ::deep video::-webkit-media-controls {
  display: none !important;
}

.camera-icon {
  width: 40rpx;
  height: 40rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #333;
  margin-top: 5rpx;
}

.play-icon {
  width: 30rpx;
  height: 30rpx;
}

.save-button {
  margin: 40rpx 30rpx 0;
}

.btn-save {
  width: 100%;
  height: 80rpx;
  background: linear-gradient(90deg, #ff9900, #ff6600);
  color: white;
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
  outline: none;
}

/* 弹窗通用样式 */
.popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 999;
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
}

.popup-content {
  width: 100%;
  background: white;
  border-radius: 16rpx 16rpx 0 0;
  max-height: 70vh;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #eee;
}

.close-btn {
  font-size: 40rpx;
  color: #333;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  margin: 0;
}

.confirm-btn {
  width: 80rpx;
  height: 40rpx;
  line-height: 40rpx;
  background-color: #ff9900;
  color: white;
  border-radius: 20rpx;
  text-align: center;
  font-size: 28rpx;
}

.picker-view {
  height: 200rpx;
  width: 100%;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  color: #333;
  height: 100%;
}

.double-picker {
  display: flex;
}

.double-picker .picker-view.half {
  width: 50%;
}

/* 封面预览 */
.cover-preview {
  display: flex;
  justify-content: center;
  margin: 30rpx 0;
}

.cover-image {
  width: 200rpx;
  height: 200rpx;
}

/* 上传区域 */
.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
}

.upload-icon {
  width: 60rpx;
  height: 60rpx;
}

.upload-text {
  font-size: 28rpx;
  color: #666;
  margin-top: 10rpx;
}

/* === 美化后的肌肉选择列表 === */
.muscle-list-beautified {
  padding: 20rpx 32rpx;
}

.muscle-item-beautified {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.muscle-name {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  flex: 1;
}

.selector-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  border-radius: 50rpx;
  background-color: #f8f8f8;
  transition: all 0.2s ease;
  min-width: 120rpx;
  text-align: center;
}

.selector-btn.primary {
  border: 2rpx solid #ffcc99;
}

.selector-btn.primary.active {
  background-color: #fff3e6;
  border-color: #ff9900;
  box-shadow: 0 4rpx 12rpx rgba(255, 153, 0, 0.2);
}

.selector-btn.secondary {
  border: 2rpx solid #cce6ff;
}

.selector-btn.secondary.active {
  background-color: #e6f7ff;
  border-color: #66ccff;
  box-shadow: 0 4rpx 12rpx rgba(102, 204, 255, 0.2);
}

.selector-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
}

.selector-dot.primary {
  background-color: #ff9900;
}

.selector-dot.secondary {
  background-color: #66ccff;
}

.selector-label {
  font-size: 26rpx;
  color: #666;
  font-weight: 500;
}

.selector-btn.primary.active .selector-label,
.selector-btn.secondary.active .selector-label {
  color: #333;
  font-weight: bold;
}
</style>