wode-xinjian-moban.vue 18.6 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
<template>
  <view class="template-edit-page">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="close-btn" @click="goBack">
        <up-icon name="close" color="#fff" size="20" bold></up-icon>
      </view>
      <view class="title-area">
        <view class="title-row" @click="openTitlePopup">
          <view class="title-text">{{ templateTitle || '点击输入标题' }}</view>
          <uni-icons type="compose" size="24" color="#fff" />
        </view>
        <view class="stats-text">{{ (trainingStore.actionDetail?.units || []).length }}个动作 ·
          {{ totalSets }}组 · {{ totalWeight }}kg</view>
      </view>
      <view class="save-btn" :class="{
        disabled: trainingStore.actionDetail?.units?.length === 0,
        active: trainingStore.actionDetail?.units?.length > 0
      }" @click="handleSave">
        保存模板
      </view>
    </view>

    <view class="content-area">
      <template v-if="trainingStore.actionDetail?.units?.length">
        <view v-for="(unit, index) in trainingStore.actionDetail?.units" :key="unit.unitId">
          <dongzuo :id="unit.unitId" :type="unit.unitType" :actionDetail="trainingStore.convertUnitToActionDetail(unit)"
            :ref="el => setActionRef(el, index)" :unitIndex="index" />
        </view>
      </template>

      <!-- 中间空白提示区域 -->
      <view v-else class="empty-area">
        <view class="empty-text">
          尚未添加任何动作
          <br />
          点击最下方 + 开始添加动作
        </view>
      </view>
    </view>

    <!-- 新手引导提示气泡 -->
    <view class="guide-bubble" v-if="trainingStore.actionDetail?.units?.length === 0">
      挑选想要的动作开始训练吧
      <view class="bubble-arrow"></view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="bar-item" @click="openActionSort">
        <text class="item-num">{{ trainingStore.actionDetail?.units?.length }}</text>
        <text class="item-label">动作排序</text>
      </view>
      <view class="bar-item" @click="openIntroPopup">
        <uni-icons type="list" size="24" color="#fff" />
        <text class="item-label">模板介绍</text>
      </view>
      <view class="bar-item add-btn" @click="handleAddAction">
        <up-icon name="plus" color="#000" size="20" bold></up-icon>
      </view>
      <view class="bar-item" @click="showScenePicker = true">
        <uni-icons type="gear" size="24" color="#fff" />
        <text class="item-label">训练场景</text>
      </view>
      <view class="bar-item" @click="handleEditCover">
        <uni-icons type="image" size="24" color="#fff" />
        <text class="item-label">编辑封面</text>
      </view>
    </view>
    <!-- 模板介绍弹窗 -->
    <view class="intro-popup" v-if="showIntroPopup">
      <view class="popup-header">
        <view class="popup-close-btn" @click="closeIntroPopup">
          <up-icon name="close" color="#fff" size="20" bold></up-icon>
        </view>
        <view class="popup-title">模板介绍</view>
        <view class="popup-save-btn" @click="saveIntro">保存</view>
      </view>
      <view class="popup-content">
        <textarea class="intro-textarea" v-model="templateIntro" placeholder="在此处输入模板介绍" />
      </view>
    </view>

    <!-- 模板标题弹窗 -->
    <view class="intro-popup" v-if="showTitlePopup">
      <view class="popup-header">
        <view class="popup-close-btn" @click="closeTitlePopup">
          <up-icon name="close" color="#fff" size="20" bold></up-icon>
        </view>
        <view class="popup-title">模板标题</view>
        <view class="popup-save-btn" @click="saveTemplateTitle">保存</view>
      </view>
      <view class="popup-content">
        <textarea class="intro-textarea" v-model="templateTitle" placeholder="请输入模板标题" />
      </view>
    </view>


    <up-picker :show="showScenePicker" :columns="sceneColumns" :defaultIndex="[0]" title="训练场景" title-color="#ffffff"
      cancel-color="#cccccc" confirm-color="#409eff" active-color="#ffd100" @confirm="handleSceneConfirm"
      @cancel="showScenePicker = false" closeOnClickOverlay />

    <!-- 动作排序组件 -->
    <action-sort ref="actionSortRef" @open-add-actions="addExShow = true" />

    <!-- 动作新增组件 -->
    <addActions :show="addExShow" @close="addExShow = false" />
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from "@dcloudio/uni-app"
import dongzuo from '@/pages/xunji/components/dongzuo-lianxi/dongzuo.vue';
import { useTrainingStore } from '@/sheep/store/trainingStore'
import FileApi from '@/sheep/api/infra/file';
import addActions from '@/pages/xunji/components/dongzuo-lianxi/add-actions.vue'
import TemplatesApi from '@/sheep/api/Template/Templates';
import ActionSort from '@/pages/xunji/components/dongzuo-lianxi/dongzuo-paixu.vue'

