<template>
  <div class="homework-page">
    <a-card class="mb-4">
      <template #title>作业管理</template>
      <template #extra>
        <a-button
          v-permission="'homework:create'"
          type="primary"
          @click="handleAdd"
        >
          <template #icon><PlusOutlined /></template>
          创建作业
        </a-button>
      </template>
    </a-card>

    <!-- 搜索表单 -->
    <a-form
      :model="searchParams"
      layout="inline"
      class="search-form"
      @finish="handleSearch"
    >
      <a-form-item label="作业名称">
        <a-input
          v-model:value="searchParams.name"
          placeholder="请输入作业名称"
          allow-clear
          style="width: 200px"
        />
      </a-form-item>
      <a-form-item label="作业状态">
        <a-select
          v-model:value="searchParams.status"
          placeholder="请选择状态"
          allow-clear
          style="width: 120px"
        >
          <a-select-option value="published">已发布</a-select-option>
          <a-select-option value="unpublished">未发布</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="提交时间">
        <a-range-picker
          v-model:value="submitTimeRange"
          :placeholder="['开始时间', '结束时间']"
          style="width: 280px"
          @change="handleTimeRangeChange"
        />
      </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 }">
        <template v-if="column.key === 'name'">
          {{ record.name }}
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="record.status === 'published' ? 'success' : 'default'">
            {{ record.status === "published" ? "已发布" : "未发布" }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'publishScope'">
          <span v-if="record.publishScopeNames && record.publishScopeNames.length > 0">
            {{ record.publishScopeNames.join("、") }}
          </span>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'submitTime'">
          <div>
            {{ formatDateTime(record.submitStartTime) }} ~
            {{ formatDateTime(record.submitEndTime) }}
          </div>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <!-- 发布/取消发布 -->
            <a-button
              v-permission="'homework:update'"
              type="link"
              size="small"
              @click="handlePublish(record)"
            >
              {{ record.status === "published" ? "取消发布" : "发布" }}
            </a-button>
            <!-- 提交记录 -->
            <a-button
              v-permission="'homework:read'"
              type="link"
              size="small"
              @click="handleViewSubmissions(record.id)"
            >
              提交记录
            </a-button>
            <!-- 编辑 -->
            <a-button
              v-permission="'homework:update'"
              type="link"
              size="small"
              :disabled="record.status === 'published'"
              @click="handleEdit(record)"
            >
              编辑
            </a-button>
            <!-- 删除 -->
            <a-popconfirm
              v-permission="'homework:delete'"
              title="确定要删除这个作业吗？"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 创建/编辑作业抽屉 -->
    <a-drawer
      v-model:open="drawerVisible"
      :title="editingId ? '编辑作业' : '创建作业'"
      placement="right"
      width="600px"
      :footer-style="{ textAlign: 'right' }"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item label="作业名称" name="name">
          <a-input v-model:value="formData.name" placeholder="请输入作业名称" />
        </a-form-item>
        <a-form-item label="提交时间" name="submitTimeRange">
          <a-range-picker
            v-model:value="formData.submitTimeRange"
            show-time
            :placeholder="['开始时间', '结束时间']"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="评审规则" name="reviewRuleId">
          <a-select
            v-model:value="formData.reviewRuleId"
            placeholder="请选择评审规则"
            allow-clear
            :options="reviewRuleOptions"
            :field-names="{ label: 'name', value: 'id' }"
          />
        </a-form-item>
        <a-form-item label="作业内容" name="content">
          <a-textarea
            v-model:value="formData.content"
            placeholder="请输入作业内容"
            :rows="6"
          />
        </a-form-item>
        <a-form-item label="附件">
          <a-upload
            v-model:file-list="formData.fileList"
            :before-upload="beforeUpload"
            :custom-request="customUpload"
            @remove="handleRemoveFile"
          >
            <a-button>
              <template #icon><UploadOutlined /></template>
              上传附件
            </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="drawerVisible = false">取消</a-button>
          <a-button type="primary" :loading="submitting" @click="handleSave">
            保存
          </a-button>
          <a-button
            v-if="!editingId"
            type="primary"
            :loading="submitting"
            @click="handleSaveAndPublish"
          >
            保存并发布
          </a-button>
        </a-space>
      </template>
    </a-drawer>

    <!-- 发布时选择公开范围 -->
    <a-modal
      v-model:open="publishModalVisible"
      title="选择公开范围"
      @ok="confirmPublish"
      @cancel="publishModalVisible = false"
    >
      <a-form layout="vertical">
        <a-form-item label="公开范围" required>
          <a-tree-select
            v-model:value="publishScope"
            :tree-data="classTreeData"
            tree-checkable
            :show-checked-strategy="TreeSelect.SHOW_CHILD"
            placeholder="请选择班级"
            style="width: 100%"
            :field-names="{ label: 'name', value: 'id', children: 'children' }"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue"
import { useRouter, useRoute } from "vue-router"
import { message, TreeSelect } from "ant-design-vue"
import type { FormInstance, UploadProps } from "ant-design-vue"
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  UploadOutlined,
} from "@ant-design/icons-vue"
import { useListRequest } from "@/composables/useListRequest"
import {
  homeworksApi,
  reviewRulesApi,
  submissionsApi,
  type Homework,
  type QueryHomeworkParams,
  type HomeworkReviewRule,
  type HomeworkAttachment,
  type ClassTreeNode,
} from "@/api/homework"
import { uploadApi } from "@/api/upload"
import dayjs, { Dayjs } from "dayjs"

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

