<template>
  <div class="submissions-page">
    <a-card class="mb-4">
      <template #title>作业提交记录</template>
      <template #extra>
        <a-button @click="goBack">
          返回作业列表
        </a-button>
      </template>
    </a-card>

    <div class="page-content">
      <!-- 左侧班级树筛选 -->
      <div class="left-panel">
        <a-card title="行政班" size="small">
          <a-tree
            v-if="classTreeData.length > 0"
            :tree-data="classTreeData"
            :field-names="{ title: 'name', key: 'id', children: 'children' }"
            :selected-keys="selectedClassKeys"
            @select="handleClassSelect"
          />
          <a-empty v-else description="暂无班级数据" />
        </a-card>
      </div>

      <!-- 右侧内容区 -->
      <div class="right-panel">
        <!-- 搜索表单 -->
        <a-form
          :model="searchParams"
          layout="inline"
          class="search-form"
          @finish="handleSearch"
        >
          <a-form-item label="作品编号">
            <a-input
              v-model:value="searchParams.workNo"
              placeholder="请输入作品编号"
              allow-clear
              style="width: 150px"
            />
          </a-form-item>
          <a-form-item label="作品名称">
            <a-input
              v-model:value="searchParams.workName"
              placeholder="请输入作品名称"
              allow-clear
              style="width: 150px"
            />
          </a-form-item>
          <a-form-item label="学生账号">
            <a-input
              v-model:value="searchParams.studentAccount"
              placeholder="请输入学生账号"
              allow-clear
              style="width: 150px"
            />
          </a-form-item>
          <a-form-item label="学生姓名">
            <a-input
              v-model:value="searchParams.studentName"
              placeholder="请输入学生姓名"
              allow-clear
              style="width: 150px"
            />
          </a-form-item>
          <a-form-item label="评审状态">
            <a-select
              v-model:value="searchParams.status"
              placeholder="请选择状态"
              allow-clear
              style="width: 120px"
            >
              <a-select-option value="pending">未评审</a-select-option>
              <a-select-option value="reviewed">已评审</a-select-option>
              <a-select-option value="rejected">已拒绝</a-select-option>
            </a-select>
          </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">
              重置
            </a-button>
          </a-form-item>
        </a-form>

        <!-- 数据表格 -->
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="pagination"
          :row-selection="rowSelection"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'workName'">
              <a @click="handleReview(record)">{{ record.workName }}</a>
            </template>
            <template v-else-if="column.key === 'studentInfo'">
              <div>{{ record.student?.nickname || "-" }}</div>
              <div class="text-gray">{{ record.student?.username || "-" }}</div>
            </template>
            <template v-else-if="column.key === 'classInfo'">
              <div>
                {{
                  record.student?.student?.class?.grade?.name || "-"
                }}
              </div>
              <div class="text-gray">
                {{ record.student?.student?.class?.name || "-" }}
              </div>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'totalScore'">
              {{ record.totalScore ?? "-" }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-button type="link" size="small" @click="handleReview(record)">
                评审
              </a-button>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 评审抽屉 -->
    <a-drawer
      v-model:open="reviewDrawerVisible"
      :title="`${currentSubmission?.student?.nickname || ''}提交作品评审`"
      placement="right"
      width="700px"
    >
      <template v-if="currentSubmission">
        <a-descriptions :column="1" bordered size="small">
          <a-descriptions-item label="作品名称">
            {{ currentSubmission.workName }}
          </a-descriptions-item>
          <a-descriptions-item label="作品介绍">
            {{ currentSubmission.workDescription || "-" }}
          </a-descriptions-item>
          <a-descriptions-item label="提交时间">
            {{ formatDateTime(currentSubmission.submitTime) }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 作品附件 -->
        <a-card title="作品附件" size="small" class="mt-4">
          <template v-if="currentSubmission.attachments?.length">
            <div
              v-for="(att, index) in currentSubmission.attachments"
              :key="index"
              class="attachment-item"
            >
              <a :href="att.fileUrl" target="_blank">{{ att.fileName }}</a>
            </div>
          </template>
          <a-empty v-else description="暂无附件" />
        </a-card>

        <!-- 评分表单 -->
        <a-card title="作品打分" size="small" class="mt-4">
          <template v-if="reviewCriteria.length > 0">
            <div
              v-for="(criterion, index) in reviewCriteria"
              :key="index"
              class="score-item"
            >
              <div class="score-label">
                {{ criterion.name }} (满分 {{ criterion.maxScore }} 分)
              </div>
              <a-input-number
                v-model:value="scoreValues[index]"
                :min="0"
                :max="criterion.maxScore"
                style="width: 120px"
              />
            </div>
            <div class="score-item mt-4">
              <div class="score-label">评语</div>
              <a-textarea
                v-model:value="scoreComments"
                :rows="3"
                placeholder="请输入评语"
              />
            </div>
          </template>
          <a-empty v-else description="未配置评审规则" />
        </a-card>
      </template>

      <template #footer>
        <a-space>
          <a-button @click="reviewDrawerVisible = false">取消</a-button>
          <a-popconfirm
            title="确定要标记该作品为违规吗？"
            @confirm="handleMarkViolation"
          >
            <a-button danger>违规</a-button>
          </a-popconfirm>
          <a-button @click="handleResetScore">重置</a-button>
          <a-button type="primary" :loading="submitting" @click="handleSubmitScore">
            提交
          </a-button>
        </a-space>
      </template>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";
import { SearchOutlined } from "@ant-design/icons-vue";
import { useListRequest } from "@/composables/useListRequest";
import {
  submissionsApi,
  scoresApi,
  type HomeworkSubmission,
  type QuerySubmissionParams,
  type ClassTreeNode,
  type ReviewCriterion,
} from "@/api/homework";
import dayjs from "dayjs";

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

// 获取URL参数中的作业ID
const homeworkId = computed(() => {
  const id = route.query.homeworkId;
  return id ? Number(id) : undefined;
});

// 使用列表请求组合函数
const {
  loading,
  dataSource,
  pagination,
  searchParams,
  fetchList,
  resetSearch,
  search,
  handleTableChange,
} = useListRequest<HomeworkSubmission, QuerySubmissionParams>({
  requestFn: submissionsApi.getList,
  defaultSearchParams: {
    homeworkId: homeworkId.value,
  } as QuerySubmissionParams,
  defaultPageSize: 10,
  errorMessage: "获取提交记录失败",
});

// 班级树
const classTreeData = ref<ClassTreeNode[]>([]);
const selectedClassKeys = ref<(string | number)[]>([]);

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

// 班级选择
const handleClassSelect = (keys: (string | number)[], info: any) => {
  selectedClassKeys.value = keys;
  const node = info.node;
  if (node.type === "class") {
    searchParams.classIds = [node.classId];
    searchParams.gradeId = undefined;
  } else if (node.type === "grade") {
    searchParams.gradeId = node.gradeId;
    searchParams.classIds = undefined;
  }
  search();
};

// 行选择
const selectedRowKeys = ref<number[]>([]);
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: number[]) => {
    selectedRowKeys.value = keys;
  },
}));

