meiri-moban-xiugai.vue 13.4 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
<template>
  <up-popup :show="popShow" mode="bottom" @close="closePop" :safeAreaInsetBottom="true" bgColor="#1c1c1e">
    <view class="popup-contain">
      <view class="pop-header">
        <view class="back-btn" @click="closePop">
          <uni-icons type="down" size="24" color="#fff" />
        </view>
        <text class="pop-title">修改动作训练组</text>
        <view class="save-btn" @click="saveEdit">保存修改</view>
      </view>
      <!-- 核心:单个dongzuo,只渲染当前选中的unit -->
      <scroll-view class="pop-content" scroll-y>
        <dongzuo v-if="isRenderDongzuo" :id="currUnit.unitId" :type="currUnit.unitType" :actionDetail="convertAction"
          :unitIndex="currUnitIndex" ref="dongzuoSingleRef" @deleteAction.prevent="handleDeleteAction"
          @replace-action.prevent="handleReplaceAction" :is-daily-templates="true" />
      </scroll-view>
    </view>

  </up-popup>
</template>

<script setup>
import { ref, defineExpose, computed, nextTick, watch } from 'vue'
import dongzuo from '@/pages/xunji/components/dongzuo-lianxi/dongzuo.vue'
import { useTrainingStore } from '@/sheep/store/trainingStore'
import dailytemplateApi from '@/sheep/api/Template/Dailytemplate'
import { useTemplateActionStore } from '@/sheep/store/templateAction'
import SupersetsApi from '@/sheep/api/motion/supersets';
import ExercisesApi from '@/sheep/api/motion/exercises';

const needReplaceUnit = ref(false)
const templateStore = useTemplateActionStore()

const trainingStore = useTrainingStore()
const emit = defineEmits(['saveSuccess'])
// 弹窗控制
const popShow = ref(false)
// dongzuo实例ref,用于收集修改后数据
const dongzuoSingleRef = ref(null)

const isRenderDongzuo = ref(false)

// 标记是否需要删除当前动作组
const needDeleteUnit = ref(false)

watch(
  () => templateStore.replaceId,
  (id) => {
    if (id) {
      needReplaceUnit.value = true
      uni.showToast({
        title: '已标记替换',
        icon: 'success'
      })
    }
  }
)

// 原watch不动,补充拉取新数据、替换source.unit
watch(
  () => templateStore.replaceId,
  async (id) => {
    if (id) {
      needReplaceUnit.value = true
      uni.showToast({ title: '已标记替换', icon: 'success' })
      // 新增代码:拉取新动作,替换弹窗数据源,触发页面刷新
      const rid = templateStore.replaceId
      const rtype = templateStore.replaceType
      let res, detail
      if (rtype === 1) res = await ExercisesApi.getExerciseById(rid)
      else res = await SupersetsApi.getSupersetsInfo(rid)
      detail = res.data
      // 拼装新unit覆盖原sourceInfo.unit
      let newUnit
      if (rtype === 1) {
        newUnit = {
          unitType: 1, unitId: detail.id, unitName: detail.name,
          exercises: [{ exerciseId: detail.id, exerciseName: detail.name, exerciseType: detail.exerciseType, urlImage: detail.urlImage || detail.url3dAnimation, categoryDescription: detail.categoryDescription || '', equipmentDescription: detail.equipmentDescription || '', sets: [] }]
        }
      } else {
        newUnit = {
          unitType: 2, unitId: detail.id, unitName: detail.name,
          exercises: detail.exercises.map(e => ({ exerciseId: e.id, exerciseName: e.name, exerciseType: e.exerciseType, urlImage: e.urlImage || e.url3dAnimation, sets: [] }))
        }
      }
      sourceInfo.value.unit = newUnit
      // 销毁重建dongzuo实现刷新
      isRenderDongzuo.value = false
      await nextTick()
      isRenderDongzuo.value = true
    }
  }
)


// 缓存打开弹窗传入的数据
let sourceInfo = ref({
  unit: null,
  unitIndex: null,
  dailyTemplate: null
})
// 当前操作的unit和下标
const currUnit = computed(() => sourceInfo.value.unit || {})
const currUnitIndex = computed(() => sourceInfo.value.unitIndex ?? 0)

// 格式化数据:统一 动作 / 超级组 结构 → 给 dongzuo 组件用
const formatDongzuoData = (unit) => {
  if (!unit) return {}

  // 1. 普通动作 type=1
  if (unit.unitType === 1) {
    const ex = unit.exercises?.[0] || {}
    return {
      id: ex.exerciseId,
      name: ex.exerciseName,
      urlImage: ex.urlImage,
      exerciseType: ex.exerciseType,
      categoryDescription: ex.categoryDescription || '',
      equipmentDescription: ex.equipmentDescription || '',
    }
  }

  // 2. 超级组 type=2
  if (unit.unitType === 2) {
    return {
      id: unit.unitId,
      name: unit.unitName || '超级组',
      // 超级组需要把子动作全部格式化
      exercises: unit.exercises?.map(ex => ({
        id: ex.exerciseId,
        name: ex.exerciseName,
        urlImage: ex.urlImage,
        exerciseType: ex.exerciseType,
      })) || []
    }
  }

  return {}
}

