<template>
  <div class="rules-container">
    <!-- 赛事选择 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" class="search-form">
        <el-form-item label="选择赛事">
          <el-select
            v-model="competitionId"
            placeholder="请选择赛事"
            clearable
            filterable
            style="width: 300px"
            @change="handleCompetitionChange"
          >
            <el-option
              v-for="item in competitionList"
              :key="item.id"
              :label="item.competitionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <div v-if="competitionId" class="content-wrapper">
      <!-- 附件管理 -->
      <el-card shadow="never" class="section-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">📎 规程附件</span>
            <el-button type="primary" size="small" :icon="Plus" @click="handleAddAttachment">
              添加附件
            </el-button>
          </div>
        </template>

        <el-table :data="attachmentList" border stripe>
          <el-table-column prop="fileName" label="文件名称" min-width="200" />
          <el-table-column prop="fileType" label="文件类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag>{{ row.fileType }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="fileSize" label="文件大小" width="120" align="center">
            <template #default="{ row }">
              {{ formatFileSize(row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column prop="orderNum" label="排序" width="80" align="center" />
          <el-table-column prop="status" label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="handleEditAttachment(row)">
                编辑
              </el-button>
              <el-button link type="primary" size="small" @click="handlePreviewFile(row)">
                预览
              </el-button>
              <el-button link type="danger" size="small" @click="handleDeleteAttachment(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 章节管理 -->
      <el-card shadow="never" class="section-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">📄 规程章节</span>
            <el-button type="primary" size="small" :icon="Plus" @click="handleAddChapter">
              添加章节
            </el-button>
          </div>
        </template>

        <el-table :data="chapterList" border stripe>
          <el-table-column prop="chapterNumber" label="章节编号" width="120" />
          <el-table-column prop="title" label="章节标题" min-width="200" />
          <el-table-column prop="orderNum" label="排序" width="80" align="center" />
          <el-table-column prop="status" label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" align="center" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="handleEditChapter(row)">
                编辑
              </el-button>
              <el-button link type="success" size="small" @click="handleManageContent(row)">
                管理内容
              </el-button>
              <el-button link type="danger" size="small" @click="handleDeleteChapter(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <el-empty v-else description="请先选择赛事" />

    <!-- 附件编辑对话框 -->
    <el-dialog
      v-model="attachmentDialogVisible"
      :title="attachmentForm.id ? '编辑附件' : '添加附件'"
      width="600px"
    >
      <el-form :model="attachmentForm" :rules="attachmentRules" ref="attachmentFormRef" label-width="100px">
        <el-form-item label="文件上传" prop="fileUrl">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleFileUploadSuccess"
            :before-upload="beforeFileUpload"
            :file-list="fileList"
            :limit="1"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 pdf/doc/docx/xls/xlsx/ppt/pptx 等文档格式，文件大小不超过50MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="attachmentForm.fileName" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="attachmentForm.orderNum" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="attachmentForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="attachmentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveAttachment">确定</el-button>
      </template>
    </el-dialog>

    <!-- 章节编辑对话框 -->
    <el-dialog
      v-model="chapterDialogVisible"
      :title="chapterForm.id ? '编辑章节' : '添加章节'"
      width="600px"
    >
      <el-form :model="chapterForm" :rules="chapterRules" ref="chapterFormRef" label-width="100px">
        <el-form-item label="章节编号" prop="chapterNumber">
          <el-input v-model="chapterForm.chapterNumber" placeholder="如：第一章" />
        </el-form-item>
        <el-form-item label="章节标题" prop="title">
          <el-input v-model="chapterForm.title" placeholder="请输入章节标题" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="chapterForm.orderNum" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="chapterForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="chapterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveChapter">确定</el-button>
      </template>
    </el-dialog>

    <!-- 章节内容管理对话框 -->
    <el-dialog
      v-model="contentDialogVisible"
      title="管理章节内容"
      width="800px"
    >
      <div class="content-header">
        <span class="content-title">{{ currentChapter.chapterNumber }} {{ currentChapter.title }}</span>
        <el-button type="primary" size="small" :icon="Plus" @click="handleAddContent">
          添加内容
        </el-button>
      </div>

      <el-table :data="contentList" border stripe class="content-table">
        <el-table-column prop="content" label="内容" min-width="400">
          <template #default="{ row, $index }">
            <el-input
              v-if="row.editing"
              v-model="row.content"
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
            />
            <span v-else>{{ row.content }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderNum" label="排序" width="80" align="center" />
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row, $index }">
            <el-button
              v-if="!row.editing"
              link
              type="primary"
              size="small"
              @click="handleEditContent(row, $index)"
            >
              编辑
            </el-button>
            <el-button
              v-else
              link
              type="success"
              size="small"
              @click="handleSaveContent(row, $index)"
            >
              保存
            </el-button>
            <el-button link type="danger" size="small" @click="handleDeleteContent($index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="contentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchSaveContents">保存全部</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Upload, Download, Refresh, Search } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
import {
  getCompetitionList,
  getAttachmentList,
  saveAttachment,
  removeAttachment,
  getChapterList,
  saveChapter,
  removeChapter,
  getContentList,
  batchSaveContents
} from '@/api/martial/rules'

// 赛事列表
const competitionList = ref([])
const competitionId = ref(null)

// 附件相关
const attachmentList = ref([])
const attachmentDialogVisible = ref(false)
const attachmentFormRef = ref(null)
const attachmentForm = reactive({
  id: null,
  competitionId: null,
  fileName: '',
  fileUrl: '',
  fileSize: null,
  fileType: '',
  orderNum: 0,
  status: 1
})
const attachmentRules = {
  fileName: [{ required: true, message: '请输入文件名称', trigger: 'blur' }],
  fileUrl: [{ required: true, message: '请上传文件', trigger: 'change' }]
}
const fileList = ref([])

// 章节相关
const chapterList = ref([])
const chapterDialogVisible = ref(false)
const chapterFormRef = ref(null)
const chapterForm = reactive({
  id: null,
  competitionId: null,
  chapterNumber: '',
  title: '',
  orderNum: 0,
  status: 1
})
const chapterRules = {
  chapterNumber: [{ required: true, message: '请输入章节编号', trigger: 'blur' }],
  title: [{ required: true, message: '请输入章节标题', trigger: 'blur' }]
}

// 章节内容相关
const contentDialogVisible = ref(false)
const currentChapter = ref({})
const contentList = ref([])

// 文件上传配置
const uploadUrl = ref(import.meta.env.VITE_API_URL + '/blade-resource/oss/endpoint/put-file')
const uploadHeaders = ref({
  'Blade-Auth': 'bearer ' + getToken()
})

// 初始化
onMounted(() => {
  fetchCompetitionList()
})

// 获取赛事列表
const fetchCompetitionList = async () => {
  try {
    const res = await getCompetitionList({ current: 1, size: 1000 })
    competitionList.value = res.data.records || []
  } catch (error) {
    ElMessage.error('获取赛事列表失败')
  }
}

// 赛事切换
const handleCompetitionChange = () => {
  if (competitionId.value) {
    fetchAttachmentList()
    fetchChapterList()
  }
}

// 获取附件列表
const fetchAttachmentList = async () => {
  try {
    const res = await getAttachmentList({ competitionId: competitionId.value })
    attachmentList.value = res.data || []
  } catch (error) {
    ElMessage.error('获取附件列表失败')
  }
}

// 添加附件
const handleAddAttachment = () => {
  Object.assign(attachmentForm, {
    id: null,
    competitionId: competitionId.value,
    fileName: '',
    fileUrl: '',
    fileSize: null,
    fileType: '',
    orderNum: 0,
    status: 1
  })
  fileList.value = []
  attachmentDialogVisible.value = true
}

// 编辑附件
const handleEditAttachment = (row) => {
  Object.assign(attachmentForm, { ...row })
  fileList.value = row.fileUrl ? [{ name: row.fileName, url: row.fileUrl }] : []
  attachmentDialogVisible.value = true
}

// 文件上传前校验
const beforeFileUpload = (file) => {
  const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
  const isAllowed = allowedTypes.includes(file.type)
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isAllowed) {
    ElMessage.error('只能上传文档格式文件！')
  }
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB！')
  }
  return isAllowed && isLt50M
}

// 文件上传成功
const handleFileUploadSuccess = (response) => {
  if (response.code === 200) {
    attachmentForm.fileUrl = response.data.link
    attachmentForm.fileName = response.data.originalName
    attachmentForm.fileSize = response.data.size
    attachmentForm.fileType = response.data.extension
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error('文件上传失败')
  }
}

// 保存附件
const handleSaveAttachment = async () => {
  await attachmentFormRef.value.validate()
  try {
    await saveAttachment(attachmentForm)
    ElMessage.success('保存成功')
    attachmentDialogVisible.value = false
    fetchAttachmentList()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 删除附件
const handleDeleteAttachment = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该附件吗？', '提示', {
      type: 'warning'
    })
    await removeAttachment({ id: row.id })
    ElMessage.success('删除成功')
    fetchAttachmentList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 预览文件
const handlePreviewFile = (row) => {
  window.open(row.fileUrl, '_blank')
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes || 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]
}