// 表格列定义
const columns = [
  {
    title: "序号",
    key: "index",
    width: 60,
    customRender: ({ index }: { index: number }) => index + 1,
  },
  {
    title: "作品编号",
    key: "workNo",
    dataIndex: "workNo",
    width: 100,
  },
  {
    title: "作品名称",
    key: "workName",
    width: 150,
  },
  {
    title: "学生信息",
    key: "studentInfo",
    width: 120,
  },
  {
    title: "班级",
    key: "classInfo",
    width: 120,
  },
  {
    title: "评分",
    key: "totalScore",
    width: 80,
  },
  {
    title: "评审状态",
    key: "status",
    width: 100,
  },
  {
    title: "操作",
    key: "action",
    width: 100,
    fixed: "right" as const,
  },
];

// 状态显示
const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    pending: "default",
    reviewed: "success",
    rejected: "error",
  };
  return colors[status] || "default";
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    pending: "未评审",
    reviewed: "已评审",
    rejected: "已拒绝",
  };
  return texts[status] || status;
};

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

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

// 重置搜索
const handleReset = () => {
  selectedClassKeys.value = [];
  searchParams.classIds = undefined;
  searchParams.gradeId = undefined;
  resetSearch();
};

// 返回
const goBack = () => {
  router.push(`/${tenantCode}/homework`);
};