const handleDeleteAction = () => {
  console.log('父组件处理删除动作')
  needDeleteUnit.value = true
  isRenderDongzuo.value = false
}

// ==================== 新增:子组件抛过来的动作替换 ====================
const handleReplaceAction = () => {
  console.log('父组件处理动作替换')
  emit('saveSuccess')
}

const convertAction = computed(() => {
  if (!sourceInfo.value.unit) return {}
  // 使用统一格式化后的数据
  return formatDongzuoData(sourceInfo.value.unit)
})

// 【对外暴露open方法,父页面调用打开弹窗】
const open = async (info) => {

  isRenderDongzuo.value = false
  needDeleteUnit.value = false

  console.log('info=', info);
  // 每次打开先清空当前store临时数据,避免上次缓存污染
  trainingStore.clearTrainingStore()

  sourceInfo.value = JSON.parse(JSON.stringify(info))
  // 关键:手动初始化当前unit的sets数据到Pinia.unitRecords(复用initTemplateRecords逻辑)
  const unit = sourceInfo.value.unit
  const unitIdx = sourceInfo.value.unitIndex
  let records = {}
  const exercises = unit.exercises || []
  console.log('后端传来的修改动作组的exercises', exercises);
  exercises.forEach(ex => {
    const sets = ex.sets || []
    // 后端sets → 转为dongzuo的record格式
    const arr = sets.map(set => {
      const totalSec = set.duration || 0
      const h = String(Math.floor(totalSec / 3600)).padStart(2, '0')
      const m = String(Math.floor((totalSec % 3600) / 60)).padStart(2, '0')
      const s = String(totalSec % 60).padStart(2, '0')
      return {
        weight: set.weight ?? '',
        reps: set.reps ?? '',
        duration: set.duration ?? '',
        distance: set.distance ?? '',
        restTime: set.restTime ?? '',
        h, m, s,
        quickTimeDisplay: (set.restTime || 60) + 's',
        isActive: (set.isCompleted ?? 0) === 1
      }
    })
    records[ex.exerciseId] = arr
  })

  console.log('赋值之后的records', records);

  // 存入Pinia对应unitIndex
  trainingStore.saveUnitRecord(unitIdx, { records, userWeight: 70 })
  await nextTick()
  await nextTick()
  // 打开弹窗
  console.log('存入后全局仓库unitRecords:', JSON.parse(JSON.stringify(trainingStore.unitRecords)))
  isRenderDongzuo.value = true
  popShow.value = true
}

// 关闭弹窗
const closePop = () => {
  popShow.value = false
  isRenderDongzuo.value = false
  // 关闭清空临时数据
  trainingStore.clearTrainingStore()
}

