<template>
  <div class="sport-detail-container">
    <el-card shadow="never" v-loading="isLoading" style="height: 100%">
      <div slot="header" class="clearfix">
        <el-button icon="el-icon-back" size="mini" @click="$router.back()">返回列表</el-button>
        <span class="header-title">赛事详情</span>
      </div>

      <div class="detail-content" v-if="matchInfo.id">
        <el-row :gutter="20" class="detail-row">
          <el-col :span="12">
            <div class="item">
              <span class="label">联赛名称：</span>
              <span class="value" style="margin-right: 6px">{{ matchInfo.league }}</span>
              <el-icon class="el-icon-lock" v-if="matchInfo.error" style="color: red;font-size: 20px;"></el-icon>
              <el-icon class="el-icon-unlock" v-else style="color: #67c23a;font-size: 20px;"></el-icon>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="item">
              <span class="label">联赛名称(英文)：</span>
              <span class="value" style="margin-right: 6px">{{ matchInfo.league_en }}</span>
              <el-icon class="el-icon-lock" v-if="matchInfo.error" style="color: red;font-size: 20px;"></el-icon>
              <el-icon class="el-icon-unlock" v-else style="color: #67c23a;font-size: 20px;"></el-icon>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="detail-row" v-if="matchInfo.league_data">
          <el-col :span="12">
            <div class="item flex-item">
              <span class="label">联赛Logo：</span>
              <el-image
                v-if="matchInfo.league_data.logo"
                :src="matchInfo.league_data.logo"
                class="team-logo">
              </el-image>
              <span v-else class="value">--</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="item">
              <span class="label">所属国家：</span>
              <span class="value">{{ matchInfo.league_data.country || '--' }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="detail-row" v-if="matchInfo.league_data">
          <el-col :span="12">
            <div class="item">
              <span class="label">赛季：</span>
              <span class="value">{{ matchInfo.league_data.season || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="item">
              <span class="label">比赛轮次：</span>
              <span class="value">{{ matchInfo.league_data.round || '--' }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="detail-row" v-if="matchInfo.league_data">
          <el-col :span="12">
            <div class="item">
              <span class="label">积分榜：</span>
              <span class="value">
                <el-tag :type="matchInfo.league_data.standings ? 'success' : 'info'" size="small">
                  {{ matchInfo.league_data.standings ? '支持' : '不支持' }}
                </el-tag>
              </span>
            </div>
          </el-col>
              <el-col :span="12">
            <div class="item">
              <span class="label">比赛时间：</span>
              <span class="value">{{ matchInfo.game_time || '--' }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="detail-row">
          <el-col :span="12">
            <div class="item flex-item">
              <span class="label">主队：</span>
              <el-image
                v-if="matchInfo.home_team_logo"
                :src="matchInfo.home_team_logo"
                class="team-logo">
              </el-image>
              <span class="value text-bold">{{ matchInfo.home_team }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="item flex-item">
              <span class="label">客队：</span>
              <el-image
                v-if="matchInfo.guest_team_logo"
                :src="matchInfo.guest_team_logo"
                class="team-logo">
              </el-image>
              <span class="value text-bold">{{ matchInfo.guest_team }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="detail-row">
          <el-col :span="12">
            <div class="item">
              <span class="label">比赛比分：</span>
              <span class="value">
                半场 <span class="text-danger">{{ matchInfo.half_score || '-' }}</span>
                / 全场 <span class="text-danger text-bold">{{ matchInfo.score || '-' }}</span>
              </span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="item">
              <span class="label">比赛状态：</span>
              <span class="value">
                {{ getStateLabel(matchInfo.state) }}
              </span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="detail-row" v-if="matchInfo.fixture_status">
          <el-col :span="12">
            <div class="item">
              <span class="label">赛事阶段：</span>
              <el-tag
                type="success"
                size="small">
                {{ matchInfo.fixture_status.long }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="item">
              <span class="label">异常状态：</span>
              <span class="value">
                <el-tag :type="matchInfo.error ? 'danger' : 'success'">
                  {{ matchInfo.error ? '是' : '否' }}
                </el-tag>
              </span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="detail-row" v-if="matchInfo.fixture_status">
          <el-col :span="12">
            <div class="item">
              <span class="label">比赛时长：</span>
              <span class="value">
                {{ matchInfo.fixture_status.elapsed }}
              </span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="item">
              <span class="label">直播中比赛时长：</span>
              <span class="value">
                {{ JSON.parse(matchInfo.odd_fixture_status) ? JSON.parse(matchInfo.odd_fixture_status).seconds : '--' }}
              </span>
            </div>
          </el-col>
        </el-row>

        <div class="event-section" v-if="processedEvents && processedEvents.length > 0">
          <div class="section-header event-header">
            <span>赛事事件</span>
            <el-link type="primary" :underline="false" @click="isEventsExpanded = !isEventsExpanded">
              {{ isEventsExpanded ? '收起全部' : '展开全部' }}
              <i :class="isEventsExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
            </el-link>
          </div>

          <el-collapse-transition>
            <div v-show="isEventsExpanded">
              <el-timeline>
                <el-timeline-item
                  v-for="evt in processedEvents"
                  :key="evt.id"
                  :timestamp="evt.timeDisplay"
                  placement="top"
                  :color="evt.iconColor"
                >
                  <el-card shadow="hover" class="event-card">
                    <div class="event-card-content">
                      <div class="team-info" :class="evt.isHome ? 'is-home' : 'is-guest'">
                        <el-image
                          v-if="evt.teamLogo"
                          :src="evt.teamLogo"
                          class="event-team-logo"
                          fit="contain">
                        </el-image>
                        <span class="team-name">{{ evt.teamName }}</span>
                      </div>

                      <span class="event-type">
                        <el-tag :type="evt.tagType" size="small">{{ evt.typeLabel }}</el-tag>
                      </span>
                      <span class="event-detail">{{ evt.detail }}</span>
                      <span class="event-player" v-if="evt.playerName">
                        ({{ evt.playerName }})
                      </span>
                    </div>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-collapse-transition>
        </div>

        <div class="statistics-section" v-if="processedStatistics && processedStatistics.length > 0">
          <div class="section-header event-header">
            <span>赛事统计</span>
            <el-link type="primary" :underline="false" @click="isStatisticsExpanded = !isStatisticsExpanded">
              {{ isStatisticsExpanded ? '收起全部' : '展开全部' }}
              <i :class="isStatisticsExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
            </el-link>
          </div>
          <el-collapse-transition>
            <div v-show="isStatisticsExpanded">
              <el-table :data="processedStatistics" border style="width: 100%" size="small">
                <el-table-column prop="label" label="统计项" width="150" align="center"></el-table-column>
                <el-table-column label="上半场" align="center">
                  <el-table-column prop="home1" :label="'主队 (' + matchInfo.home_team + ')'" align="center"></el-table-column>
                  <el-table-column prop="guest1" :label="'客队 (' + matchInfo.guest_team + ')'" align="center"></el-table-column>
                </el-table-column>
                <el-table-column label="下半场" align="center">
                  <el-table-column prop="home2" :label="'主队 (' + matchInfo.home_team + ')'" align="center"></el-table-column>
                  <el-table-column prop="guest2" :label="'客队 (' + matchInfo.guest_team + ')'" align="center"></el-table-column>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-transition>
        </div>

        <div class="odds-section" v-if="matchInfo.odds && matchInfo.odds.length > 0">
          <div class="section-header" style="display: flex; justify-content: space-between; align-items: center; padding-right: 10px;">
            <span>盘口及赔率信息</span>
            <el-button
              :icon="isAllLocked ? 'el-icon-lock' : 'el-icon-unlock'"
              @click="toggleAllOddsLock"
              size="mini"
              :type="isAllLocked ? 'danger' : 'success'"
            >
              {{ isAllLocked ? '一键解锁' : '一键上锁' }}
            </el-button>
          </div>
          <div v-for="oddGroup in matchInfo.odds" :key="oddGroup.id" class="odd-group-box">
            <div class="odd-group-title">
              {{ oddGroup.name }}
              <el-button
                :icon="oddGroup.is_locked ? 'el-icon-lock' : 'el-icon-unlock'"
                @click="toggleOddLock(oddGroup)"
                size="mini"
                style="margin-left: 10px;"
                :type="oddGroup.is_locked ? 'danger' : 'success'"
              ></el-button>
            </div>
            <el-row :gutter="15">
              <el-col :span="8" v-for="(val, index) in oddGroup.values" :key="index">
                <div class="odd-item" :class="{ 'is-suspended': val.suspended }">
                  <span class="odd-label">{{ val.value }}
                  <template v-if="val.handicap">
                    ({{ val.handicap }})
                  </template>
                  </span>
                  <div style="display: flex; align-items: center;">
                    <span class="odd-value" style="margin-right: 8px;">{{ val.odd }}</span>
                    <el-button
                      v-if="!val.suspended"
                      :icon="val.is_locked ? 'el-icon-lock' : 'el-icon-unlock'"
                      @click="toggleValueLock(oddGroup.id, val)"
                      size="mini"
                      circle
                      style="padding: 4px;"
                      :type="val.is_locked ? 'danger' : 'success'"
                    ></el-button>
                    <div v-if="val.suspended" style="width: 24px;"></div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>

      </div>

      <el-empty v-else-if="!loading" description="暂无数据"></el-empty>
    </el-card>
  </div>
</template>

<script>
// 引入 sportSetValuesLocked 接口
import { sportInfo, setOddsLocked, sportSetValuesLocked } from '@/api/data'

export default {
  name: 'SportOrderDetail',
  data() {
    return {
      loading: false,
      loadingConfig: true,
      matchInfo: {},
      isEventsExpanded: true,
      isStatisticsExpanded: false,
      stateOptions: [
        { value: 0, label: '未开始' },
        { value: 1, label: '进行中' },
        { value: 2, label: '已完成' },
        { value: 3, label: '延期' },
        { value: 4, label: '取消' },
        { value: '', label: '全部' }
      ],
      timer: null
    }
  },
  computed: {
    isLoading() {
      return this.loading && this.loadingConfig
    },
    isAllLocked() {
      if (!this.matchInfo.odds || this.matchInfo.odds.length === 0) return false
      return this.matchInfo.odds.every(group => group.is_locked)
    },
    processedEvents() {
      if (!this.matchInfo.event || !Array.isArray(this.matchInfo.event)) return []

      return this.matchInfo.event.map(evt => {
        const isHome = evt.team_id === this.matchInfo.home_team_id
        const teamName = isHome ? this.matchInfo.home_team : this.matchInfo.guest_team
        const teamLogo = isHome ? this.matchInfo.home_team_logo : this.matchInfo.guest_team_logo

        let playerName = ''
        try {
          if (evt.player) {
            const playerObj = JSON.parse(evt.player)
            playerName = playerObj.name || ''
          }
        } catch (e) {
          console.error('解析球员数据失败', e)
        }

        const typeLower = evt.type ? evt.type.toLowerCase() : ''
        let typeLabel = evt.type
        let tagType = 'info'
        let iconColor = '#909399'

        if (typeLower === 'goal') {
          typeLabel = '进球'
          tagType = 'danger'
          iconColor = '#F56C6C'
        } else if (typeLower === 'card') {
          const isRedCard = evt.detail && evt.detail.toLowerCase().includes('red')
          typeLabel = isRedCard ? '红牌' : '黄牌'
          tagType = isRedCard ? 'danger' : 'warning'
          iconColor = isRedCard ? '#F56C6C' : '#E6A23C'
        } else if (typeLower === 'subst') {
          typeLabel = '换人'
          tagType = 'success'
          iconColor = '#67C23A'
        } else if (typeLower === 'var') {
          typeLabel = 'VAR'
          tagType = 'info'
          iconColor = '#909399'
        }

        return {
          ...evt,
          timeDisplay: `第 ${evt.time_elapsed} 分钟`,
          isHome,
          teamName,
          teamLogo,
          typeLabel,
          tagType,
          iconColor,
          playerName
        }
      })
    },
    processedStatistics() {
      if (!this.matchInfo.statistics || !this.matchInfo.statistics.length) return []

      const statsMap = {
        'shots_on_goal': '射正球门',
        'shots_off_goal': '射偏球门',
        'shots_insidebox': '禁区内射门',
        'shots_outsidebox': '禁区外射门',
        'total_shots': '总射门次数',
        'blocked_shots': '被封堵射门',
        'fouls': '犯规次数',
        'corner_kicks': '角球',
        'offsides': '越位',
        'ball_possession': '控球率(%)',
        'yellow_cards': '黄牌',
        'red_cards': '红牌',
        'goalkeeper_saves': '门将扑救',
        'total_passes': '总传球数',
        'passes_accurate': '精准传球',
        'passes_percent': '传球成功率(%)'
      }

      const result = []
      const homeId = this.matchInfo.home_team_id
      const guestId = this.matchInfo.guest_team_id

      const findStat = (teamId, half) => {
        return this.matchInfo.statistics.find(s => s.team_id === teamId && s.half === half) || {}
      }

      const homeHalf1 = findStat(homeId, 1)
      const guestHalf1 = findStat(guestId, 1)
      const homeHalf2 = findStat(homeId, 2)
      const guestHalf2 = findStat(guestId, 2)

      for (const [key, label] of Object.entries(statsMap)) {
        result.push({
          label: label,
          home1: homeHalf1[key] !== null && homeHalf1[key] !== undefined ? homeHalf1[key] : '-',
          guest1: guestHalf1[key] !== null && guestHalf1[key] !== undefined ? guestHalf1[key] : '-',
          home2: homeHalf2[key] !== null && homeHalf2[key] !== undefined ? homeHalf2[key] : '-',
          guest2: guestHalf2[key] !== null && guestHalf2[key] !== undefined ? guestHalf2[key] : '-'
        })
      }
      return result
    }
  },
  created() {
    this.fetchDetail()
    this.timer = setInterval(() => {
      if (this.matchInfo.state === 0 || this.matchInfo.state === 1) {
        this.loadingConfig = false
        this.fetchDetail()
      }
    }, 5000)
  },
  destroyed() {
    clearInterval(this.timer)
  },
  methods: {
    getStateLabel(stateValue) {
      const target = this.stateOptions.find(item => item.value === stateValue)
      return target ? target.label : '未知'
    },

    async fetchDetail() {
      const id = this.$route.query.id || this.$route.params.id
      if (!id) {
        this.$message.error('赛事ID缺失')
        return
      }

      this.loading = true
      try {
        const res = await sportInfo({ id })
        if (res && res.code === 0) {
          if (res.data && res.data.odds && Array.isArray(res.data.odds)) {
            const lockedIds = res.data.odd_ids_locked || []
            res.data.odds.forEach(oddGroup => {
              oddGroup.is_locked = lockedIds.includes(oddGroup.id)
            })
          }
          this.matchInfo = res.data
        } else {
          this.$message.error(res.msg || '获取详情失败')
        }
      } catch (error) {
        console.error('API Error:', error)
      } finally {
        this.loading = false
      }
    },

    async toggleAllOddsLock() {
      try {
        const targetState = !this.isAllLocked
        const res = await setOddsLocked({
          id: this.matchInfo.id
        })
        if (res && res.code === 0) {
          this.matchInfo.odds.forEach(oddGroup => {
            this.$set(oddGroup, 'is_locked', targetState)
          })
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('API Error:', error)
        this.$message.error('请求异常')
      }
    },

    async toggleOddLock(oddGroup) {
      try {
        const res = await setOddsLocked({
          id: this.matchInfo.id,
          odd_id: oddGroup.id
        })
        if (res && res.code === 0) {
          this.$set(oddGroup, 'is_locked', !oddGroup.is_locked)
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('API Error:', error)
        this.$message.error('请求异常')
      }
    },

    // 新增：单个投注项的上锁/解锁控制
    async toggleValueLock(odd_id, val) {
      try {
        const res = await sportSetValuesLocked({
          id: this.matchInfo.id,
          odd_id: odd_id,
          value: val.value,
          handicap: val.handicap
        })
        if (res && res.code === 0) {
          this.$set(val, 'is_locked', !val.is_locked)
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('API Error:', error)
        this.$message.error('请求异常')
      }
    }
  }
}
</script>

<style scoped>
.sport-detail-container {
  padding: 20px;
  height: calc(100vh - 60px);
}
.header-title {
  margin-left: 15px;
  font-weight: bold;
  font-size: 16px;
  vertical-align: middle;
}
::v-deep .el-card__body{
  height: 100%;
}
.detail-content {
  padding: 10px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  height: 100%;
  overflow-y: auto;
  padding-bottom: 50px;
}
.detail-row {
  border-bottom: 1px solid #EBEEF5;
  display: flex;
  align-items: center;
}
.item {
  padding: 12px 10px;
  font-size: 14px;
}
.flex-item {
  display: flex;
  align-items: center;
}
.label {
  color: #909399;
  width: 120px;
  display: inline-block;
  flex-shrink: 0;
}
.value {
  color: #303133;
}
.text-bold {
  font-weight: bold;
}
.text-danger {
  color: #F56C6C;
}

/* 队伍Logo样式 */
.team-logo {
  width: 24px;
  height: 24px;
  margin-right: 8px;
  vertical-align: middle;
}

/* 模块公共标题样式 */
.section-header {
  font-weight: bold;
  font-size: 15px;
  color: #303133;
  margin-bottom: 15px;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

/* === 赛事事件样式 === */
.event-section {
  padding: 20px 10px 10px;
  border-bottom: 1px solid #EBEEF5;
}
.event-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 10px; /* 右侧留白防止紧贴边缘 */
}
.event-card {
  margin-bottom: 0;
}
::v-deep .event-card .el-card__body {
  padding: 12px 15px;
}
.event-card-content {
  display: flex;
  align-items: center;
  font-size: 14px;
}
/* 修改后的事件队伍信息区 */
.team-info {
  display: flex;
  align-items: center;
  min-width: 140px;
  margin-right: 15px;
}
.team-info.is-home {
  color: #409EFF; /* 主队蓝色 */
}
.team-info.is-guest {
  color: #E6A23C; /* 客队橙色 */
}
.team-info .team-name {
  font-weight: bold;
}
.event-team-logo {
  width: 22px;
  height: 22px;
  margin-right: 8px;
  border-radius: 50%; /* 如果你想让LOGO变圆形，可保留这行 */
}

.event-type {
  margin-right: 15px;
  min-width: 50px;
}
.event-detail {
  color: #303133;
  font-weight: 500;
}
.event-player {
  margin-left: 8px;
  color: #909399;
  font-size: 13px;
}

/* 赛事统计样式 */
.statistics-section {
  padding: 20px 10px 10px;
  border-bottom: 1px solid #EBEEF5;
}

/* 赔率区域样式 */
.odds-section {
  padding: 20px 10px 10px;
}
.odd-group-box {
  background: #F8F9FA;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 15px;
}
.odd-group-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
  /* 为标题增加对齐样式，使图标居中对齐 */
  display: flex;
  align-items: center;
}
.odd-item {
  background: #fff;
  border: 1px solid #EBEEF5;
  padding: 10px;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.odd-label {
  color: #909399;
  font-size: 13px;
}
.odd-value {
  color: #F56C6C;
  font-weight: bold;
  font-size: 14px;
}
.is-suspended {
  background: #f5f7fa;
  opacity: 0.6;
  text-decoration: line-through;
}
</style>