// 使用列表请求组合函数
const {
  loading,
  dataSource,
  pagination,
  searchParams,
  fetchList,
  resetSearch,
  search,
  handleTableChange,
} = useListRequest<Homework, QueryHomeworkParams>({
  requestFn: homeworksApi.getList,
  defaultSearchParams: {} as QueryHomeworkParams,
  defaultPageSize: 10,
  errorMessage: "获取作业列表失败",
})

// 时间范围
const submitTimeRange = ref<[Dayjs, Dayjs] | null>(null)

// 表格列定义
const columns = [
  {
    title: "序号",
    key: "index",
    width: 60,
    customRender: ({ index }: { index: number }) => index + 1,
  },
  {
    title: "作业名称",
    key: "name",
    dataIndex: "name",
    width: 200,
  },
  {
    title: "作业状态",
    key: "status",
    dataIndex: "status",
    width: 100,
  },
  {
    title: "公开范围",
    key: "publishScope",
    width: 200,
  },
  {
    title: "提交时间",
    key: "submitTime",
    width: 350,
  },
  {
    title: "操作",
    key: "action",
    width: 280,
    fixed: "right" as const,
  },
]

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

// 时间范围变化
const handleTimeRangeChange = (dates: [Dayjs, Dayjs] | null) => {
  if (dates) {
    searchParams.submitStartTime = dates[0].format("YYYY-MM-DD")
    searchParams.submitEndTime = dates[1].format("YYYY-MM-DD")
  } else {
    searchParams.submitStartTime = undefined
    searchParams.submitEndTime = undefined
  }
}

// 搜索
const handleSearch = () => {
  search()
}

// 重置搜索
const handleReset = () => {
  submitTimeRange.value = null
  resetSearch()
}

// 抽屉相关
const drawerVisible = ref(false)
const editingId = ref<number | null>(null)
const submitting = ref(false)
const formRef = ref<FormInstance>()
const reviewRuleOptions = ref<HomeworkReviewRule[]>([])

const formData = reactive<{
  name: string
  content: string
  submitTimeRange: [Dayjs, Dayjs] | null
  reviewRuleId: number | undefined
  fileList: any[]
}>({
  name: "",
  content: "",
  submitTimeRange: null,
  reviewRuleId: undefined,
  fileList: [],
})

const formRules = {
  name: [{ required: true, message: "请输入作业名称" }],
  submitTimeRange: [{ required: true, message: "请选择提交时间" }],
}

// 加载评审规则
const loadReviewRules = async () => {
  try {
    const rules = await reviewRulesApi.getForSelect()
    reviewRuleOptions.value = rules
  } catch (error) {
    console.error("加载评审规则失败", error)
  }
}

// 新增
const handleAdd = () => {
  editingId.value = null
  formData.name = ""
  formData.content = ""
  formData.submitTimeRange = null
  formData.reviewRuleId = undefined
  formData.fileList = []
  drawerVisible.value = true
  loadReviewRules()
}