// 【保存修改:核心,组装参数调用更新接口】
const saveEdit = async () => {
  if (!dongzuoSingleRef.value) return uni.showToast({ title: '获取数据失败', icon: 'none' })
  const { unit, unitIndex, dailyTemplate } = sourceInfo.value

  // ================== 新增:删除逻辑 ==================
  if (needDeleteUnit.value) {
    // 1. 复制所有 unit,删掉当前这个
    const allUnits = [...dailyTemplate.units]
    allUnits.splice(unitIndex, 1)

    // 2. 调用你原来的保存接口
    try {
      await dailytemplateApi.updateDailyTemplate({
        dailyTemplateId: dailyTemplate.id,
        units: allUnits
      })
      uni.showToast({ title: '删除成功', icon: 'success' })
      emit('saveSuccess')
      closePop()
    } catch (err) {
      uni.showToast({ title: '删除失败', icon: 'none' })
    }
    // 直接 return,不执行后面的修改逻辑
    return
  }
  // ====================================================

  // ========================替换
  if (needReplaceUnit.value) {
    const replaceId = templateStore.replaceId
    const replaceType = templateStore.replaceType

    if (!replaceId || !replaceType) {
      uni.showToast({ title: '替换异常', icon: 'none' })
      return
    }

    try {
      let detail = null

      // ======================
      // 👇 完全移植你现成的接口逻辑
      // ======================
      if (replaceType === 1) {
        // 普通动作
        const res = await ExercisesApi.getExerciseById(replaceId)
        detail = res.data
      } else if (replaceType === 2) {
        // 超级组
        const res = await SupersetsApi.getSupersetsInfo(replaceId)
        detail = res.data
      }

      if (!detail) {
        uni.showToast({ title: '获取动作详情失败', icon: 'none' })
        return
      }

      // ======================
      // 组装 newUnit
      // ======================
      let newUnit = null

      if (replaceType === 1) {
        newUnit = {
          unitType: 1,
          unitId: detail.id,
          unitName: detail.name,
          exercises: [
            {
              exerciseId: detail.id,
              exerciseName: detail.name,
              exerciseType: detail.exerciseType,
              urlImage: detail.urlImage || detail.url3dAnimation,
              categoryDescription: detail.categoryDescription || '',
              equipmentDescription: detail.equipmentDescription || '',
              sets: []
            }
          ]
        }
      } else if (replaceType === 2) {
        newUnit = {
          unitType: 2,
          unitId: detail.id,
          unitName: detail.name,
          exercises: detail.exercises.map(e => ({
            exerciseId: e.id,
            exerciseName: e.name,
            exerciseType: e.exerciseType,
            urlImage: e.urlImage || e.url3dAnimation,
            sets: []
          }))
        }
      }

      // ======================
      // 替换到模板数组
      // ======================
      const allUnits = [...dailyTemplate.units]
      allUnits[unitIndex] = newUnit

      console.log('allUnits[unitIndex]=', allUnits[unitIndex]);

      await dailytemplateApi.updateDailyTemplate({
        dailyTemplateId: dailyTemplate.id,
        units: allUnits
      })

      uni.showToast({ title: '替换成功', icon: 'success' })
      emit('saveSuccess')
      closePop()
      return

    } catch (err) {
      uni.showToast({ title: '替换失败', icon: 'none' })
    } finally {
      // 最后清空
      templateStore.clearReplaceAction()
    }
  }

  let targetExercises = [...unit.exercises]
  if (unit.unitType === 1) {
    // 单动作:exercises只有1个
    const exItem = targetExercises[0]
    // expose出来的recordList
    const newSets = dongzuoSingleRef.value.recordList.map((item, idx) => {
      // 组件数据转回后端sets结构(和原页面save组装逻辑一致)
      const duration = Number(item.h) * 3600 + Number(item.m) * 60 + Number(item.s) || 0
      const rest = Number(item.quickTimeDisplay.replace('s', '')) || 0
      return {
        setIndex: idx + 1,
        weight: Number(item.weight) || 0,
        reps: Number(item.reps) || 0,
        distance: Number(item.distance) || 0,
        duration,
        restTime: rest,
        isCompleted: item.isActive ? 1 : 0
      }
    })
    exItem.sets = newSets
  } else if (unit.unitType === 2) {
    // 超级组:superRecordMap{exId:[]}
    const superMap = dongzuoSingleRef.value.superRecordMap
    targetExercises.forEach(ex => {
      const setArr = superMap[ex.exerciseId] || []
      ex.sets = setArr.map((item, idx) => {
        const duration = Number(item.h) * 3600 + Number(item.m) * 60 + Number(item.s) || 0
        const rest = Number(item.quickTimeDisplay.replace('s', '')) || 0
        return {
          setIndex: idx + 1,
          weight: Number(item.weight) || 0,
          reps: Number(item.reps) || 0,
          distance: Number(item.distance) || 0,
          duration,
          restTime: rest,
          isCompleted: item.isActive ? 1 : 0
        }
      })
    })
  }
  // 2、组装整份units:只替换当前修改的这个unit,其余units保持原样
  const allUnits = [...dailyTemplate.units]
  allUnits[unitIndex] = {
    ...unit,
    exercises: targetExercises
  }
  // 3、调用每日模板更新接口
  try {
    await dailytemplateApi.updateDailyTemplate({
      dailyTemplateId: dailyTemplate.id, // 当前每日模板主键id
      units: allUnits
    })
    uni.showToast({ title: '修改成功', icon: 'success' })
    popShow.value = false
    // 通知父页面刷新列表
    emit('saveSuccess')
    trainingStore.clearTrainingStore()
  } catch (err) {
    console.error(err)
    uni.showToast({ title: '修改失败', icon: 'none' })
  }
}

// 向外暴露open方法给父组件调用
defineExpose({ open })

</script>

<style lang="scss" scoped>
.popup-contain {
  width: 100%;
  max-height: 75vh;

}

.pop-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  color: #fff;

  .back-btn {
    font-size: 32rpx;
    color: #fff;
  }

  .pop-title {
    font-size: 34rpx;
    font-weight: bold;
  }

  .save-btn {
    background: #ffc107;
    color: #000;
    padding: 12rpx 30rpx;
    border-radius: 30rpx;
    font-size: 28rpx;
  }
}

.pop-content {
  // padding: 0 20rpx 120rpx;
  margin: 0 20rpx;
  height: calc(100vh - 120rpx);
  background: #f5b5b5;
  max-height: 70vh;
}
</style>