<template>
  <div class="notices-page">
    <!-- 标题卡片 -->
    <a-card class="mb-4">
      <template #title>公告管理</template>
      <template #extra>
        <a-button
          v-permission="'notice:create'"
          type="primary"
          @click="handleAdd"
        >
          <template #icon><PlusOutlined /></template>
          新建公告
        </a-button>
      </template>
    </a-card>

    <!-- 搜索表单 -->
    <a-form layout="inline" :model="searchForm" class="search-form" @finish="handleSearch">
      <a-form-item label="标题名称">
        <a-input
          v-model:value="searchForm.title"
          placeholder="请输入标题名称"
          style="width: 200px"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="发布日期">
        <a-date-picker
          v-model:value="searchForm.publishDate"
          placeholder="请选择发布日期"
          style="width: 200px"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">
          <template #icon><SearchOutlined /></template>
          搜索
        </a-button>
        <a-button style="margin-left: 8px" @click="handleReset">
          <template #icon><ReloadOutlined /></template>
          重置
        </a-button>
      </a-form-item>
    </a-form>

    <!-- 数据表格 -->
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'index'">
          {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
        </template>
        <template v-else-if="column.key === 'title'">
          <a @click="handleView(record)">{{ record.title }}</a>
        </template>
        <template v-else-if="column.key === 'contestName'">
          {{ record.contest?.contestName || "-" }}
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="record.publishTime ? 'success' : 'default'">
            {{ record.publishTime ? "已发布" : "未发布" }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'publishTime'">
          {{ formatDateTime(record.publishTime) }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button
              v-permission="'notice:update'"
              type="link"
              size="small"
              @click="handleTogglePublish(record)"
            >
              {{ record.publishTime ? "取消发布" : "发布" }}
            </a-button>
            <a-button
              v-permission="'notice:update'"
              type="link"
              size="small"
              @click="handleEdit(record)"
            >
              编辑
            </a-button>
            <a-popconfirm
              v-permission="'notice:delete'"
              title="确定要删除这条公告吗？"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 公告详情弹窗 -->
    <a-modal
      v-model:open="viewModalVisible"
      :title="currentNotice?.title"
      :footer="null"
      width="600px"
    >
      <a-descriptions :column="1" bordered v-if="currentNotice">
        <a-descriptions-item label="关联活动">
          {{ currentNotice.contest?.contestName || "-" }}
        </a-descriptions-item>
        <a-descriptions-item label="发布时间">
          {{ formatDateTime(currentNotice.publishTime) }}
        </a-descriptions-item>
        <a-descriptions-item label="公告内容">
          <div v-html="currentNotice.content"></div>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>

    <!-- 创建/编辑公告抽屉 -->
    <a-drawer
      v-model:open="drawerVisible"
      :title="isEditing ? '编辑公告' : '新建公告'"
      width="600px"
      placement="right"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item label="标题名称" name="title" required>
          <a-input
            v-model:value="formData.title"
            placeholder="请输入标题名称"
          />
        </a-form-item>
        <a-form-item label="关联活动" name="contestId" required>
          <a-select
            v-model:value="formData.contestId"
            placeholder="请选择关联活动"
            show-search
            :filter-option="filterContestOption"
            :loading="contestsLoading"
          >
            <a-select-option
              v-for="contest in contestsList"
              :key="contest.id"
              :value="contest.id"
            >
              {{ contest.contestName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="正文" name="content" required>
          <a-textarea
            v-model:value="formData.content"
            placeholder="请输入正文内容"
            :rows="8"
          />
        </a-form-item>
        <a-form-item label="活动附件">
          <a-upload
            v-model:file-list="attachmentFileList"
            :before-upload="beforeUpload"
            :custom-request="handleUpload"
            :on-remove="handleRemoveAttachment"
          >
            <a-button>
              <template #icon><UploadOutlined /></template>
              上传附件
            </a-button>
          </a-upload>
          <div v-if="attachmentList.length > 0" style="margin-top: 16px">
            <div
              v-for="attachment in attachmentList"
              :key="attachment.id"
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                margin-bottom: 8px;
              "
            >
              <span>{{ attachment.fileName }}</span>
              <a-space>
                <a-button
                  type="link"
                  size="small"
                  @click="handleDownload(attachment)"
                >
                  下载
                </a-button>
                <a-button
                  type="link"
                  danger
                  size="small"
                  @click="handleDeleteAttachment(attachment.id)"
                >
                  删除
                </a-button>
              </a-space>
            </div>
          </div>
        </a-form-item>
      </a-form>

      <template #footer>
        <a-space>
          <a-button @click="handleCancel">取消</a-button>
          <a-button
            type="primary"
            :loading="submitLoading"
            @click="handleSubmit"
          >
            保存
          </a-button>
        </a-space>
      </template>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue"
import { useRoute } from "vue-router"
import { message } from "ant-design-vue"
import { PlusOutlined, UploadOutlined, SearchOutlined, ReloadOutlined } from "@ant-design/icons-vue"
import dayjs, { type Dayjs } from "dayjs"
import type { FormInstance, UploadFile } from "ant-design-vue"
import {
  contestsApi,
  noticesApi,
  attachmentsApi,
  type Contest,
  type ContestNotice,
  type CreateNoticeForm,
  type ContestAttachment,
} from "@/api/contests"

const route = useRoute()
const tenantCode = route.params.tenantCode as string

const loading = ref(false)
const dataSource = ref<ContestNotice[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})

// 搜索表单
const searchForm = reactive({
  title: "",
  publishDate: null as Dayjs | null,
})

// 详情弹窗
const viewModalVisible = ref(false)
const currentNotice = ref<ContestNotice | null>(null)

// 抽屉
const drawerVisible = ref(false)
const submitLoading = ref(false)
const isEditing = ref(false)
const editingId = ref<number | null>(null)
const formRef = ref<FormInstance>()
const formData = reactive<CreateNoticeForm>({
  contestId: 0,
  title: "",
  content: "",
})

// 活动列表
const contestsList = ref<Contest[]>([])
const contestsLoading = ref(false)

// 附件
const attachmentFileList = ref<UploadFile[]>([])
const attachmentList = ref<ContestAttachment[]>([])

const formRules = {
  title: [{ required: true, message: "请输入标题名称", trigger: "blur" }],
  contestId: [{ required: true, message: "请选择关联活动", trigger: "change" }],
  content: [{ required: true, message: "请输入正文内容", trigger: "blur" }],
}

// 表格列定义
const columns = [
  {
    title: "序号",
    key: "index",
    width: 80,
    align: "center" as const,
  },
  {
    title: "公告标题",
    key: "title",
    dataIndex: "title",
    width: 250,
  },
  {
    title: "活动名称",
    key: "contestName",
    width: 200,
  },
  {
    title: "状态",
    key: "status",
    width: 100,
    align: "center" as const,
  },
  {
    title: "发布时间",
    key: "publishTime",
    dataIndex: "publishTime",
    width: 180,
  },
  {
    title: "操作",
    key: "action",
    width: 200,
    fixed: "right" as const,
  },
]

// 格式化日期时间
const formatDateTime = (dateStr?: string) => {
  if (!dateStr) return "-"
  return dayjs(dateStr).format("YYYY-MM-DD HH:mm")
}

// 过滤活动选项
const filterContestOption = (input: string, option: any) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 加载活动列表
const fetchContests = async () => {
  contestsLoading.value = true
  try {
    const response = await contestsApi.getList({
      page: 1,
      pageSize: 100,
      contestState: "published",
    })
    contestsList.value = response.list || []
  } catch (error: any) {
    console.error("获取活动列表失败", error)
    message.error(error?.response?.data?.message || "获取活动列表失败")
  } finally {
    contestsLoading.value = false
  }
}

// 加载公告列表
const fetchNotices = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.current,
      pageSize: pagination.pageSize,
    }

    if (searchForm.title) {
      params.title = searchForm.title
    }

    if (searchForm.publishDate) {
      params.publishDate = searchForm.publishDate.format("YYYY-MM-DD")
    }

    const response = await noticesApi.getAll(params)
    dataSource.value = response.list || []
    pagination.total = response.total || 0
  } catch (error: any) {
    message.error(error?.response?.data?.message || "获取公告列表失败")
  } finally {
    loading.value = false
  }
}

// 加载附件列表
const fetchAttachments = async (noticeId: number) => {
  try {
    // TODO: 需要后端API支持获取公告附件
    // 临时方案：使用活动附件API
    const notice = dataSource.value.find((n) => n.id === noticeId)
    if (notice) {
      const attachments = await attachmentsApi.getList(notice.contestId)
      attachmentList.value = attachments.filter(
        (a) => a.contestId === notice.contestId
      )
    }
  } catch (error) {
    console.error("获取附件列表失败", error)
  }
}

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchNotices()
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchNotices()
}

