<template>
  <div class="participant-container">
    <el-card shadow="hover">
      <div class="page-header">
        <el-button icon="el-icon-back" size="small" @click="goBack">返回</el-button>
        <h2 class="page-title">维护参赛选手 - {{ competitionInfo.competitionName }}</h2>
      </div>

      <!-- 赛事基本信息 -->
      <div class="competition-info">
        <el-descriptions :column="3" border size="small">
          <el-descriptions-item label="赛事名称">{{ competitionInfo.competitionName }}</el-descriptions-item>
          <el-descriptions-item label="主办单位">{{ competitionInfo.organizer }}</el-descriptions-item>
          <el-descriptions-item label="比赛时间">{{ competitionInfo.competitionTime }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 操作按钮区 -->
      <div class="action-bar">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">添加选手</el-button>
        <el-button type="success" size="small" icon="el-icon-upload" @click="handleImport">导入选手</el-button>
        <el-button type="warning" size="small" icon="el-icon-sort" @click="handleBatchSort">批量排序</el-button>
        <el-button type="info" size="small" icon="el-icon-download" @click="handleExport">导出名单</el-button>
      </div>

      <!-- 参赛选手列表 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        size="small"
        row-key="id"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="orderNum" label="出场顺序" width="100" align="center">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.orderNum"
              :min="1"
              :max="9999"
              size="small"
              @change="handleOrderChange(scope.row)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="playerName" label="选手姓名" width="120"></el-table-column>
        <el-table-column prop="gender" label="性别" width="60" align="center">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="60" align="center"></el-table-column>
        <el-table-column prop="organization" label="所属单位" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="projectName" label="参赛项目" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="category" label="组别" width="100"></el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" width="120"></el-table-column>
        <el-table-column label="附件" width="80" align="center">
          <template #default="scope">
            <el-button
              v-if="scope.row.attachments && scope.row.attachments.length > 0"
              type="text"
              size="small"
              @click="handleViewAttachments(scope.row)"
            >
              查看({{ scope.row.attachments.length }})
            </el-button>
            <span v-else style="color: #999;">无</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</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>

    <!-- 新增/编辑选手弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="700px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form ref="playerForm" :model="formData" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选手姓名" prop="playerName">
              <el-input v-model="formData.playerName" placeholder="请输入选手姓名" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="formData.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="formData.age" :min="1" :max="150" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" clearable maxlength="11"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属单位" prop="organization">
              <el-input v-model="formData.organization" placeholder="请输入所属单位" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="formData.idCard" placeholder="请输入身份证号" clearable maxlength="18"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="参赛项目" prop="projectName">
              <el-input v-model="formData.projectName" placeholder="请输入参赛项目" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组别" prop="category">
              <el-select v-model="formData.category" placeholder="请选择组别" style="width: 100%">
                <el-option label="少儿组" value="少儿组"></el-option>
                <el-option label="少年组" value="少年组"></el-option>
                <el-option label="青年组" value="青年组"></el-option>
                <el-option label="成人组" value="成人组"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="出场顺序" prop="orderNum">
          <el-input-number v-model="formData.orderNum" :min="1" :max="9999" style="width: 100%"></el-input-number>
        </el-form-item>

        <el-form-item label="选手简介" prop="introduction">
          <el-input
            v-model="formData.introduction"
            type="textarea"
            :rows="4"
            placeholder="请输入选手简介、成绩、特长等信息"
          ></el-input>
        </el-form-item>

        <el-form-item label="上传附件">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持上传PDF、Word、图片等文件，单个文件不超过5MB</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 查看附件弹窗 -->
    <el-dialog
      title="附件列表"
      :visible.sync="attachmentDialogVisible"
      width="600px"
    >
      <el-table :data="currentAttachments" border stripe size="small">
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="name" label="文件名" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="size" label="大小" width="100" align="center">
          <template #default="scope">
            {{ formatFileSize(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleDownload(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { getParticipantList, addParticipant, updateParticipant, removeParticipant, updateOrder } from '@/api/martial/participant'

export default {
  name: 'ParticipantManage',
  data() {
    return {
      competitionId: null,
      loading: false,
      submitLoading: false,
      dialogVisible: false,
      attachmentDialogVisible: false,
      dialogTitle: '添加选手',
      isEdit: false,
      competitionInfo: {
        competitionName: '',
        organizer: '',
        competitionTime: ''
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      formData: {
        id: null,
        playerName: '',
        gender: 1,
        age: null,
        contactPhone: '',
        organization: '',
        idCard: '',
        projectName: '',
        category: '',
        orderNum: 1,
        introduction: '',
        attachments: [],
        remark: ''
      },
      fileList: [],
      currentAttachments: [],
      rules: {
        playerName: [
          { required: true, message: '请输入选手姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        contactPhone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        idCard: [
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
        ],
        projectName: [
          { required: true, message: '请输入参赛项目', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择组别', trigger: 'change' }
        ],
        orderNum: [
          { required: true, message: '请输入出场顺序', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.competitionId = this.$route.query.competitionId
    if (this.competitionId) {
      this.loadCompetitionInfo()
      this.fetchData()
    } else {
      this.$message.error('缺少赛事ID参数')
    }
  },
  methods: {
    // 加载赛事信息
    loadCompetitionInfo() {
      // 这里应该调用API获取赛事信息，暂时使用模拟数据
      this.competitionInfo = {
        competitionName: '第三十届武术大赛',
        organizer: '武术协会',
        competitionTime: '2025-11-28 至 2025-12-01'
      }
    },

    // 获取参赛选手列表
    fetchData() {
      this.loading = true

      getParticipantList(this.competitionId, this.pagination.current, this.pagination.size)
        .then(res => {
          this.tableData = res.data.records || []
          this.pagination.total = res.data.total || 0
        })
        .catch(err => {
          this.$message.error(err.message || '获取数据失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 返回
    goBack() {
      this.$router.go(-1)
    },

    // 添加选手
    handleAdd() {
      this.dialogTitle = '添加选手'
      this.isEdit = false
      this.dialogVisible = true
    },

    // 编辑选手
    handleEdit(row) {
      this.dialogTitle = '编辑选手'
      this.isEdit = true
      this.formData = { ...row }
      this.fileList = row.attachments || []
      this.dialogVisible = true
    },

    // 删除选手
    handleDelete(row) {
      this.$confirm('确定删除该选手吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeParticipant(row.id).then(() => {
          this.$message.success('删除成功')
          this.fetchData()
        }).catch(err => {
          this.$message.error(err.message || '删除失败')
        })
      }).catch(() => {})
    },

    // 出场顺序变更
    handleOrderChange(row) {
      updateOrder(row.id, row.orderNum).then(() => {
        this.$message.success('顺序更新成功')
        this.fetchData()
      }).catch(err => {
        this.$message.error(err.message || '更新失败')
      })
    },

    // 提交表单
    handleSubmit() {
      this.$refs.playerForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true

          const submitData = {
            ...this.formData,
            competitionId: this.competitionId,
            attachments: this.fileList
          }

          const apiMethod = this.isEdit ? updateParticipant : addParticipant
          const successMsg = this.isEdit ? '修改成功' : '添加成功'

          apiMethod(submitData)
            .then(() => {
              this.$message.success(successMsg)
              this.dialogVisible = false
              this.fetchData()
            })
            .catch(err => {
              this.$message.error(err.message || '操作失败')
            })
            .finally(() => {
              this.submitLoading = false
            })
        }
      })
    },

    // 关闭弹窗
    handleDialogClose() {
      this.$refs.playerForm.resetFields()
      this.formData = {
        id: null,
        playerName: '',
        gender: 1,
        age: null,
        contactPhone: '',
        organization: '',
        idCard: '',
        projectName: '',
        category: '',
        orderNum: 1,
        introduction: '',
        attachments: [],
        remark: ''
      }
      this.fileList = []
    },

    // 文件上传
    handleFileChange(file, fileList) {
      this.fileList = fileList
    },

    handleFileRemove(file, fileList) {
      this.fileList = fileList
    },

    // 查看附件
    handleViewAttachments(row) {
      this.currentAttachments = row.attachments || []
      this.attachmentDialogVisible = true
    },

    // 下载附件
    handleDownload(file) {
      // 实现文件下载逻辑
      this.$message.info('下载功能开发中')
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
    },

    // 导入选手
    handleImport() {
      this.$message.info('批量导入功能开发中')
    },

    // 批量排序
    handleBatchSort() {
      this.$message.info('批量排序功能开发中')
    },

    // 导出名单
    handleExport() {
      this.$message.info('导出功能开发中')
    },

    // 分页
    handleSizeChange(size) {
      this.pagination.size = size
      this.fetchData()
    },

    handleCurrentChange(current) {
      this.pagination.current = current
      this.fetchData()
    }
  }
}
</script>

<style lang="scss" scoped>
.participant-container {
  min-height: 100%;
  padding: 15px;

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

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

  .competition-info {
    margin-bottom: 15px;
  }

  .action-bar {
    margin-bottom: 15px;
    padding: 12px;
    background: #f5f7fa;
    border-radius: 4px;
  }

  .pagination {
    margin-top: 15px;
    text-align: right;
  }

  .dialog-footer {
    text-align: right;
  }

  .upload-demo {
    width: 100%;
  }
}
</style>
