<template>
  <el-dialog
    v-model="visible"
    title="分配奖牌"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 赛事和项目信息 -->
    <div class="medal-info">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="赛事名称">{{ competitionName }}</el-descriptions-item>
        <el-descriptions-item label="项目名称">{{ projectName }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 奖牌分配表单 -->
    <div class="medal-form">
      <!-- 金牌 -->
      <div class="medal-section">
        <div class="section-header">
          <span class="medal-icon gold">🥇</span>
          <span class="medal-title">金牌</span>
        </div>
        <el-select
          v-model="form.goldMedal"
          placeholder="请选择金牌获得者"
          filterable
          clearable
          class="medal-select"
        >
          <el-option
            v-for="item in athleteList"
            :key="item.id"
            :label="`${item.name} (${item.number}) - ${item.score}分`"
            :value="item.id"
            :disabled="isDisabled(item.id, 'gold')"
          ></el-option>
        </el-select>
      </div>

      <!-- 银牌 -->
      <div class="medal-section">
        <div class="section-header">
          <span class="medal-icon silver">🥈</span>
          <span class="medal-title">银牌</span>
        </div>
        <el-select
          v-model="form.silverMedal"
          placeholder="请选择银牌获得者"
          filterable
          clearable
          class="medal-select"
        >
          <el-option
            v-for="item in athleteList"
            :key="item.id"
            :label="`${item.name} (${item.number}) - ${item.score}分`"
            :value="item.id"
            :disabled="isDisabled(item.id, 'silver')"
          ></el-option>
        </el-select>
      </div>

      <!-- 铜牌 -->
      <div class="medal-section">
        <div class="section-header">
          <span class="medal-icon bronze">🥉</span>
          <span class="medal-title">铜牌</span>
        </div>
        <el-select
          v-model="form.bronzeMedals"
          placeholder="请选择铜牌获得者(可多选)"
          filterable
          clearable
          multiple
          class="medal-select"
        >
          <el-option
            v-for="item in athleteList"
            :key="item.id"
            :label="`${item.name} (${item.number}) - ${item.score}分`"
            :value="item.id"
            :disabled="isDisabled(item.id, 'bronze')"
          ></el-option>
        </el-select>
      </div>
    </div>

    <!-- 自动分配建议 -->
    <el-alert
      v-if="autoSuggestion"
      :title="autoSuggestion"
      type="info"
      :closable="false"
      class="auto-suggestion"
    >
      <template #default>
        <div>{{ autoSuggestion }}</div>
        <el-button type="primary" size="small" @click="applyAutoSuggestion">
          应用建议
        </el-button>
      </template>
    </el-alert>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          确定分配
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { allocateMedals } from '@/api/martial/result'

export default {
  name: 'MedalDialog',

  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    competitionId: {
      type: Number,
      required: true
    },
    projectId: {
      type: Number,
      required: true
    },
    competitionName: {
      type: String,
      default: ''
    },
    projectName: {
      type: String,
      default: ''
    },
    athleteList: {
      type: Array,
      default: () => []
    }
  },

  emits: ['update:modelValue', 'success'],

  data() {
    return {
      visible: this.modelValue,
      submitting: false,
      form: {
        goldMedal: null,
        silverMedal: null,
        bronzeMedals: []
      }
    }
  },

  computed: {
    autoSuggestion() {
      if (this.athleteList.length < 3) {
        return null
      }

      // 按分数排序
      const sorted = [...this.athleteList].sort((a, b) => b.score - a.score)

      return `建议: 金牌-${sorted[0].name}(${sorted[0].score}分), 银牌-${sorted[1].name}(${sorted[1].score}分), 铜牌-${sorted[2].name}(${sorted[2].score}分)`
    }
  },

  watch: {
    modelValue(newVal) {
      this.visible = newVal
      if (newVal) {
        this.resetForm()
      }
    },

    visible(newVal) {
      this.$emit('update:modelValue', newVal)
    }
  },

  methods: {
    isDisabled(athleteId, medalType) {
      // 同一选手不能获得多个奖牌
      if (medalType === 'gold') {
        return this.form.silverMedal === athleteId ||
               this.form.bronzeMedals.includes(athleteId)
      }
      if (medalType === 'silver') {
        return this.form.goldMedal === athleteId ||
               this.form.bronzeMedals.includes(athleteId)
      }
      if (medalType === 'bronze') {
        return this.form.goldMedal === athleteId ||
               this.form.silverMedal === athleteId
      }
      return false
    },

    applyAutoSuggestion() {
      if (this.athleteList.length < 3) {
        return
      }

      const sorted = [...this.athleteList].sort((a, b) => b.score - a.score)

      this.form.goldMedal = sorted[0].id
      this.form.silverMedal = sorted[1].id
      this.form.bronzeMedals = [sorted[2].id]

      this.$message.success('已应用自动分配建议')
    },

    resetForm() {
      this.form = {
        goldMedal: null,
        silverMedal: null,
        bronzeMedals: []
      }
    },

    handleClose() {
      this.visible = false
    },

    async handleSubmit() {
      // 验证
      if (!this.form.goldMedal && !this.form.silverMedal && this.form.bronzeMedals.length === 0) {
        this.$message.warning('请至少分配一个奖牌')
        return
      }

      this.submitting = true
      try {
        await allocateMedals({
          competitionId: this.competitionId,
          projectId: this.projectId,
          goldMedal: this.form.goldMedal,
          silverMedal: this.form.silverMedal,
          bronzeMedals: this.form.bronzeMedals
        })

        this.$message.success('奖牌分配成功')
        this.$emit('success')
        this.handleClose()
      } catch (error) {
        console.error('奖牌分配失败:', error)
        this.$message.error('奖牌分配失败')
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.medal-info {
  margin-bottom: 20px;
}

.medal-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin: 20px 0;
}

.medal-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.medal-icon {
  font-size: 24px;

  &.gold {
    filter: drop-shadow(0 0 5px rgba(212, 175, 55, 0.5));
  }

  &.silver {
    filter: drop-shadow(0 0 5px rgba(192, 192, 192, 0.5));
  }

  &.bronze {
    filter: drop-shadow(0 0 5px rgba(205, 127, 50, 0.5));
  }
}

.medal-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.medal-select {
  width: 100%;
}

.auto-suggestion {
  margin-top: 20px;

  :deep(.el-alert__content) {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