// 评审相关
const reviewDrawerVisible = ref(false);
const currentSubmission = ref<HomeworkSubmission | null>(null);
const reviewCriteria = ref<ReviewCriterion[]>([]);
const scoreValues = ref<number[]>([]);
const scoreComments = ref("");
const submitting = ref(false);

const handleReview = async (record: HomeworkSubmission) => {
  try {
    const detail = await submissionsApi.getDetail(record.id);
    currentSubmission.value = detail;

    // 获取评审规则中的评分标准
    const criteria = detail.homework?.reviewRule?.criteria;
    if (criteria) {
      reviewCriteria.value =
        typeof criteria === "string" ? JSON.parse(criteria) : criteria;
      scoreValues.value = reviewCriteria.value.map(() => 0);
    } else {
      reviewCriteria.value = [];
      scoreValues.value = [];
    }
    scoreComments.value = "";

    reviewDrawerVisible.value = true;
  } catch (error: any) {
    message.error(error?.response?.data?.message || "获取详情失败");
  }
};

const handleSubmitScore = async () => {
  if (!currentSubmission.value) return;

  if (reviewCriteria.value.length === 0) {
    message.warning("未配置评审规则");
    return;
  }

  const dimensionScores = reviewCriteria.value.map((criterion, index) => ({
    name: criterion.name,
    score: scoreValues.value[index] || 0,
    maxScore: criterion.maxScore,
  }));

  try {
    submitting.value = true;
    await scoresApi.create({
      submissionId: currentSubmission.value.id,
      dimensionScores,
      comments: scoreComments.value,
    });
    message.success("评分成功");
    reviewDrawerVisible.value = false;
    fetchList();
  } catch (error: any) {
    message.error(error?.response?.data?.message || "评分失败");
  } finally {
    submitting.value = false;
  }
};

const handleResetScore = async () => {
  if (!currentSubmission.value) return;

  try {
    await scoresApi.resetScore(currentSubmission.value.id);
    message.success("重置成功");
    scoreValues.value = reviewCriteria.value.map(() => 0);
    scoreComments.value = "";
    fetchList();
  } catch (error: any) {
    message.error(error?.response?.data?.message || "重置失败");
  }
};

const handleMarkViolation = async () => {
  if (!currentSubmission.value) return;

  try {
    await scoresApi.markViolation(currentSubmission.value.id);
    message.success("已标记为违规");
    reviewDrawerVisible.value = false;
    fetchList();
  } catch (error: any) {
    message.error(error?.response?.data?.message || "操作失败");
  }
};

onMounted(() => {
  loadClassTree();
  if (homeworkId.value) {
    searchParams.homeworkId = homeworkId.value;
  }
  fetchList();
});
</script>

<style scoped>
.page-content {
  display: flex;
  gap: 16px;
}

.left-panel {
  width: 250px;
  flex-shrink: 0;
}

.right-panel {
  flex: 1;
  min-width: 0;
}

.search-form {
  margin-bottom: 16px;
}

.text-gray {
  color: #999;
  font-size: 12px;
}

.mt-4 {
  margin-top: 16px;
}

.score-item {
  margin-bottom: 12px;
}

.score-label {
  margin-bottom: 4px;
  font-weight: 500;
}

.attachment-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.attachment-item:last-child {
  border-bottom: none;
}
</style>