// 重置
const handleReset = () => {
  searchForm.title = ""
  searchForm.publishDate = null
  pagination.current = 1
  fetchNotices()
}

// 查看详情
const handleView = (record: ContestNotice) => {
  currentNotice.value = record
  viewModalVisible.value = true
}

// 新增
const handleAdd = async () => {
  isEditing.value = false
  editingId.value = null
  formData.contestId = 0
  formData.title = ""
  formData.content = ""
  attachmentList.value = []
  attachmentFileList.value = []

  // 打开抽屉时加载活动列表
  await fetchContests()
  drawerVisible.value = true
}

// 编辑
const handleEdit = async (record: ContestNotice) => {
  isEditing.value = true
  editingId.value = record.id
  formData.contestId = record.contestId
  formData.title = record.title
  formData.content = record.content
  attachmentList.value = []
  attachmentFileList.value = []
  await fetchAttachments(record.id)
  drawerVisible.value = true
}

// 删除
const handleDelete = async (id: number) => {
  try {
    await noticesApi.delete(id)
    message.success("删除成功")
    fetchNotices()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "删除失败")
  }
}

// 发布/取消发布
const handleTogglePublish = async (record: ContestNotice) => {
  try {
    if (record.publishTime) {
      // 取消发布
      await noticesApi.update(record.id, {
        publishTime: null,
      } as any)
      message.success("取消发布成功")
    } else {
      // 发布
      await noticesApi.update(record.id, {
        publishTime: new Date().toISOString(),
      } as any)
      message.success("发布成功")
    }
    fetchNotices()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "操作失败")
  }
}