const coverImage = ref('');
const addExShow = ref(false)
const hasConverted = ref(false)
const dongzuoRefs = ref([]) // 获得子组件模板的数据

const trainingStore = useTrainingStore()

const canSave = ref(false);
const showGuide = ref(true);

const showIntroPopup = ref(false);
const templateIntro = ref('');

const showTitlePopup = ref(false);
const templateTitle = ref('');

const actionSortRef = ref(null)

const sceneList = ref([
  { id: 0, title: '不限' },
  { id: 1, title: '健身房' },
  { id: 2, title: '仅哑铃' },
  { id: 3, title: '仅哑铃+杠铃' },
]);

const showScenePicker = ref(false);
const selectedSceneId = ref(0);

const sceneColumns = ref([
  ['不限', '健身房', '仅哑铃', '仅哑铃+杠铃']
]);

onLoad(() => {
  if (trainingStore.type !== 3 && !hasConverted.value) {
    trainingStore.convertToTemplate();
    hasConverted.value = true;
    console.log('✅ 已完成模板转换(仅执行一次)', trainingStore.actionDetail);
  }
  console.log('在主页面转换为模板架构后的全局数据', trainingStore.type, trainingStore.actionDetail)
  console.log('units.length:', trainingStore.actionDetail?.units?.length);

  // ==============================================
  // 编辑页回显(标题、介绍、场景、封面)
  // ==============================================
  const detail = trainingStore.actionDetail || {}
  templateTitle.value = detail.templateName || ''
  templateIntro.value = detail.introduction || ''
  selectedSceneId.value = detail.scene || 0
  coverImage.value = detail.urlCover || ''

});

// 动作排序弹窗
const openActionSort = () => {
  console.log('调用前,ref 的值:', actionSortRef.value)
  actionSortRef.value.openActionSort()
}

// 全部的组数
const totalSets = computed(() => {
  let count = 0
  dongzuoRefs.value.forEach(ref => {
    if (ref?.totalSetCount) count += ref.totalSetCount
  })
  return count
})

// 计算总训练重量(kg × 次数,仅统计力量类动作)
const totalWeight = computed(() => {
  const units = trainingStore.actionDetail?.units || []
  const records = trainingStore.unitRecords || {}
  let total = 0

  units.forEach((unit, unitIndex) => {
    const record = records[unitIndex]
    if (!record?.records) return

    unit.exercises?.forEach(ex => {
      const sets = record.records[ex.exerciseId]
      if (!Array.isArray(sets)) return

      sets.forEach(set => {
        let weight = Number(set.weight) || 0
        const reps = Number(set.reps) || 0
        const userWeight = record.userWeight || 70

        // 只计算 0、4、5 类型
        if (ex.exerciseType === 0) {
          total += weight * reps
        }
        else if (ex.exerciseType === 4) {
          total += (userWeight + weight) * reps
        }
        else if (ex.exerciseType === 5) {
          total += (userWeight - weight) * reps
        }
      })
    })
  })

  return total
})
// 场景确认
const handleSceneConfirm = (e) => {
  console.log('up-picker confirm 原始参数:', e);
  // 从 indexs 里拿到选中的索引(单列就是 0 号)
  const selectedIndex = e.indexs[0];
  const selectedItem = sceneList.value[selectedIndex];

  if (selectedItem) {
    console.log("选中ID:", selectedItem.id);
    console.log("选中标题:", selectedItem.title);
    selectedSceneId.value = selectedItem.id;
  }

  showScenePicker.value = false;
};

// dongzuo组件
const setActionRef = (el, index) => {
  if (el) {
    dongzuoRefs.value[index] = el
  }
  // console.log('✅ 成功收集子组件实例:', dongzuoRefs.value)
}