// 编辑
const handleEdit = async (record: Homework) => {
  editingId.value = record.id
  formData.name = record.name
  formData.content = record.content || ""
  formData.submitTimeRange = [
    dayjs(record.submitStartTime),
    dayjs(record.submitEndTime),
  ]
  formData.reviewRuleId = record.reviewRuleId

  // 处理 attachments：可能是数组或 JSON 字符串
  let attachments: HomeworkAttachment[] = []
  if (record.attachments) {
    if (typeof record.attachments === "string") {
      try {
        attachments = JSON.parse(record.attachments)
      } catch (e) {
        console.error("解析 attachments 失败", e)
        attachments = []
      }
    } else if (Array.isArray(record.attachments)) {
      attachments = record.attachments
    }
  }

  formData.fileList = attachments.map((att, index) => ({
    uid: `-${index}`,
    name: att.fileName,
    status: "done",
    url: att.fileUrl,
  }))
  drawerVisible.value = true
  loadReviewRules()
}

// 文件上传
const beforeUpload: UploadProps["beforeUpload"] = () => {
  return false
}

const customUpload = async ({ file, onSuccess, onError }: any) => {
  try {
    const formData = new FormData()
    formData.append("file", file)
    const result = await uploadApi.upload(formData)
    file.url = result.url
    onSuccess(result)
  } catch (error) {
    onError(error)
  }
}

const handleRemoveFile = () => {
  return true
}

// 保存
const handleSave = async () => {
  try {
    await formRef.value?.validate()
    submitting.value = true

    const attachments = formData.fileList.map((file) => ({
      fileName: file.name,
      fileUrl: file.url || file.response?.url,
      size: file.size?.toString(),
    }))

    const submitData = {
      name: formData.name,
      content: formData.content,
      submitStartTime: formData.submitTimeRange?.[0]?.toISOString(),
      submitEndTime: formData.submitTimeRange?.[1]?.toISOString(),
      reviewRuleId: formData.reviewRuleId,
      attachments,
    }

    if (editingId.value) {
      await homeworksApi.update(editingId.value, submitData)
      message.success("更新成功")
    } else {
      await homeworksApi.create(submitData as any)
      message.success("创建成功")
    }

    drawerVisible.value = false
    fetchList()
  } catch (error: any) {
    if (error?.errorFields) return
    message.error(error?.response?.data?.message || "操作失败")
  } finally {
    submitting.value = false
  }
}

// 保存并发布
const handleSaveAndPublish = async () => {
  try {
    await formRef.value?.validate()
    submitting.value = true

    const attachments = formData.fileList.map((file) => ({
      fileName: file.name,
      fileUrl: file.url || file.response?.url,
      size: file.size?.toString(),
    }))

    const submitData = {
      name: formData.name,
      content: formData.content,
      submitStartTime: formData.submitTimeRange?.[0]?.toISOString(),
      submitEndTime: formData.submitTimeRange?.[1]?.toISOString(),
      reviewRuleId: formData.reviewRuleId,
      attachments,
    }

    const created = await homeworksApi.create(submitData as any)
    currentPublishingId.value = created.id
    drawerVisible.value = false
    publishModalVisible.value = true
    loadClassTree()
  } catch (error: any) {
    if (error?.errorFields) return
    message.error(error?.response?.data?.message || "操作失败")
  } finally {
    submitting.value = false
  }
}

// 发布相关
const publishModalVisible = ref(false)
const publishScope = ref<number[]>([])
const currentPublishingId = ref<number | null>(null)
const classTreeData = ref<ClassTreeNode[]>([])

const loadClassTree = async () => {
  try {
    const tree = await submissionsApi.getClassTree()
    classTreeData.value = tree
  } catch (error) {
    console.error("加载班级树失败", error)
  }
}

const handlePublish = async (record: Homework) => {
  if (record.status === "published") {
    // 取消发布
    try {
      await homeworksApi.unpublish(record.id)
      message.success("取消发布成功")
      fetchList()
    } catch (error: any) {
      message.error(error?.response?.data?.message || "操作失败")
    }
  } else {
    // 发布
    currentPublishingId.value = record.id
    publishScope.value = []
    publishModalVisible.value = true
    loadClassTree()
  }
}

const confirmPublish = async () => {
  if (!publishScope.value || publishScope.value.length === 0) {
    message.warning("请选择公开范围")
    return
  }

  try {
    await homeworksApi.publish(currentPublishingId.value!, publishScope.value)
    message.success("发布成功")
    publishModalVisible.value = false
    fetchList()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "发布失败")
  }
}

// 查看提交记录
const handleViewSubmissions = (id: number) => {
  router.push(`/${tenantCode}/homework/submissions?homeworkId=${id}`)
}

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

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

<style scoped>
.search-form {
  margin-bottom: 16px;
}
</style>
