<template>
  <div class="martial-dispatch-container">
    <div class="page-header">
      <el-button icon="el-icon-back" size="small" @click="goBack">返回</el-button>
      <h2 class="page-title">调度</h2>
    </div>

    <div class="tabs-section">
        <div class="tab-buttons">
          <el-button size="small" type="primary">竞赛分组</el-button>
        </div>

        <div class="tab-content">
          <!-- 场地选择器 -->
          <div class="venue-selector">
            <el-button
              v-for="venue in venues"
              :key="venue.id"
              size="small"
              :type="selectedVenueId === venue.id ? 'primary' : ''"
              @click="selectedVenueId = venue.id; loadDispatchData()"
            >
              {{ venue.venueName }}
            </el-button>
          </div>

          <!-- 时间段选择器 -->
          <div class="time-selector">
            <el-button
              v-for="(time, index) in timeSlots"
              :key="index"
              size="small"
              :type="selectedTime === index ? 'primary' : ''"
              @click="selectedTime = index; loadDispatchData()"
            >
              {{ time }}
            </el-button>
            <el-button size="small" plain style="margin-left: auto;" @click="handleBatchComplete">
              批次完赛
            </el-button>
          </div>

          <div v-for="(group, index) in dispatchGroups" :key="index" class="dispatch-group">
            <div class="group-header">
              <div class="group-info">
                <span class="group-title">{{ group.title }}</span>
                <span class="group-meta">{{ group.type }}</span>
                <span class="group-meta">{{ group.count }}</span>
                <span class="group-meta">{{ group.code }}</span>
              </div>
              <div class="group-actions">
                <div class="toggle-buttons">
                  <el-button size="small" :type="group.viewMode === 'dispatch' ? 'primary' : ''" @click="setViewMode(index, 'dispatch')">
                    调度列表
                  </el-button>
                  <el-button size="small" :type="group.viewMode === 'menu' ? 'primary' : 'success'" @click="setViewMode(index, 'menu')">
                    {{ group.venueType === 1 ? '一号场地' : '二号场地' }}
                  </el-button>
                </div>
                <el-button size="small" type="danger">赛程</el-button>
              </div>
            </div>

            <el-table :data="group.items" border stripe size="small">
              <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
              <el-table-column prop="schoolUnit" label="学校/单位" min-width="200"></el-table-column>
              <el-table-column label="状态" width="100" align="center">
                <template #default="scope">
                  <el-tag v-if="scope.row.completed" type="success" size="small">已完赛</el-tag>
                  <el-tag v-else type="warning" size="small">未完赛</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="裁判" width="100" align="center">
                <template #default="scope">
                  <el-tag v-if="scope.row.refereed" type="success" size="small">已裁判</el-tag>
                  <el-tag v-else type="danger" size="small">未裁判</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template #default="scope">
                  <el-button
                    link
                    size="small"
                    @click="handleMoveUp(index, scope.$index)"
                    :disabled="scope.$index === 0"
                    title="上移"
                    class="move-btn"
                  >
                    <img src="/img/图标 3@3x.png" class="move-icon" alt="上移" />
                  </el-button>
                  <el-button
                    link
                    size="small"
                    @click="handleMoveDown(index, scope.$index)"
                    :disabled="scope.$index === group.items.length - 1"
                    title="下移"
                    class="move-btn"
                  >
                    <img src="/img/图标 4@3x.png" class="move-icon" alt="下移" />
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 保存按钮 -->
          <div class="dispatch-footer" v-if="dispatchGroups.length > 0">
            <el-button @click="goBack">返回</el-button>
            <el-button type="primary" @click="handleSaveDispatch" :disabled="!hasChanges">
              保存调度
            </el-button>
          </div>
        </div>
      </div>
  </div>
</template>

<script>
import { getVenuesByCompetition } from '@/api/martial/venue'
import { getCompetitionDetail } from '@/api/martial/competition'
import { getDispatchData, saveDispatch, getScheduleResult } from '@/api/martial/activitySchedule'

