<template>
  <div class="deduction-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="选择赛事" required>
          <el-select
            v-model="queryParams.competitionId"
            placeholder="请选择赛事"
            clearable
            filterable
            :loading="competitionLoading"
            :disabled="competitionLoading"
            style="width: 250px"
            @change="handleCompetitionChange"
          >
            <template #empty>
              <div style="padding: 20px; text-align: center; color: #909399;">
                <p>暂无赛事数据</p>
                <p style="font-size: 12px; margin-top: 5px;">
                  请先在"赛事管理"中创建赛事
                </p>
              </div>
            </template>
            <el-option
              v-for="item in competitionList"
              :key="item.id"
              :label="item.competitionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属项目">
          <el-select
            v-model="queryParams.projectId"
            placeholder="请选择项目"
            clearable
            filterable
            :disabled="!queryParams.competitionId"
            style="width: 250px"
          >
            <el-option
              v-for="item in projectList"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="扣分项名称">
          <el-input
            v-model="queryParams.itemName"
            placeholder="请输入扣分项名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工具栏 -->
    <el-card shadow="never" class="toolbar-card">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button
            type="primary"
            :icon="Plus"
            :disabled="!queryParams.competitionId"
            @click="handleAdd"
          >
            新增扣分项
          </el-button>
          <el-button
            type="danger"
            :icon="Delete"
            :disabled="!selection.length || !queryParams.competitionId"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
          <!-- <el-button type="success" :icon="DocumentCopy" @click="handleClone">
            克隆扣分项
          </el-button> -->
          <el-button
            type="warning"
            :icon="Download"
            :disabled="!queryParams.competitionId"
            @click="handleExport"
          >
            导出模板
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-tooltip content="拖拽行可调整顺序" placement="top">
            <el-icon :size="20" color="#409EFF">
              <InfoFilled />
            </el-icon>
          </el-tooltip>
          <el-tooltip content="刷新" placement="top">
            <el-button
              circle
              :icon="Refresh"
              :disabled="!queryParams.competitionId"
              @click="fetchData"
            />
          </el-tooltip>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="排序" width="80" align="center">
          <template #default="{ row }">
            <el-icon class="drag-handle" :size="20">
              <Rank />
            </el-icon>
            <span style="margin-left: 5px">{{ row.sortOrder }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="itemName"
          label="扣分项名称"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="projectName"
          label="所属项目"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          prop="deductionPoints"
          label="扣分值(分)"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <el-tag type="danger" effect="dark">
              -{{ row.deductionPoints }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述说明"
          min-width="250"
          show-overflow-tooltip
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="160"
          align="center"
        >
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="danger" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchData"
          @current-change="fetchData"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="所属赛事" prop="competitionId">
          <el-select
            v-model="form.competitionId"
            placeholder="请选择赛事"
            filterable
            disabled
            style="width: 100%"
          >
            <el-option
              v-for="item in competitionList"
              :key="item.id"
              :label="item.competitionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属项目" prop="projectId">
          <el-select
            v-model="form.projectId"
            placeholder="请选择所属项目"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in projectList"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="扣分项名称" prop="itemName">
          <el-input
            v-model="form.itemName"
            placeholder="请输入扣分项名称"
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="扣分值(分)" prop="deductionPoints">
          <el-input-number
            v-model="form.deductionPoints"
            :min="0.1"
            :max="10"
            :precision="1"
            :step="0.1"
            style="width: 100%"
          />
          <div class="form-tip">扣分范围：0.1 - 10.0 分</div>
        </el-form-item>
        <el-form-item label="排序序号" prop="sortOrder">
          <el-input-number
            v-model="form.sortOrder"
            :min="0"
            :max="999"
            style="width: 100%"
          />
          <div class="form-tip">数字越小越靠前</div>
        </el-form-item>
        <el-form-item label="描述说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入描述说明"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 克隆扣分项弹窗 -->
    <el-dialog
      v-model="cloneDialogVisible"
      title="克隆扣分项"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="cloneFormRef"
        :model="cloneForm"
        :rules="cloneRules"
        label-width="120px"
      >
        <el-form-item label="源项目">
          <el-input :value="cloneForm.sourceProjectName" disabled />
        </el-form-item>
        <el-form-item label="目标项目" prop="targetProjectId">
          <el-select
            v-model="cloneForm.targetProjectId"
            placeholder="请选择目标项目"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in projectList.filter(p => p.id !== cloneForm.sourceProjectId)"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-alert
          type="info"
          :closable="false"
          show-icon
        >
          <template #title>
            将复制 <strong>{{ cloneForm.itemCount }}</strong> 个扣分项到目标项目
          </template>
        </el-alert>
      </el-form>
      <template #footer>
        <el-button @click="cloneDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="cloneLoading" @click="handleCloneSubmit">
          确定克隆
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Edit,
  Download,
  InfoFilled,
  Rank
} from '@element-plus/icons-vue'
import {
  getDeductionList,
  addDeduction,
  updateDeduction,
  removeDeduction,
  cloneDeductions,
  updateDeductionOrder
} from '@/api/martial/deduction'
import { getProjectList } from '@/api/martial/project'
import dayjs from 'dayjs'
import Sortable from 'sortablejs'
import { getCompetitionList } from '@/api/martial/competition'

// 数据定义
const loading = ref(false)
const submitLoading = ref(false)
const cloneLoading = ref(false)
const tableData = ref([])
const total = ref(0)
const selection = ref([])
const projectList = ref([])
const dialogVisible = ref(false)
const cloneDialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const cloneFormRef = ref(null)
const competitionList = ref([])
const competitionLoading = ref(false)

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  competitionId: null,
  projectId: null,
})