// 获取章节列表
const fetchChapterList = async () => {
  try {
    const res = await getChapterList({ competitionId: competitionId.value })
    chapterList.value = res.data || []
  } catch (error) {
    ElMessage.error('获取章节列表失败')
  }
}

// 添加章节
const handleAddChapter = () => {
  Object.assign(chapterForm, {
    id: null,
    competitionId: competitionId.value,
    chapterNumber: '',
    title: '',
    orderNum: 0,
    status: 1
  })
  chapterDialogVisible.value = true
}

// 编辑章节
const handleEditChapter = (row) => {
  Object.assign(chapterForm, { ...row })
  chapterDialogVisible.value = true
}

// 保存章节
const handleSaveChapter = async () => {
  await chapterFormRef.value.validate()
  try {
    await saveChapter(chapterForm)
    ElMessage.success('保存成功')
    chapterDialogVisible.value = false
    fetchChapterList()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 删除章节
const handleDeleteChapter = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该章节吗？删除后章节下的所有内容也将被删除！', '提示', {
      type: 'warning'
    })
    await removeChapter({ id: row.id })
    ElMessage.success('删除成功')
    fetchChapterList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 管理章节内容
const handleManageContent = async (row) => {
  currentChapter.value = row
  await fetchContentList(row.id)
  contentDialogVisible.value = true
}