export default {
  name: 'MartialDispatchList',
  data() {
    return {
      competitionId: null,
      loading: false,
      selectedTime: 0,
      selectedVenueId: null,
      venues: [], // 场地列表
      timeSlots: [], // 时间段列表
      dispatchGroups: [], // 调度分组列表
      hasChanges: false, // 是否有未保存的更改
      originalData: null // 原始数据（用于取消时恢复）
    }
  },
  async mounted() {
    this.competitionId = this.$route.query.competitionId
    if (this.competitionId) {
      // 先检查编排状态
      await this.checkScheduleStatus()
      this.loadCompetitionInfo()
      this.loadVenues()
    } else {
      this.$message.warning('未获取到赛事ID')
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },

    // 检查编排状态
    async checkScheduleStatus() {
      try {
        const res = await getScheduleResult(this.competitionId)
        const scheduleStatus = res.data?.data?.scheduleStatus || res.data?.scheduleStatus || 0

        console.log('编排状态:', scheduleStatus)

        // 如果编排未完成（状态不是2），提示用户并返回
        if (scheduleStatus !== 2) {
          this.$message.warning('请先完成编排并锁定后，才能进行调度操作')
          // 延迟返回上一页
          setTimeout(() => {
            this.$router.go(-1)
          }, 2000)
          return false
        }

        return true
      } catch (error) {
        console.error('检查编排状态失败:', error)
        this.$message.error('无法获取编排状态，请稍后重试')
        setTimeout(() => {
          this.$router.go(-1)
        }, 2000)
        return false
      }
    },

    // 加载赛事信息
    async loadCompetitionInfo() {
      try {
        this.loading = true
        const res = await getCompetitionDetail(this.competitionId)
        const data = res.data?.data

        if (data) {
          // 生成时间段
          this.generateTimeSlots(data.competitionStartTime || data.competition_start_time, data.competitionEndTime || data.competition_end_time)
        }
      } catch (err) {
        console.error('加载赛事信息失败', err)
        this.$message.error('加载赛事信息失败')
      } finally {
        this.loading = false
      }
    },

    // 生成时间段列表
    generateTimeSlots(startTime, endTime) {
      if (!startTime || !endTime) {
        this.timeSlots = ['2025年11月6日 上午8:30', '2025年11月6日 下午13:30']
        return
      }

      const slots = []
      const start = new Date(startTime)
      const end = new Date(endTime)
      let currentDate = new Date(start)

      while (currentDate <= end) {
        const year = currentDate.getFullYear()
        const month = currentDate.getMonth() + 1
        const day = currentDate.getDate()
        const dateStr = `${year}年${month}月${day}日`

        slots.push(`${dateStr} 上午8:30`)
        slots.push(`${dateStr} 下午13:30`)

        currentDate.setDate(currentDate.getDate() + 1)
      }

      this.timeSlots = slots
    },

    // 加载场地列表
    async loadVenues() {
      try {
        this.loading = true
        const res = await getVenuesByCompetition(this.competitionId)
        const venuesData = res.data?.data?.records || res.data?.data || []

        if (venuesData.length === 0) {
          this.$message.warning('该赛事暂无场地信息')
          this.venues = []
        } else {
          this.venues = venuesData.map(v => ({
            id: v.id,
            venueName: v.venueName || v.venue_name
          }))
          // 默认选中第一个场地
          if (this.venues.length > 0) {
            this.selectedVenueId = this.venues[0].id
            this.loadDispatchData()
          }
        }
      } catch (err) {
        console.error('加载场地失败', err)
        this.$message.error('加载场地失败')
        this.venues = []
      } finally {
        this.loading = false
      }
    },

    // 加载调度数据
    async loadDispatchData() {
      if (!this.selectedVenueId || this.selectedTime === null) {
        this.dispatchGroups = []
        return
      }

      try {
        this.loading = true
        const res = await getDispatchData({
          competitionId: this.competitionId,
          venueId: this.selectedVenueId,
          timeSlotIndex: this.selectedTime
        })

        if (res.data.success) {
          const groups = res.data.data.groups || []
          this.dispatchGroups = groups.map(group => ({
            ...group,
            viewMode: 'dispatch',
            title: group.groupName,
            items: group.participants.map(p => ({
              ...p,
              schoolUnit: p.organization,
              completed: false,
              refereed: false
            }))
          }))
          // 保存原始数据
          this.originalData = JSON.parse(JSON.stringify(this.dispatchGroups))
          this.hasChanges = false
        } else {
          this.$message.error(res.data.msg || '加载调度数据失败')
        }
      } catch (error) {
        console.error('加载调度数据失败:', error)
        this.$message.error('加载调度数据失败')
      } finally {
        this.loading = false
      }
    },

    setViewMode(index, mode) {
      this.dispatchGroups[index].viewMode = mode
      this.$message.success(`已切换到${mode === 'dispatch' ? '调度列表' : '场地'}模式`)
    },

    handleMoveUp(groupIndex, itemIndex) {
      if (itemIndex === 0) return
      const group = this.dispatchGroups[groupIndex]
      const temp = group.items[itemIndex]
      group.items.splice(itemIndex, 1)
      group.items.splice(itemIndex - 1, 0, temp)

      // 更新顺序号
      group.items.forEach((item, index) => {
        item.performanceOrder = index + 1
      })

      this.hasChanges = true
      this.$message.success('上移成功')
    },

    handleMoveDown(groupIndex, itemIndex) {
      const group = this.dispatchGroups[groupIndex]
      if (itemIndex === group.items.length - 1) return
      const temp = group.items[itemIndex]
      group.items.splice(itemIndex, 1)
      group.items.splice(itemIndex + 1, 0, temp)

      // 更新顺序号
      group.items.forEach((item, index) => {
        item.performanceOrder = index + 1
      })

      this.hasChanges = true
      this.$message.success('下移成功')
    },

    handleBatchComplete() {
      this.$confirm('确定要标记当前批次所有为完赛状态吗？', '批次完赛', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dispatchGroups.forEach(group => {
          group.items.forEach(item => {
            item.completed = true
          })
        })
        this.$message.success('批次完赛成功')
      }).catch(() => {})
    },

    // 保存调度
    async handleSaveDispatch() {
      if (!this.hasChanges) {
        this.$message.info('没有需要保存的更改')
        return
      }

      try {
        this.loading = true

        const adjustments = this.dispatchGroups.map(group => ({
          detailId: group.detailId,
          participants: group.items.map(p => ({
            id: p.id,
            performanceOrder: p.performanceOrder
          }))
        }))

        const res = await saveDispatch({
          competitionId: this.competitionId,
          adjustments
        })

        if (res.data.success) {
          this.$message.success('调度保存成功')
          this.hasChanges = false
          await this.loadDispatchData()
        } else {
          this.$message.error(res.data.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存调度失败:', error)
        this.$message.error('保存失败，请稍后重试')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.martial-dispatch-container {
  padding: 15px;
  background: #fff;

  .page-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    gap: 10px;

    .page-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }

  .tabs-section {
    .tab-buttons {
      margin-bottom: 15px;
      display: flex;
      gap: 8px;
    }

    .tab-content {
      .venue-selector {
        margin-bottom: 15px;
        display: flex;
        gap: 8px;
        align-items: center;
        flex-wrap: wrap;
      }

      .time-selector {
        margin-bottom: 15px;
        display: flex;
        gap: 8px;
        align-items: center;
        flex-wrap: wrap;
      }

      .dispatch-group {
        margin-bottom: 15px;

        .group-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 10px 14px;
          background: #f5f7fa;
          border: 1px solid #e4e7ed;
          border-bottom: none;

          .group-info {
            display: flex;
            align-items: center;
            gap: 12px;

            .group-title {
              font-weight: 600;
              color: #2c3e50;
              font-size: 13px;
            }

            .group-meta {
              color: #909399;
              font-size: 12px;
            }
          }

          .group-actions {
            display: flex;
            gap: 8px;
            align-items: center;

            .toggle-buttons {
              display: flex;
              gap: 4px;
            }
          }
        }
      }
    }
  }

  .move-btn {
    padding: 4px;

    &:disabled {
      opacity: 0.4;
      cursor: not-allowed;
    }
  }

  .move-icon {
    width: 20px;
    height: 20px;
    display: inline-block;
    vertical-align: middle;
  }

  .dispatch-footer {
    margin-top: 30px;
    text-align: center;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;

    .el-button {
      min-width: 120px;
    }
  }
}
</style>
