<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.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.refereeType" placeholder="裁判类型" clearable size="small" style="width: 180px">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="主裁判" :value="1"></el-option>
            <el-option label="普通裁判" :value="2"></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' : 'primary'" size="small">
              {{ scope.row.refereeType === 1 ? '主裁判' : '普通裁判' }}
            </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"
      :visible.sync="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-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="等级/职称" prop="level">
              <el-input v-model="formData.level" placeholder="请输入等级/职称" clearable></el-input>
            </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>

      <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>
  </div>
</template>

<script>
export default {
  name: 'RefereeList',
  data() {
    return {
      loading: false,
      submitLoading: false,
      dialogVisible: false,
      dialogTitle: '新增评委',
      isEdit: false,
      searchForm: {
        keyword: '',
        refereeType: null
      },
      allTableData: [
        {
          id: 1,
          name: '王大伟',
          gender: 1,
          phone: '13800138001',
          idCard: '110101197001011234',
          refereeType: 1,
          level: '国家一级裁判',
          specialty: '太极拳、长拳',
          remark: '经验丰富，专业能力强',
          createTime: '2025-11-20 10:00:00'
        },
        {
          id: 2,
          name: '李美丽',
          gender: 2,
          phone: '13800138002',
          idCard: '110101198001011234',
          refereeType: 2,
          level: '国家二级裁判',
          specialty: '剑术、刀术',
          remark: '认真负责',
          createTime: '2025-11-21 11:00:00'
        },
        {
          id: 3,
          name: '张强',
          gender: 1,
          phone: '13800138003',
          idCard: '110101197501011234',
          refereeType: 2,
          level: '国家一级裁判',
          specialty: '棍术、枪术',
          remark: '',
          createTime: '2025-11-22 14:00:00'
        },
        {
          id: 4,
          name: '刘芳',
          gender: 2,
          phone: '13800138004',
          idCard: '110101198501011234',
          refereeType: 1,
          level: '国际级裁判',
          specialty: '太极拳、太极剑',
          remark: '国际武术裁判',
          createTime: '2025-11-23 15:00:00'
        },
        {
          id: 5,
          name: '陈建国',
          gender: 1,
          phone: '13800138005',
          idCard: '110101197801011234',
          refereeType: 2,
          level: '国家二级裁判',
          specialty: '长拳、南拳',
          remark: '',
          createTime: '2025-11-24 16:00:00'
        }
      ],
      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: {
    // 从 localStorage 加载数据
    loadRefereeList() {
      const savedData = localStorage.getItem('refereeList')
      if (savedData) {
        try {
          this.allTableData = JSON.parse(savedData)
        } catch (e) {
          console.error('加载评委数据失败', e)
        }
      } else {
        // 首次加载，保存默认数据
        this.saveRefereeList()
      }
      this.fetchData()
    },

    // 保存数据到 localStorage
    saveRefereeList() {
      localStorage.setItem('refereeList', JSON.stringify(this.allTableData))
    },

    // 获取数据
    fetchData() {
      this.loading = true

      setTimeout(() => {
        // 过滤数据
        let filteredData = [...this.allTableData]

        // 搜索过滤
        if (this.searchForm.keyword) {
          const keyword = this.searchForm.keyword.toLowerCase()
          filteredData = filteredData.filter(item =>
            item.name.toLowerCase().includes(keyword) ||
            item.phone.includes(keyword)
          )
        }

        // 类型过滤
        if (this.searchForm.refereeType !== null && this.searchForm.refereeType !== '') {
          filteredData = filteredData.filter(item => item.refereeType === this.searchForm.refereeType)
        }

        this.pagination.total = filteredData.length

        // 分页处理
        const start = (this.pagination.current - 1) * this.pagination.size
        const end = start + this.pagination.size
        this.tableData = filteredData.slice(start, end)

        this.loading = false
      }, 300)
    },

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

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

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

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

    // 新增
    handleAdd() {
      this.dialogTitle = '新增评委'
      this.isEdit = false
      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(() => {
        const index = this.allTableData.findIndex(item => item.id === row.id)
        if (index !== -1) {
          this.allTableData.splice(index, 1)
          this.saveRefereeList()
          this.$message.success('删除成功')
          this.fetchData()
        }
      }).catch(() => {})
    },

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

          setTimeout(() => {
            if (this.isEdit) {
              // 编辑
              const index = this.allTableData.findIndex(item => item.id === this.formData.id)
              if (index !== -1) {
                this.allTableData[index] = { ...this.formData }
                this.$message.success('修改成功')
              }
            } else {
              // 新增
              const newId = this.allTableData.length > 0
                ? Math.max(...this.allTableData.map(item => item.id)) + 1
                : 1
              const now = new Date()
              const createTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`

              this.allTableData.push({
                ...this.formData,
                id: newId,
                createTime
              })
              this.$message.success('新增成功')
            }

            this.saveRefereeList()
            this.dialogVisible = false
            this.fetchData()
            this.submitLoading = false
          }, 500)
        }
      })
    },

    // 关闭弹窗
    handleDialogClose() {
      this.$refs.refereeForm.resetFields()
      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>
