<template>
  <div class="martial-order-container">
    <el-card shadow="hover">
      <div class="page-header">
        <h2 class="page-title">订单管理</h2>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索赛事名称"
            clearable
            size="small"
            style="width: 240px"
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.status"
            placeholder="赛事状态"
            clearable
            size="small"
            style="width: 180px"
          >
            <el-option label="未开始" :value="1"></el-option>
            <el-option label="报名中" :value="2"></el-option>
            <el-option label="进行中" :value="3"></el-option>
            <el-option label="已结束" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        size="small"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="competitionName" label="赛事名称" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="competitionCode" label="赛事编号" width="150"></el-table-column>
        <el-table-column prop="organizer" label="主办单位" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="location" label="举办地点" width="120"></el-table-column>
        <el-table-column prop="registrationTime" label="报名时间" width="180" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDateRange(scope.row.registrationStartTime, scope.row.registrationEndTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="competitionTime" label="比赛时间" width="180" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDateRange(scope.row.competitionStartTime, scope.row.competitionEndTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="90" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleRegistrationDetail(scope.row)">报名详情</el-button>
            <el-button type="success" size="small" @click="handleSchedule(scope.row)">编排</el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleDispatch(scope.row)"
              :title="isScheduleCompleted(scope.row.id) ? '进入调度' : '请先完成编排'"
            >
              调度
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.size"
        layout="total, sizes, prev, pager, next"
        :total="pagination.total"
        small
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
import { getCompetitionList } from '@/api/martial/competition'
import { getScheduleResult } from '@/api/martial/activitySchedule'

export default {
  name: 'MartialOrderList',
  data() {
    return {
      loading: false,
      searchForm: {
        keyword: '',
        status: null
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      scheduleStatusMap: {} // 存储每个赛事的编排状态
    }
  },
  mounted() {
    this.loadCompetitionList()
  },
  activated() {
    // 当页面被激活时（从其他页面返回），重新加载编排状态
    if (this.tableData.length > 0) {
      this.loadScheduleStatus()
    }
  },
  methods: {
    // 加载赛事列表
    loadCompetitionList() {
      this.loading = true
      const params = {}

      if (this.searchForm.keyword) {
        params.competitionName = this.searchForm.keyword
      }
      if (this.searchForm.status !== null && this.searchForm.status !== '') {
        params.status = this.searchForm.status
      }

      getCompetitionList(this.pagination.current, this.pagination.size, params)
        .then(res => {
          console.log('赛事列表返回数据:', res)
          const responseData = res.data?.data
          if (responseData && responseData.records) {
            // 处理赛事数据，兼容驼峰和下划线命名
            this.tableData = responseData.records.map(competition => ({
              id: competition.id,
              competitionName: competition.competitionName || competition.competition_name,
              competitionCode: competition.competitionCode || competition.competition_code,
              organizer: competition.organizer,
              location: competition.location,
              venue: competition.venue,
              registrationStartTime: competition.registrationStartTime || competition.registration_start_time,
              registrationEndTime: competition.registrationEndTime || competition.registration_end_time,
              competitionStartTime: competition.competitionStartTime || competition.competition_start_time,
              competitionEndTime: competition.competitionEndTime || competition.competition_end_time,
              status: competition.status,
              createTime: competition.createTime || competition.create_time
            }))
            this.pagination.total = responseData.total || 0

            // 加载每个赛事的编排状态
            this.loadScheduleStatus()
          }
        })
        .catch(err => {
          console.error('加载赛事列表失败', err)
          this.$message.error('加载赛事列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 加载编排状态
    async loadScheduleStatus() {
      for (const competition of this.tableData) {
        try {
          const res = await getScheduleResult(competition.id)
          if (res.data?.data) {
            this.$set(this.scheduleStatusMap, competition.id, res.data.data.isCompleted || false)
          } else {
            this.$set(this.scheduleStatusMap, competition.id, false)
          }
        } catch (err) {
          // 如果获取失败，默认为未完成
          this.$set(this.scheduleStatusMap, competition.id, false)
        }
      }
    },

    // 检查编排是否完成
    isScheduleCompleted(competitionId) {
      return this.scheduleStatusMap[competitionId] === true
    },

    handleSearch() {
      this.pagination.current = 1
      this.loadCompetitionList()
    },

    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadCompetitionList()
    },

    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadCompetitionList()
    },

    // 查看报名详情 - 传递赛事ID
    handleRegistrationDetail(row) {
      this.$router.push({
        path: '/martial/registration/detail',
        query: { competitionId: row.id }
      })
    },

    // 编排 - 传递赛事ID
    handleSchedule(row) {
      this.$router.push({
        path: '/martial/schedule/list',
        query: { competitionId: row.id }
      })
    },

    // 调度 - 传递赛事ID
    handleDispatch(row) {
      // 检查编排是否完成
      if (!this.isScheduleCompleted(row.id)) {
        this.$message.warning('请先完成编排后再进行调度')
        return
      }

      this.$router.push({
        path: '/martial/dispatch/list',
        query: { competitionId: row.id }
      })
    },

    // 格式化日期范围
    formatDateRange(startTime, endTime) {
      if (!startTime || !endTime) return '-'
      // 简单格式化，只显示日期部分
      const start = startTime.split(' ')[0]
      const end = endTime.split(' ')[0]
      return `${start} ~ ${end}`
    },

    getStatusType(status) {
      const statusMap = {
        1: 'info',     // 未开始
        2: 'success',  // 报名中
        3: 'warning',  // 进行中
        4: 'info'      // 已结束
      }
      return statusMap[status] || 'info'
    },

    getStatusText(status) {
      const statusMap = {
        1: '未开始',
        2: '报名中',
        3: '进行中',
        4: '已结束'
      }
      return statusMap[status] || '未知'
    }
  }
}
</script>

<style lang="scss" scoped>
.martial-order-container {
  min-height: 100%;
  padding: 15px;
  background: #fff;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

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

  .tip-message {
    display: flex;
    gap: 12px;
    padding: 10px 14px;
    margin-bottom: 15px;
    background: linear-gradient(90deg, #ffd54f 0%, #ffecb3 100%);
    border: 1px solid #ffc107;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(255, 193, 7, 0.2);

    .tip-header {
      flex-shrink: 0;

      .tip-number {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 18px;
        height: 18px;
        background: #ff9800;
        color: #fff;
        font-size: 11px;
        font-weight: bold;
        border-radius: 50%;
      }
    }

    .tip-content {
      flex: 1;
      color: #5d4037;
      font-size: 12px;
      line-height: 1.5;

      .tip-subtitle {
        margin-top: 3px;
        color: #6d4c41;
        font-size: 11px;
        font-style: italic;
      }
    }
  }

  .search-form {
    margin-bottom: 15px;
  }

  .amount-text {
    color: #e6a23c;
    font-weight: 600;
    font-size: 14px;
  }

  .pagination {
    margin-top: 15px;
    text-align: right;
  }
}
</style>