// 获取章节内容列表
const fetchContentList = async (chapterId) => {
  try {
    const res = await getContentList({ chapterId })
    contentList.value = (res.data || []).map(item => ({
      ...item,
      editing: false
    }))
  } catch (error) {
    ElMessage.error('获取章节内容失败')
  }
}

// 添加内容
const handleAddContent = () => {
  contentList.value.push({
    id: null,
    chapterId: currentChapter.value.id,
    content: '',
    orderNum: contentList.value.length + 1,
    status: 1,
    editing: true
  })
}

// 编辑内容
const handleEditContent = (row, index) => {
  row.editing = true
}

// 保存单个内容
const handleSaveContent = (row, index) => {
  if (!row.content.trim()) {
    ElMessage.warning('内容不能为空')
    return
  }
  row.editing = false
}

// 删除内容
const handleDeleteContent = (index) => {
  contentList.value.splice(index, 1)
  // 重新排序
  contentList.value.forEach((item, idx) => {
    item.orderNum = idx + 1
  })
}

// 批量保存内容
const handleBatchSaveContents = async () => {
  const contents = contentList.value.map(item => item.content).filter(c => c.trim())
  if (contents.length === 0) {
    ElMessage.warning('请至少添加一条内容')
    return
  }
  try {
    await batchSaveContents({
      chapterId: currentChapter.value.id,
      contents
    })
    ElMessage.success('保存成功')
    contentDialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存失败')
  }
}
</script>

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

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

.content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.section-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .card-title {
      font-size: 16px;
      font-weight: bold;
    }
  }
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;

  .content-title {
    font-size: 16px;
    font-weight: bold;
  }
}

.content-table {
  margin-top: 10px;
}
</style>