// 表单数据
const form = reactive({
  id: null,
  competitionId: null,
  projectId: null,
  deductionPoints: 0.5,
  sortOrder: 0,
  description: ''
})

// 克隆表单
const cloneForm = reactive({
  sourceProjectId: '',
  sourceProjectName: '',
  targetProjectId: '',
  itemCount: 0
})

// 表单验证规则
const rules = {
  competitionId: [
    { required: true, message: '请选择赛事', trigger: 'change' }
  ],
  projectId: [
    { required: true, message: '请选择所属项目', trigger: 'change' }
  ],
  itemName: [
    { required: true, message: '请输入扣分项名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  deductionPoints: [
    { required: true, message: '请输入扣分值', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序序号', trigger: 'blur' }
  ]
}

// 克隆表单验证规则
const cloneRules = {
  targetProjectId: [
    { required: true, message: '请选择目标项目', trigger: 'change' }
  ]
}

// 加载赛事列表
const loadCompetitionList = async () => {
  competitionLoading.value = true
  try {
    const resCompe = await getCompetitionList(1, 1000, {})
    const recordsCompe = resCompe.data?.data?.records || []
    competitionList.value = recordsCompe

    if (recordsCompe.length === 0) {
      console.warn('赛事列表为空，请先在"赛事管理"中创建赛事')
    }
  } catch (error) {
    console.error('加载赛事列表失败:', error)
    ElMessage.error('加载赛事列表失败')
  } finally {
    competitionLoading.value = false
  }
}

// 加载项目列表（根据赛事ID）
const loadProjectList = async (competitionId) => {
  if (!competitionId) {
    projectList.value = []
    return
  }

  try {
    const res = await getProjectList(1, 1000, { competitionId })
    // 根据axios响应拦截器的处理，数据在 res.data.data.records 中
    const records = res.data?.data?.records || []
    projectList.value = records

    if (records.length === 0) {
      console.warn('该赛事下暂无项目，请先在"轮编管理"中创建项目')
    }
  } catch (error) {
    console.error('加载项目列表失败:', error)
    ElMessage.error('加载项目列表失败')
  }
}

// 赛事选择变化
const handleCompetitionChange = (competitionId) => {
  // 清空项目选择和表格数据
  queryParams.projectId = null
  tableData.value = []
  total.value = 0

  // 加载该赛事下的项目
  if (competitionId) {
    loadProjectList(competitionId)
    // 自动查询数据
    fetchData()
  } else {
    projectList.value = []
  }
}

// 查询数据
const fetchData = async () => {
  // 必须选择赛事才能查询
  if (!queryParams.competitionId) {
    ElMessage.warning('请先选择赛事')
    return
  }

  loading.value = true
  try {
    const res = await getDeductionList(
      queryParams.current,
      queryParams.size,
      queryParams
    )
    // 根据axios响应拦截器的处理，数据在 res.data.data 中
    const data = res.data?.data || {}
    tableData.value = data.records || []
    total.value = data.total || 0
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  const competitionId = queryParams.competitionId
  Object.assign(queryParams, {
    current: 1,
    size: 10,
    competitionId: competitionId,
    projectId: null,
    itemName: ''
  })
  if (competitionId) {
    fetchData()
  }
}

// 新增
const handleAdd = () => {
  if (!queryParams.competitionId) {
    ElMessage.warning('请先选择赛事')
    return
  }
  dialogTitle.value = '新增扣分项'
  resetForm()
  form.competitionId = queryParams.competitionId
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑扣分项'
  Object.keys(form).forEach((key) => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该扣分项吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await removeDeduction(row.id)
        ElMessage.success('删除成功')
        fetchData()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selection.value.length} 个扣分项吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const ids = selection.value.map((item) => item.id).join(',')
        await removeDeduction(ids)
        ElMessage.success('删除成功')
        fetchData()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}


// 提交克隆
const handleCloneSubmit = async () => {
  if (!cloneFormRef.value) return

  await cloneFormRef.value.validate(async (valid) => {
    if (valid) {
      cloneLoading.value = true
      try {
        await cloneDeductions({
          sourceProjectId: cloneForm.sourceProjectId,
          targetProjectId: cloneForm.targetProjectId
        })
        ElMessage.success('克隆成功')
        cloneDialogVisible.value = false
        fetchData()
      } catch (error) {
        ElMessage.error('克隆失败')
      } finally {
        cloneLoading.value = false
      }
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (form.id) {
          await updateDeduction(form)
          ElMessage.success('修改成功')
        } else {
          await addDeduction(form)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        ElMessage.error(form.id ? '修改失败' : '新增失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 选择变化
const handleSelectionChange = (val) => {
  selection.value = val
}

// 关闭弹窗
const handleDialogClose = () => {
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    competitionId: null,
    projectId: null,
    itemName: '',
    deductionPoints: 0.5,
    sortOrder: 0,
    description: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 导出模板
const handleExport = async () => {
  try {
    const csvContent = [
      ['项目ID', '扣分项名称', '扣分值', '描述说明', '排序序号'],
      ['1', '示例扣分项', '0.5', '这是一个示例', '1']
    ].map(row => row.join(',')).join('\n')

    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `扣分项导入模板_${dayjs().format('YYYYMMDDHHmmss')}.csv`
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 初始化拖拽排序
const initSortable = () => {
  nextTick(() => {
    const tbody = document.querySelector('.el-table__body-wrapper tbody')
    if (!tbody) return

    Sortable.create(tbody, {
      handle: '.drag-handle',
      animation: 150,
      onEnd: async ({ oldIndex, newIndex }) => {
        if (oldIndex === newIndex) return

        const movedItem = tableData.value.splice(oldIndex, 1)[0]
        tableData.value.splice(newIndex, 0, movedItem)

        // 更新排序
        try {
          const sortData = tableData.value.map((item, index) => ({
            id: item.id,
            sortOrder: index
          }))
          await updateDeductionOrder(sortData)
          ElMessage.success('排序已更新')
        } catch (error) {
          ElMessage.error('排序更新失败')
          fetchData() // 重新加载数据
        }
      }
    })
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 生命周期
onMounted(() => {
  loadCompetitionList()
  initSortable()
})
</script>

<style scoped lang="scss">
.deduction-container {
  padding: 20px;

  .search-card,
  .toolbar-card,
  .table-card {
    margin-bottom: 20px;
  }

  .search-form {
    .el-form-item {
      margin-bottom: 0;
    }
  }

  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .toolbar-left {
      display: flex;
      gap: 10px;
    }

    .toolbar-right {
      display: flex;
      gap: 10px;
      align-items: center;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .drag-handle {
    cursor: move;
    vertical-align: middle;
  }

  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }
}
</style>
