<template>
  <div class="training-camp-root">
    <!-- 训练营列表：左侧 30% + 营期 70% -->
    <div v-show="!periodWorkspace.periodId" class="app-container training-camp-page">
      <el-alert
        title="训练营直播间与普通直播相互独立：此处仅管理「训练营 → 营期」；进入营期后在「直播间」页签中管理直播。普通直播仍在「直播管理」中维护。"
        type="info"
        :closable="false"
        show-icon
        class="mb12"
      />

      <el-row :gutter="16">
        <el-col :span="7">
          <el-card shadow="never" class="box-card">
            <div slot="header" class="clearfix">
              <span>训练营</span>
              <el-button
                v-hasPermi="['live:trainingCamp:add']"
                style="float: right; padding: 3px 0"
                type="text"
                icon="el-icon-plus"
                @click="openCampForm()"
              >新建</el-button>
            </div>
            <el-table
              ref="campTable"
              v-loading="campLoading"
              :data="campList"
              highlight-current-row
              border
              size="small"
              @current-change="onCampChange"
            >
              <el-table-column label="名称" prop="campName" min-width="100" show-overflow-tooltip />
              <el-table-column label="排序" prop="sortOrder" width="56" align="center" />
              <el-table-column label="状态" width="68" align="center">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.status === 0" size="mini" type="success">正常</el-tag>
                  <el-tag v-else size="mini" type="info">停用</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="96" align="center" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    v-hasPermi="['live:trainingCamp:edit']"
                    type="text"
                    size="mini"
                    @click.stop="openCampForm(scope.row)"
                  >编辑</el-button>
                  <el-button
                    v-hasPermi="['live:trainingCamp:remove']"
                    type="text"
                    size="mini"
                    @click.stop="removeCamp(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <el-col :span="17">
          <el-card shadow="never" class="box-card box-card-period">
            <div slot="header" class="period-header">
              <div class="period-header-left">
                <span>营期</span>
                <span v-if="currentCamp" class="sub-hint">（{{ currentCamp.campName }}）</span>
              </div>
              <div class="period-header-actions">
                <el-button
                  type="primary"
                  plain
                  size="small"
                  icon="el-icon-right"
                  :disabled="!currentPeriod"
                  @click="enterPeriodWorkspace(currentPeriod)"
                >进入营期</el-button>
                <el-button
                  v-hasPermi="['live:trainingCamp:add']"
                  type="primary"
                  size="small"
                  icon="el-icon-plus"
                  :disabled="!currentCamp"
                  @click="openPeriodForm()"
                >新建营期</el-button>
              </div>
            </div>
            <el-empty v-if="!currentCamp" description="请先选择训练营" :image-size="64" />
            <el-table
              v-else
              ref="periodTable"
              v-loading="periodLoading"
              :data="periodList"
              highlight-current-row
              border
              size="small"
              @current-change="onPeriodChange"
            >
              <el-table-column label="营期名称" prop="periodName" min-width="120" show-overflow-tooltip />
              <el-table-column label="营期图" width="76" align="center">
                <template slot-scope="scope">
                  <el-image
                    v-if="scope.row.periodImgUrl"
                    class="period-thumb"
                    :src="scope.row.periodImgUrl"
                    fit="cover"
                    :preview-src-list="[scope.row.periodImgUrl]"
                  />
                  <span v-else class="period-thumb-empty">—</span>
                </template>
              </el-table-column>
              <el-table-column label="开始" prop="startTime" width="100" show-overflow-tooltip>
                <template slot-scope="scope">{{ formatDt(scope.row.startTime) }}</template>
              </el-table-column>
              <el-table-column label="结束" prop="endTime" width="100" show-overflow-tooltip>
                <template slot-scope="scope">{{ formatDt(scope.row.endTime) }}</template>
              </el-table-column>
              <el-table-column label="操作" width="168" align="center" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-right"
                    @click.stop="enterPeriodWorkspace(scope.row)"
                  >进入营期</el-button>
                  <el-button
                    v-hasPermi="['live:trainingCamp:edit']"
                    type="text"
                    size="mini"
                    @click.stop="openPeriodForm(scope.row)"
                  >编辑</el-button>
                  <el-button
                    v-hasPermi="['live:trainingCamp:remove']"
                    type="text"
                    size="mini"
                    @click.stop="removePeriod(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <period-workspace
      v-show="periodWorkspace.periodId"
      ref="periodWorkspaceRef"
      :workspace="periodWorkspace"
      @back="closePeriodWorkspace"
      @add-live="openLiveForm"
      @edit-live="openLiveFormEdit"
    />

    <!-- 训练营表单 -->
    <el-dialog :title="campForm.campId ? '编辑训练营' : '新建训练营'" :visible.sync="campOpen" width="480px" append-to-body>
      <el-form ref="campFormRef" :model="campForm" :rules="campRules" label-width="88px">
        <el-form-item label="名称" prop="campName">
          <el-input v-model="campForm.campName" maxlength="128" show-word-limit placeholder="训练营名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="campForm.sortOrder" :min="0" :max="9999" controls-position="right" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="campForm.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="campForm.description" type="textarea" rows="3" maxlength="512" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="campOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitCamp">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 营期表单 -->
    <el-dialog :title="periodForm.periodId ? '编辑营期' : '新建营期'" :visible.sync="periodOpen" width="520px" append-to-body>
      <el-form ref="periodFormRef" :model="periodForm" :rules="periodRules" label-width="88px">
        <el-form-item label="营期名称" prop="periodName">
          <el-input v-model="periodForm.periodName" maxlength="128" show-word-limit />
        </el-form-item>
        <el-form-item label="营期图片" prop="periodImgUrl">
          <image-upload v-model="periodForm.periodImgUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="periodForm.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="periodForm.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="periodForm.sortOrder" :min="0" :max="9999" controls-position="right" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="periodForm.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="periodForm.description" type="textarea" rows="3" maxlength="512" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="periodOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitPeriod">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增/修改直播间（与「直播管理」表单一致；新增走营期接口，修改走直播更新接口） -->
    <el-dialog :title="liveUpsertMode === 'edit' ? '修改直播间' : '添加直播间'" :visible.sync="liveOpen" width="900px" append-to-body>
      <el-form ref="liveUpsertFormRef" :model="liveUpsertForm" :rules="liveUpsertRules" label-width="80px">
        <el-form-item label="直播名称" prop="liveName">
          <el-input v-model="liveUpsertForm.liveName" placeholder="请输入直播名称" />
        </el-form-item>
        <el-form-item label="显示类型" prop="showType">
          <el-radio-group v-model="liveUpsertForm.showType">
            <el-radio :label="1">横屏</el-radio>
            <el-radio :label="2">竖屏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="直播类型" prop="liveType">
          <el-radio-group v-model="liveUpsertForm.liveType">
            <el-radio
              v-for="item in liveTypeDictList"
              :key="item.dictValue"
              :label="parseInt(item.dictValue)"
            >
              {{ item.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="直播描述" prop="liveDesc">
          <Editor ref="liveUpsertEditor" :height="300" @on-text-change="onLiveDescChange" />
        </el-form-item>
        <el-form-item label="录播视屏" prop="videoUrl" v-if="liveUpsertForm.liveType == 2">
          <video-upload
            :fileKey.sync="liveUpsertForm.fileKey"
            :fileSize.sync="liveUpsertForm.fileSize"
            :videoUrl.sync="liveUpsertForm.videoUrl"
            :fileName.sync="liveUpsertForm.fileName"
            :line_1.sync="liveUpsertForm.lineOne"
            :uploadType.sync="liveUpsertForm.uploadType"
            :isTranscode.sync="liveUpsertForm.isTranscode"
            ref="liveUpsertVideoUpload"
            :transcodeFileKey.sync="liveUpsertForm.transcodeFileKey"
            @video-duration="onLiveVideoDuration"
            @change="onLiveVideoChange"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            size="small"
            v-model="liveUpsertForm.startTime"
            @change="onLiveStartTimeChange"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="{
              timePickerOptions: {
                selectableRange: '00:00:00 - 23:59:59',
                format: 'HH:mm:ss'
              }
            }"
            placeholder="选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="finishTime" v-loading="liveTimeLoading">
          <el-date-picker
            size="small"
            v-model="liveUpsertForm.finishTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="{
              timePickerOptions: {
                selectableRange: '00:00:00 - 23:59:59',
                format: 'HH:mm:ss'
              }
            }"
            placeholder="视屏播放结束"
          />
        </el-form-item>
        <el-form-item label="直播封面" prop="liveImgUrl">
          <image-upload v-model="liveUpsertForm.liveImgUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="上下架" prop="isShow">
          <el-radio-group v-model="liveUpsertForm.isShow">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitLive">确 定</el-button>
        <el-button @click="cancelLiveDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTrainingCamp,
  addTrainingCamp,
  updateTrainingCamp,
  delTrainingCamp,
  listTrainingPeriod,
  addTrainingPeriod,
  updateTrainingPeriod,
  delTrainingPeriod,
  addTrainingLive,
  getTrainingPeriod
} from '@/api/live/trainingCamp'
import { getLive, updateLive } from '@/api/live/live'
import PeriodWorkspace from './PeriodWorkspace.vue'
import Editor from '@/components/Editor/wang'
import VideoUpload from '@/components/LiveVideoUpload/single.vue'

