meiri-moban-xiugai.vue 14.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
<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 trainingSnapshot = ref(null)

const isRenderDongzuo = ref(false)

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

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

//当替换动作的时候, 原watch不动,补充拉取新数据、替换source.unit
const replaceCacheUnit = ref(null)
watch(
  () => templateStore.replaceId,
  async (id) => {
    if (id) {
      console.log('+++++每日模板修改替换++++++');
      needReplaceUnit.value = true
      uni.showToast({ title: '已标记替换', icon: 'success' })
      // 新增代码:拉取新动作,替换弹窗数据源,触发页面刷新
      const rid = templateStore.replaceId
      const rtype = templateStore.replaceType

      console.log('rid=', rid, 'rtype=', rtype);

      let res, detail
      if (rtype === 1) {
        res = await ExercisesApi.getExerciseById(rid)
        console.log('每日模板res=', res);
      }
      else {
        res = await SupersetsApi.getSupersetsInfo(rid)
        console.log('每日模板res=', res);
      }
      console.log('每日模板res=', res);
      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.url3dAnimation || detail.urlImage, categoryDescription: detail.categoryDescription || '', equipmentDescription: detail.equipmentDescription || '', sets: [] }]
        }
        console.log('newUnit', newUnit);

      } 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.url3dAnimation || e.exerciseCover, sets: [] }))
        }
        console.log('newUnit', newUnit);
      }

      // ============【新增改动】缓存拼装好的替换单元,保存复用============
      replaceCacheUnit.value = newUnit
      // =================================================================


      sourceInfo.value.unit = newUnit

      // ========== 新增:同步初始化当前unitIndex的Pinia训练记录 ==========
      const unitIdx = sourceInfo.value.unitIndex
      const exercises = newUnit.exercises || []
      let records = {}
      exercises.forEach(ex => {
        // 新动作无历史sets,给默认空白一组(和open初始化逻辑统一)
        records[ex.exerciseId] = [{
          h: '00', m: '00', s: '00', quickTimeDisplay: '60s',
          distance: '', weight: '', reps: '', duration: '', restTime: '', isActive: false
        }]
      })
      // 覆盖当前unitIndex的仓库记录
      trainingStore.saveUnitRecord(unitIdx, { records, userWeight: 70 })
      // =================================================================

      // 销毁重建dongzuo实现刷新
      isRenderDongzuo.value = false
      await nextTick()
      isRenderDongzuo.value = true
    }
  }
)

// 格式化传入动作组件的unit
const formatDongzuoData = (unit) => {
  if (!unit) return {}
  console.log('++每日模板的unit++', unit);
  let result = {} // 定义接收结果的变量

  // 1. 普通动作 type=1
  if (unit.unitType === 1) {
    const ex = unit.exercises?.[0] || {}
    result = {
      id: ex.exerciseId,
      name: ex.exerciseName,
      urlImage: ex.url3dAnimation || ex.exerciseCover || ex.urlImage,
      exerciseType: ex.exerciseType,
      categoryDescription: ex.categoryDescription || '',
      equipmentDescription: ex.equipmentDescription || '',
    }
  }
  // 2. 超级组 type=2
  if (unit.unitType === 2) {
    result = {
      id: unit.unitId,
      name: unit.unitName || '超级组',
      exercises: unit.exercises?.map(ex => ({
        id: ex.exerciseId,
        name: ex.exerciseName,
        urlImage: ex.url3dAnimation || ex.exerciseCover || ex.urlImage,
        exerciseType: ex.exerciseType,
      })) || []
    }
  }

  console.log('格式化后结果:', result) // 打印最终数据
  return result
}

// 
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('trainingStore.isTraining 值:', trainingStore.isTraining)

  // ✅ 新增:如果有正在进行的训练,先把整个 store 状态装进口袋
  if (trainingStore.isTraining) {
    trainingSnapshot.value = JSON.parse(JSON.stringify({
      id: trainingStore.id,
      type: trainingStore.type,
      actionDetail: trainingStore.actionDetail,
      unitRecords: trainingStore.unitRecords,
      trainingName: trainingStore.trainingName,
      totalSeconds: trainingStore.totalSeconds,
      trainingTimeText: trainingStore.trainingTimeText,
      min: trainingStore.min,
      isSystem: trainingStore.isSystem,
      isTraining: trainingStore.isTraining,
    }))
  }

  console.log('弹窗打开前,快照缓存:', trainingSnapshot.value);

  console.log('打印全局数据trainingStore:', trainingStore);




  console.log('info=', info);
  // 每次打开先清空当前store临时数据(保存计时功能,最小化可能在运行),避免上次缓存污染
  trainingStore.resetContentOnly();

  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.resetContentOnly()


  // ✅ 新增:如果有快照,把训练数据还回去
  if (trainingSnapshot.value) {
    Object.assign(trainingStore, trainingSnapshot.value)
    trainingSnapshot.value = null  // 清空口袋
  }

  console.log('关闭弹窗后,快照缓存:', trainingSnapshot.value);

}

// 【保存修改:核心,组装参数调用更新接口】
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]
    if (allUnits.length <= 1) {
      uni.showToast({ title: '每日模板至少保留1个动作组,无法删除', icon: 'none' })
      return
    }
    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
  }

  // ========================替换==================
  // =========【新增:替换动作分支,覆盖基础unit】=========
  let baseUnit = { ...unit }

  if (needReplaceUnit.value && replaceCacheUnit.value) {
    // 使用watch提前缓存好的替换单元作为基础载体
    baseUnit = { ...replaceCacheUnit.value }
  }
  // =====================================================


  let targetExercises = [...baseUnit.exercises]
  if (unit.unitType === 1) {
    // 单动作:exercises只有1个
    const exItem = targetExercises[0]
    const exerciseType = exItem.exerciseType;
    console.log('----------exerciseType---------', exerciseType);
    // expose出来的recordList
    const newSets = dongzuoSingleRef.value.recordList.map((item, idx) => {
      // 组件数据转回后端sets结构(和原页面save组装逻辑一致)
      let duration = 0
      let restTime = 0
      // 间歇动作单独取值
      if (exerciseType === 6) {
        duration = Number(item.duration) || 0
        restTime = Number(item.restTime) || 0
      } else {
        // 普通动作时分秒换算
        duration = Number(item.h) * 3600 + Number(item.m) * 60 + Number(item.s) || 0
        restTime = 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,
        restTime,
        isCompleted: item.isActive ? 1 : 0
      }
    })
    exItem.sets = newSets
  } else if (unit.unitType === 2) {
    // 超级组:superRecordMap{exId:[]}
    const superMap = dongzuoSingleRef.value.superRecordMap
    targetExercises.forEach(ex => {
      // 获得当前超级组的动作类型
      const exerciseType = ex.exerciseType;
      console.log('----------exerciseType---------', exerciseType);

      const setArr = superMap[ex.exerciseId] || []
      ex.sets = setArr.map((item, idx) => {
        let duration = 0
        let restTime = 0
        // 子动作是间歇则取专属字段
        if (exerciseType === 6) {
          duration = Number(item.duration) || 0
          restTime = Number(item.restTime) || 0
        } else {
          duration = Number(item.h) * 3600 + Number(item.m) * 60 + Number(item.s) || 0
          restTime = 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,
          restTime,
          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.resetContentOnly()

    // ✅ 新增:如果有快照,把训练数据还回去
    if (trainingSnapshot.value) {
      Object.assign(trainingStore, trainingSnapshot.value)
      trainingSnapshot.value = null
    }


  } 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: #242424;
  max-height: 70vh;
}
</style>