// 编辑封面
const handleEditCover = async () => {
  try {
    // 1. 选择图片
    const res = await uni.chooseImage({
      count: 1,         // 只选1张(封面)
      sizeType: ['compressed'], // 压缩图
      sourceType: ['album', 'camera'], // 相册+相机
    });

    const filePath = res.tempFilePaths[0];
    if (!filePath) return;

    // 2. 调用你现成的 FileApi 上传文件
    const uploadRes = await FileApi.uploadFile(filePath, 'template-cover');

    // 3. 上传成功
    if (uploadRes && uploadRes.data) {
      // 后端返回的图片地址
      coverImage.value = uploadRes.data;
      console.log('封面上传成功:', coverImage.value);
      uni.showToast({ title: '封面设置成功' });
    }
  } catch (err) {
    console.log('上传封面失败:', err);
    uni.showToast({ title: '上传失败', icon: 'none' });
  }
};

// 模板介绍
const openIntroPopup = () => {
  showIntroPopup.value = true;
};
const closeIntroPopup = () => {
  setTimeout(() => {
    showIntroPopup.value = false;
  }, 2000);
};
// 保存模板介绍
const saveIntro = () => {
  console.log(templateIntro.value);
  uni.showToast({ title: '保存成功' });
  closeIntroPopup();
};

// 模板标题
const openTitlePopup = () => {
  showTitlePopup.value = true;
};

const closeTitlePopup = () => {
  showTitlePopup.value = false;
};

const saveTemplateTitle = () => {
  if (!templateTitle.value.trim()) {
    uni.showToast({
      title: '请输入模板标题',
      icon: 'none'
    });
    return;
  }

  // 保存后关闭弹窗
  closeTitlePopup();
  uni.showToast({
    title: '标题保存成功',
    icon: 'success'
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
  trainingStore.clearTrainingStore()
};

// 保存模板(完整修复间歇训练 type=6)
const handleSave = async () => {
  const units = trainingStore.actionDetail?.units;
  if (!units || units.length === 0) {
    uni.showToast({ title: '请先添加动作', icon: 'none' });
    return;
  }
  if (!templateTitle.value.trim()) {
    uni.showToast({ title: '请输入模板标题', icon: 'none' });
    // openTitlePopup();
    return;
  }

  try {
    uni.showLoading({ title: '保存中...' });
    const postData = {
      templateId: trainingStore.actionDetail.id || null,
      groupId: null,
      templateName: templateTitle.value.trim(),
      scene: selectedSceneId.value,
      templateCover: coverImage.value || '',
      templateIntroduction: templateIntro.value || '',
      units: units.map((unit, unitIndex) => {
        const record = trainingStore.unitRecords[unitIndex] || {};
        return {
          id: unit.unitId || 0,
          name: unit.name || '',
          unitType: unit.unitType || 1,
          sortOrder: unitIndex,
          exercises: (unit.exercises || []).map((ex, exIndex) => {
            const sets = record.records?.[ex.exerciseId] || [];
            return {
              exerciseId: ex.exerciseId || 0,
              exerciseType: ex.exerciseType || 0,
              innerOrder: exIndex,
              sets: sets.map((set, setIndex) => {
                let duration = 0;
                let restTime = 0;
                // 间歇训练单独处理
                if (ex.exerciseType === 6) {
                  duration = Number(set.duration) || 0;
                  restTime = Number(set.restTime) || 0;
                }
                // 其它
                else {
                  duration =
                    (Number(set.h) || 0) * 3600 +
                    (Number(set.m) || 0) * 60 +
                    (Number(set.s) || 0);
                  restTime = parseInt(set.quickTimeDisplay) || 60;
                }

                return {
                  weight: Number(set.weight) || 0,
                  reps: Number(set.reps) || 0,
                  distance: Number(set.distance) || 0,
                  duration: duration,
                  restTime: restTime,
                  setIndex: setIndex,
                };
              }),
            };
          }),
        };
      }),
    };

    // 调用接口
    let res;
    // 判断:有 ID 就更新,没有 ID 就新建
    if (trainingStore.actionDetail.id) {
      res = await TemplatesApi.updateCustTemplate(postData);
    } else {
      res = await TemplatesApi.createCustTemplate(postData);
    }
    console.log('保存成功', res);
    uni.hideLoading();
    uni.showToast({ title: '保存成功' });

    setTimeout(() => {
      uni.redirectTo({
        url: '/pages4/pages/xunji/xunji-wode-moban'
      });
      trainingStore.clearTrainingStore();
    }, 1500);

  } catch (err) {
    uni.hideLoading();
    console.error('保存失败', err);
    uni.showToast({ title: '保存失败', icon: 'none' });
  }
};

// 添加动作
const handleAddAction = () => {
  console.log('添加动作');
  addExShow.value = true
  showGuide.value = false;
};
</script>

<style scoped lang="scss">
.template-edit-page {
  width: 100%;
  height: 100vh;
  background-color: #1a1a1a;
  display: flex;
  flex-direction: column;
  color: #fff;
  font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', sans-serif;
}

/* 顶部导航栏 */
.header {
  margin-top: 150rpx;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 30rpx 30rpx 20rpx;
  flex-shrink: 0;

  .close-btn {
    width: 60rpx;
    height: 60rpx;
    background-color: #333;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }

  .title-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-left: 20rpx;

    .title-row {
      display: flex;
      gap: 15rpx;
    }

    .title-text {
      font-size: 36rpx;
      font-weight: 600;
      margin-bottom: 10rpx;
      display: flex;
      align-items: center;
      gap: 10rpx;
    }

    .stats-text {
      font-size: 26rpx;
      color: #999;
    }
  }

  .save-btn {
    padding: 16rpx 32rpx;
    background-color: #333;
    border-radius: 40rpx;
    font-size: 28rpx;
    color: #999;
    flex-shrink: 0;

    &.active {
      background-color: #ffdc00;
      color: #000;
    }

    &.disabled {
      opacity: 0.5;
    }
  }
}

// 中间内容区域
.content-area {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 20rpx;
  display: flex;
  flex-direction: column;
}

/* 中间空白区域 */
.empty-area {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;

  .empty-text {
    font-size: 30rpx;
    color: #888;
    text-align: center;
    line-height: 1.6;
  }
}

/* 新手引导气泡 */
.guide-bubble {
  position: absolute;
  bottom: 220rpx;
  left: 50%;
  transform: translateX(-50%);
  background-color: #000;
  color: #fff;
  padding: 20rpx 30rpx;
  border-radius: 12rpx;
  font-size: 30rpx;
  z-index: 10;

  .bubble-arrow {
    position: absolute;
    bottom: -16rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 0;
    height: 0;
    border-left: 12rpx solid transparent;
    border-right: 12rpx solid transparent;
    border-top: 16rpx solid #000;
  }
}

/* 底部操作栏 */
.bottom-bar {
  display: flex;
  height: 110rpx;
  align-items: center;
  justify-content: space-around;
  padding: 20rpx 0;
  background-color: #1a1a1a;
  border-top: 1rpx solid #333;
  flex-shrink: 0;
  padding-bottom: env(safe-area-inset-bottom);

  .bar-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
    font-size: 24rpx;
    color: #fff;

    .item-num {
      font-size: 32rpx;
      font-weight: 600;
    }

    .item-label {
      font-size: 24rpx;
      color: #ccc;
    }

    &.add-btn {
      width: 100rpx;
      height: 100rpx;
      background-color: #fff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: -40rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
    }
  }
}

.intro-popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 999;
}

