<template>
  <div class="referee-container">
    <el-card shadow="hover">
      <div class="page-header">
        <h2 class="page-title">评委管理</h2>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">新增评委</el-button>
      </div>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input
            v-model="searchForm.name"
            placeholder="搜索姓名"
            clearable
            size="small"
            style="width: 200px"
          >
            <template #prefix>
              <i class="el-input__icon el-icon-search"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchForm.phone"
            placeholder="搜索手机号"
            clearable
            size="small"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.refereeType" placeholder="裁判类型" clearable size="small" style="width: 150px">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="主裁判" :value="1"></el-option>
            <el-option label="裁判员" :value="2"></el-option>
            <el-option label="总裁" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
          <el-button size="small" @click="handleReset">重置</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="name" label="姓名" width="100"></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="phone" label="手机号" width="130"></el-table-column>
        <el-table-column prop="idCard" label="身份证号" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="refereeType" label="裁判类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.refereeType === 1 ? 'danger' : (scope.row.refereeType === 3 ? 'warning' : 'primary')" size="small">
              {{ scope.row.refereeType === 1 ? '主裁判' : (scope.row.refereeType === 3 ? '总裁' : '裁判员') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="等级/职称" width="120"></el-table-column>
        <el-table-column prop="specialty" label="擅长项目" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
        <el-table-column label="操作" width="180" 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"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form ref="refereeForm" :model="formData" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" 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="phone">
              <el-input v-model="formData.phone" placeholder="请输入手机号" clearable maxlength="11"></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="refereeType">
              <el-select v-model="formData.refereeType" placeholder="请选择裁判类型" style="width: 100%">
                <el-option label="主裁判" :value="1"></el-option>
                <el-option label="裁判员" :value="2"></el-option>
            <el-option label="总裁" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="等级/职称" prop="level">
              <el-select
                v-model="formData.level"
                placeholder="请选择等级"
                clearable
                style="width: 130px"
              >
                <el-option label="国家级" value="国家级" />
                <el-option label="一级" value="一级" />
                <el-option label="二级" value="二级" />
                <el-option label="三级" value="三级" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="擅长项目" prop="specialty">
          <el-input v-model="formData.specialty" placeholder="请输入擅长项目，多个用逗号分隔" clearable></el-input>
        </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>

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

<script>
import { getRefereeList, submitReferee, removeReferee } from '@/api/martial/referee'

export default {
  name: 'RefereeList',
  data() {
    return {
      loading: false,
      submitLoading: false,
      dialogVisible: false,
      dialogTitle: '新增评委',
      isEdit: false,
      searchForm: {
        name: '',
        phone: '',
        refereeType: null
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      formData: {
        id: null,
        name: '',
        gender: 1,
        phone: '',
        idCard: '',
        refereeType: null,
        level: '',
        specialty: '',
        remark: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { 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' }
        ],
        refereeType: [
          { required: true, message: '请选择裁判类型', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.loadRefereeList()
  },
  methods: {
    // 加载裁判列表
    loadRefereeList() {
      this.loading = true
      const params = {}

      // 搜索条件
      if (this.searchForm.name) {
        params.name = this.searchForm.name
      }
      if (this.searchForm.phone) {
        params.phone = this.searchForm.phone
      }
      if (this.searchForm.refereeType !== null && this.searchForm.refereeType !== '') {
        params.refereeType = this.searchForm.refereeType
      }

      getRefereeList(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
            this.pagination.total = responseData.total || 0
          }
        })
        .catch(err => {
          console.error('加载裁判列表失败', err)
          this.$message.error('加载裁判列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadRefereeList()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        name: '',
        phone: '',
        refereeType: null
      }
      this.pagination.current = 1
      this.loadRefereeList()
    },

    // 分页
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadRefereeList()
    },

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

    // 新增
    handleAdd() {
      this.dialogTitle = '新增评委'
      this.isEdit = false
      this.resetFormData()
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑评委'
      this.isEdit = true
      this.formData = { ...row }
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定删除该评委吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        removeReferee(row.id.toString())
          .then(res => {
            this.$message.success('删除成功')
            this.loadRefereeList()
          })
          .catch(err => {
            console.error('删除失败', err)
            this.$message.error('删除失败')
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {})
    },

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

          const submitData = { ...this.formData }

          // 如果是编辑，确保有 id
          if (this.isEdit && !submitData.id) {
            this.$message.error('编辑数据异常，请重新操作')
            this.submitLoading = false
            return
          }

          // 如果是新增，删除 id 字段
          if (!this.isEdit) {
            delete submitData.id
          }

          submitReferee(submitData)
            .then(res => {
              this.$message.success(this.isEdit ? '修改成功' : '新增成功')
              this.dialogVisible = false
              this.loadRefereeList()
            })
            .catch(err => {
              console.error('提交失败', err)
              this.$message.error('提交失败')
            })
            .finally(() => {
              this.submitLoading = false
            })
        }
      })
    },

    // 关闭弹窗
    handleDialogClose() {
      this.$refs.refereeForm.resetFields()
      this.resetFormData()
    },

    // 重置表单数据
    resetFormData() {
      this.formData = {
        id: null,
        name: '',
        gender: 1,
        phone: '',
        idCard: '',
        refereeType: null,
        level: '',
        specialty: '',
        remark: ''
      }
    }
  }
}
</script>

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

  .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;
    }
  }

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

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

  .dialog-footer {
    text-align: right;
  }
}
</style>