// 上传前检查
const beforeUpload = (_file: File) => {
  // 可以添加文件大小、类型等验证
  return true
}

// 上传文件
const handleUpload = async (options: any) => {
  const { file, onSuccess, onError } = options
  try {
    // TODO: 调用实际上传接口
    // 临时方案：先添加到附件列表
    const attachment: ContestAttachment = {
      id: Date.now(),
      contestId: formData.contestId,
      fileName: file.name,
      fileUrl: URL.createObjectURL(file),
      size: String(file.size),
    }
    attachmentList.value.push(attachment)
    onSuccess()
    message.success("上传成功")
  } catch (error) {
    onError(error)
    message.error("上传失败")
  }
}

// 删除附件
const handleRemoveAttachment = (file: UploadFile) => {
  // 从附件列表中移除
  attachmentList.value = attachmentList.value.filter(
    (a) => a.fileName !== file.name
  )
}

// 下载附件
const handleDownload = (attachment: ContestAttachment) => {
  window.open(attachment.fileUrl, "_blank")
}

// 删除附件
const handleDeleteAttachment = async (id: number) => {
  try {
    // TODO: 调用后端删除接口
    attachmentList.value = attachmentList.value.filter((a) => a.id !== id)
    message.success("删除成功")
  } catch (error: any) {
    message.error(error?.response?.data?.message || "删除失败")
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    if (isEditing.value && editingId.value) {
      await noticesApi.update(editingId.value, {
        contestId: formData.contestId,
        title: formData.title,
        content: formData.content,
      })
      message.success("更新成功")
    } else {
      await noticesApi.create({
        contestId: formData.contestId,
        title: formData.title,
        content: formData.content,
      })
      message.success("创建成功")
    }

    drawerVisible.value = false
    fetchNotices()
  } catch (error: any) {
    if (error?.errorFields) {
      return // 表单验证失败
    }
    message.error(
      error?.response?.data?.message ||
        (isEditing.value ? "更新失败" : "创建失败")
    )
  } finally {
    submitLoading.value = false
  }
}

// 取消
const handleCancel = () => {
  drawerVisible.value = false
  formRef.value?.resetFields()
}

onMounted(() => {
  fetchNotices()
})
</script>

<style scoped lang="scss">
// 主色调
$primary: #1890ff;
$primary-dark: #0958d9;
$gradient-primary: linear-gradient(135deg, $primary 0%, $primary-dark 100%);

.notices-page {
  // 标题卡片样式
  :deep(.ant-card) {
    border: none;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

    .ant-card-head {
      border-bottom: none;
      padding: 16px 24px;

      .ant-card-head-title {
        font-size: 18px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.85);
      }
    }

    .ant-card-body {
      padding: 0;
    }
  }

  // 渐变主按钮样式
  :deep(.ant-btn-primary) {
    background: $gradient-primary;
    border: none;
    box-shadow: 0 4px 12px rgba($primary, 0.35);
    transition: all 0.3s ease;

    &:hover {
      background: linear-gradient(135deg, $primary-dark 0%, darken($primary-dark, 8%) 100%);
      box-shadow: 0 6px 16px rgba($primary, 0.45);
      transform: translateY(-1px);
    }

    &:active {
      transform: translateY(0);
    }
  }

  // 表格样式
  :deep(.ant-table-wrapper) {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow: hidden;

    .ant-table {
      .ant-table-thead > tr > th {
        background: #fafafa;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.85);
        border-bottom: 1px solid #f0f0f0;
      }

      .ant-table-tbody > tr {
        transition: all 0.2s ease;

        &:hover > td {
          background: rgba($primary, 0.04);
        }

        > td {
          border-bottom: 1px solid #f5f5f5;
        }
      }
    }

    .ant-table-pagination {
      padding: 16px;
      margin: 0;
    }
  }
}

.search-form {
  margin-bottom: 16px;
  padding: 20px 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

  // 自适应换行
  :deep(.ant-form-item) {
    margin-bottom: 16px;
    margin-right: 16px;

    &:last-child {
      margin-right: 0;
    }
  }
}

.mb-4 {
  margin-bottom: 16px;
}
</style>