.intro-popup {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 85vh;
  background: #333;
  border-radius: 24rpx 24rpx 0 0;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  // transition: transform 0.3s
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 30rpx 20rpx;
}

.popup-title {
  font-size: 34rpx;
  color: #fff;
  font-weight: bold;
}

.popup-save-btn {
  background: #ffd100;
  color: #000;
  padding: 12rpx 24rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.popup-content {
  flex: 1;
  padding: 30rpx;
  flex-shrink: 0;
}

.intro-textarea {
  width: 95%;
  height: 300rpx;
  background: #444;
  color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  font-size: 30rpx;
  border: 0;
}

// 场景弹窗遮罩
.scene-popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 999;
}

// 场景弹窗本体
.scene-popup {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #333;
  border-radius: 24rpx 24rpx 0 0;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  padding-bottom: env(safe-area-inset-bottom);
  // 固定高度(和截图比例一致)
  height: 60vh;
  max-height: 70vh;
}

// 顶部横条
.scene-popup::before {
  content: '';
  position: absolute;
  top: 16rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 80rpx;
  height: 8rpx;
  background: #666;
  border-radius: 4rpx;
}

// 弹窗头部
.scene-popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40rpx 30rpx 20rpx;

  .scene-close-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .scene-popup-title {
    font-size: 34rpx;
    color: #fff;
    font-weight: bold;
  }
}

// 场景选项列表
.scene-list {
  flex: 1;
  overflow-y: auto;

  .scene-item {
    padding: 30rpx;
    text-align: center;
    font-size: 32rpx;
    color: #999;
    border-bottom: 1rpx solid #444;

    &.active {
      color: #fff;
      font-weight: bold;
    }
  }
}

// 底部确认按钮
.scene-confirm-btn {
  margin: 30rpx;
  padding: 24rpx;
  background: #ffd100;
  color: #000;
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
}
</style>