export default {
  name: 'LiveTrainingCamp',
  components: { PeriodWorkspace, Editor, VideoUpload },
  data() {
    return {
      campLoading: false,
      periodLoading: false,
      campList: [],
      periodList: [],
      currentCamp: null,
      currentPeriod: null,
      campOpen: false,
      periodOpen: false,
      liveOpen: false,
      /** add | edit */
      liveUpsertMode: 'add',
      campForm: {},
      periodForm: {},
      liveTypeDictList: [],
      liveUpsertForm: {
        uploadType: 1,
        isTranscode: 0,
        transcodeFileKey: null,
        videoUrl: null,
        fileKey: null,
        fileName: null,
        fileSize: null,
        lineOne: null
      },
      liveVideoUrl: '',
      liveTimeLoading: false,
      periodWorkspace: {
        periodId: null,
        periodName: '',
        campName: '',
        periodImgUrl: '',
        startTime: null,
        endTime: null
      },
      campRules: {
        campName: [{ required: true, message: '请输入训练营名称', trigger: 'blur' }]
      },
      periodRules: {
        periodName: [{ required: true, message: '请输入营期名称', trigger: 'blur' }]
      },
      liveUpsertRules: {
        liveName: [{ required: true, message: '不能为空', trigger: 'blur' }],
        showType: [{ required: true, message: '不能为空', trigger: 'blur' }],
        liveType: [{ required: true, message: '不能为空', trigger: 'blur' }],
        startTime: [{ required: true, message: '不能为空', trigger: 'blur' }],
        liveImgUrl: [{ required: true, message: '不能为空', trigger: 'blur' }],
        isShow: [{ required: true, message: '不能为空', trigger: 'change' }]
      }
    }
  },
  watch: {
    'liveUpsertForm.startTime': {
      handler(newVal) {
        if (!newVal) return
        const timeObj = new Date(newVal)
        if (isNaN(timeObj.getTime())) return
        timeObj.setSeconds(1)
        const formattedSeconds = this.padTime(timeObj.getSeconds())
        const year = timeObj.getFullYear()
        const month = this.padTime(timeObj.getMonth() + 1)
        const day = this.padTime(timeObj.getDate())
        const hours = this.padTime(timeObj.getHours())
        const minutes = this.padTime(timeObj.getMinutes())
        this.liveUpsertForm.startTime = `${year}-${month}-${day} ${hours}:${minutes}:${formattedSeconds}`
      },
      immediate: true,
      deep: false
    },
    '$route.query.periodId'(val) {
      if (!val) {
        this.resetWorkspaceState(false)
        return
      }
      const id = Number(val)
      if (Number.isNaN(id)) return
      if (this.periodWorkspace.periodId === id) return
      this.restoreWorkspaceFromRoute(id)
    }
  },
  created() {
    this.loadCamps()
    this.getDicts('live_type').then(response => {
      this.liveTypeDictList = response.data
    })
    const pid = this.$route.query.periodId
    if (pid) {
      const id = Number(pid)
      if (!Number.isNaN(id)) {
        this.$nextTick(() => this.restoreWorkspaceFromRoute(id))
      }
    }
  },
  methods: {
    formatDt(val) {
      if (!val) return '—'
      const s = String(val).replace('T', ' ')
      return s.length >= 16 ? s.slice(0, 16) : s
    },
    resetWorkspaceState(updateRoute) {
      this.periodWorkspace = {
        periodId: null,
        periodName: '',
        campName: '',
        periodImgUrl: '',
        startTime: null,
        endTime: null
      }
      if (updateRoute !== false) {
        const q = { ...this.$route.query }
        delete q.periodId
        this.$router.replace({ path: this.$route.path, query: q }).catch(() => {})
      }
    },
    enterPeriodWorkspace(row) {
      if (!row || !row.periodId) {
        this.$message.warning('请先选中一行营期，或点击操作栏「进入营期」')
        return
      }
      const campName = (this.currentCamp && this.currentCamp.campName) || row.campName || ''
      this.periodWorkspace = {
        periodId: row.periodId,
        periodName: row.periodName || '',
        campName,
        periodImgUrl: row.periodImgUrl || '',
        startTime: row.startTime || null,
        endTime: row.endTime || null
      }
      this.$router.replace({
        path: this.$route.path,
        query: { ...this.$route.query, periodId: String(row.periodId) }
      }).catch(() => {})
    },
    restoreWorkspaceFromRoute(periodId) {
      getTrainingPeriod(periodId).then(res => {
        const data = res.data
        if (!data) {
          this.$message.error('营期不存在或无权限')
          this.resetWorkspaceState()
          return
        }
        this.periodWorkspace = {
          periodId: data.periodId,
          periodName: data.periodName || '',
          campName: data.campName || '',
          periodImgUrl: data.periodImgUrl || '',
          startTime: data.startTime || null,
          endTime: data.endTime || null
        }
      }).catch(() => {
        this.resetWorkspaceState()
      })
    },
    closePeriodWorkspace() {
      this.resetWorkspaceState(true)
    },
    loadCamps() {
      this.campLoading = true
      listTrainingCamp({ pageNum: 1, pageSize: 500 }).then(res => {
        this.campList = res.rows || []
        this.campLoading = false
        this.$nextTick(() => {
          if (this.currentCamp) {
            const hit = this.campList.find(c => c.campId === this.currentCamp.campId)
            if (hit) {
              this.$refs.campTable && this.$refs.campTable.setCurrentRow(hit)
            } else {
              this.currentCamp = null
              this.currentPeriod = null
              this.periodList = []
            }
          }
        })
      }).catch(() => { this.campLoading = false })
    },
    onCampChange(row) {
      this.currentCamp = row || null
      this.currentPeriod = null
      this.periodList = []
      if (!row) return
      this.loadPeriods()
    },
    loadPeriods() {
      if (!this.currentCamp) return
      this.periodLoading = true
      listTrainingPeriod({ campId: this.currentCamp.campId, pageNum: 1, pageSize: 500 }).then(res => {
        this.periodList = res.rows || []
        this.periodLoading = false
      }).catch(() => { this.periodLoading = false })
    },
    onPeriodChange(row) {
      this.currentPeriod = row || null
    },
    openCampForm(row) {
      this.campForm = row
        ? { ...row }
        : { campName: '', sortOrder: 0, status: 0, description: '' }
      this.campOpen = true
      this.$nextTick(() => this.$refs.campFormRef && this.$refs.campFormRef.clearValidate())
    },
    submitCamp() {
      this.$refs.campFormRef.validate(valid => {
        if (!valid) return
        const req = this.campForm.campId ? updateTrainingCamp(this.campForm) : addTrainingCamp(this.campForm)
        req.then(res => {
          this.$message.success((res && res.msg) || '保存成功')
          this.campOpen = false
          this.loadCamps()
        })
      })
    },
    removeCamp(row) {
      this.$confirm('确认删除训练营「' + row.campName + '」？须先清空营期。').then(() => {
        return delTrainingCamp(row.campId)
      }).then(res => {
        this.$message.success((res && res.msg) || '已删除')
        if (this.currentCamp && this.currentCamp.campId === row.campId) {
          this.currentCamp = null
          this.currentPeriod = null
          this.periodList = []
        }
        this.loadCamps()
      }).catch(() => {})
    },
    openPeriodForm(row) {
      if (!this.currentCamp) return
      this.periodForm = row
        ? { ...row, campId: row.campId }
        : {
          campId: this.currentCamp.campId,
          periodName: '',
          periodImgUrl: '',
          startTime: null,
          endTime: null,
          sortOrder: 0,
          status: 0,
          description: ''
        }
      this.periodOpen = true
      this.$nextTick(() => this.$refs.periodFormRef && this.$refs.periodFormRef.clearValidate())
    },
    submitPeriod() {
      this.$refs.periodFormRef.validate(valid => {
        if (!valid) return
        const req = this.periodForm.periodId ? updateTrainingPeriod(this.periodForm) : addTrainingPeriod(this.periodForm)
        req.then(res => {
          this.$message.success((res && res.msg) || '保存成功')
          this.periodOpen = false
          if (this.periodWorkspace.periodId && this.periodForm.periodId === this.periodWorkspace.periodId) {
            this.periodWorkspace = {
              ...this.periodWorkspace,
              periodName: this.periodForm.periodName || '',
              periodImgUrl: this.periodForm.periodImgUrl || '',
              startTime: this.periodForm.startTime || null,
              endTime: this.periodForm.endTime || null
            }
          }
          this.loadPeriods()
        })
      })
    },
    removePeriod(row) {
      this.$confirm('确认删除营期「' + row.periodName + '」？须先删除营期下直播间。').then(() => {
        return delTrainingPeriod(row.periodId)
      }).then(res => {
        this.$message.success((res && res.msg) || '已删除')
        if (this.currentPeriod && this.currentPeriod.periodId === row.periodId) {
          this.currentPeriod = null
        }
        if (this.periodWorkspace.periodId === row.periodId) {
          this.closePeriodWorkspace()
        }
        this.loadPeriods()
      }).catch(() => {})
    },
    initLiveUpsertDefaults() {
      this.liveUpsertForm = {
        showType: 1,
        liveType: 2,
        isShow: 1,
        isTranscode: 0,
        uploadType: 1,
        transcodeFileKey: null
      }
      this.liveVideoUrl = ''
    },
    cancelLiveDialog() {
      this.liveOpen = false
      this.liveUpsertMode = 'add'
      this.initLiveUpsertDefaults()
    },
    padTime(n) {
      return n < 10 ? `0${n}` : String(n)
    },
    formatLiveEndDate(date) {
      const y = date.getFullYear()
      const m = (date.getMonth() + 1).toString().padStart(2, '0')
      const d = date.getDate().toString().padStart(2, '0')
      const h = date.getHours().toString().padStart(2, '0')
      const min = date.getMinutes().toString().padStart(2, '0')
      const s = date.getSeconds().toString().padStart(2, '0')
      return `${y}-${m}-${d} ${h}:${min}:${s}`
    },
    onLiveStartTimeChange() {
      if (!this.liveUpsertForm.startTime) return
      if (!this.liveUpsertForm.duration) return
      const startDateTime = new Date(this.liveUpsertForm.startTime)
      const endDateTime = new Date(startDateTime.getTime() + this.liveUpsertForm.duration * 1000)
      this.liveUpsertForm.finishTime = this.formatLiveEndDate(endDateTime)
    },
    onLiveVideoDuration(duration) {
      this.liveUpsertForm.duration = duration
    },
    onLiveVideoChange(videoUrl) {
      this.liveVideoUrl = videoUrl
      this.liveUpsertForm.videoUrl = videoUrl
    },
    onLiveDescChange(text) {
      setTimeout(() => {
        this.liveUpsertForm.liveDesc = text
      }, 1)
    },
    openLiveForm() {
      if (!this.periodWorkspace.periodId) {
        this.$message.warning('请先进入营期')
        return
      }
      this.liveUpsertMode = 'add'
      this.initLiveUpsertDefaults()
      this.liveOpen = true
      this.$nextTick(() => {
        if (this.$refs.liveUpsertFormRef) {
          this.$refs.liveUpsertFormRef.clearValidate()
        }
        setTimeout(() => {
          if (this.$refs.liveUpsertEditor) {
            this.$refs.liveUpsertEditor.setText('')
          }
          if (this.$refs.liveUpsertVideoUpload) {
            this.$refs.liveUpsertVideoUpload.reset()
          }
        }, 100)
      })
    },
    openLiveFormEdit(row) {
      if (!this.periodWorkspace.periodId) {
        this.$message.warning('请先进入营期')
        return
      }
      if (!row || !row.liveId) {
        this.$message.warning('直播间信息无效')
        return
      }
      this.liveUpsertMode = 'edit'
      getLive(row.liveId).then(res => {
        const d = res.data
        if (!d) {
          this.$message.error('获取直播间失败')
          this.liveUpsertMode = 'add'
          return
        }
        this.liveUpsertForm = { ...d }
        this.liveVideoUrl = d.videoUrl || ''
        this.liveOpen = true
        this.$nextTick(() => {
          if (this.$refs.liveUpsertFormRef) {
            this.$refs.liveUpsertFormRef.clearValidate()
          }
          setTimeout(() => {
            if (this.$refs.liveUpsertEditor) {
              this.$refs.liveUpsertEditor.setText(d.liveDesc || '')
            }
            if (d.videoUrl) {
              this.liveUpsertForm.videoUrl = d.videoUrl
            }
          }, 100)
        })
      }).catch(() => {
        this.liveUpsertMode = 'add'
      })
    },
    submitLive() {
      if (this.liveUpsertForm.liveType === 2 && (!this.liveVideoUrl || this.liveVideoUrl.length === 0)) {
        this.$message.error('请上传视频')
        return
      }
      this.$refs.liveUpsertFormRef.validate(valid => {
        if (!valid) return
        if (!this.periodWorkspace.periodId) {
          this.$message.warning('营期已失效，请返回列表重新进入')
          return
        }
        const body = { ...this.liveUpsertForm }
        body.videoUrl = this.liveVideoUrl
        body.trainingPeriodId = this.periodWorkspace.periodId
        if (this.liveUpsertMode === 'add') {
          delete body.liveId
          addTrainingLive(body).then(res => {
            this.$message.success((res && res.msg) || '新增成功')
            this.liveOpen = false
            this.liveUpsertMode = 'add'
            this.initLiveUpsertDefaults()
            this.$refs.periodWorkspaceRef && this.$refs.periodWorkspaceRef.refreshLiveList()
          })
        } else {
          if (!body.liveId) {
            this.$message.error('缺少直播间ID')
            return
          }
          updateLive(body).then(res => {
            this.$message.success((res && res.msg) || '修改成功')
            this.liveOpen = false
            this.liveUpsertMode = 'add'
            this.initLiveUpsertDefaults()
            this.$refs.periodWorkspaceRef && this.$refs.periodWorkspaceRef.refreshLiveList()
          })
        }
      })
    },
  }
}
</script>

<style scoped>
.training-camp-root {
  min-height: 100%;
}
.training-camp-page .mb12 {
  margin-bottom: 12px;
}
.box-card {
  min-height: 420px;
}
.box-card-period {
  min-height: 420px;
}
.period-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 8px;
}
.period-header-left {
  flex: 1;
  min-width: 0;
}
.period-header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}
.sub-hint {
  color: #909399;
  font-size: 12px;
  margin-left: 6px;
}
.period-thumb {
  width: 48px;
  height: 48px;
  border-radius: 4px;
  vertical-align: middle;
}
.period-thumb-empty {
  color: #c0c4cc;
  font-size: 12px;
}
</style>
