<template>
  <div class="review-rules-page">
    <a-card class="mb-4">
      <template #title>评审规则</template>
      <template #extra>
        <a-button
          v-permission="'homework:update'"
          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="searchName"
          placeholder="请输入规则名称"
          allow-clear
          style="width: 200px"
        />
      </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="dataList"
      :loading="loading"
      :pagination="pagination"
      :row-selection="rowSelection"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'name'">
          {{ record.name }}
        </template>
        <template v-else-if="column.key === 'description'">
          {{ record.description || "-" }}
        </template>
        <template v-else-if="column.key === 'homeworks'">
          <template v-if="record.homeworks?.length">
            <a-tag v-for="hw in record.homeworks" :key="hw.id">
              {{ hw.name }}
            </a-tag>
          </template>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button
              v-permission="'homework:update'"
              type="link"
              size="small"
              @click="handleEdit(record)"
            >
              编辑
            </a-button>
            <a-popconfirm
              v-permission="'homework:update'"
              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"
    >
      <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="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入规则描述"
            :rows="3"
          />
        </a-form-item>
        <a-form-item label="评分标准" name="criteria">
          <div class="criteria-list">
            <div
              v-for="(criterion, index) in formData.criteria"
              :key="index"
              class="criterion-item"
            >
              <a-input
                v-model:value="criterion.name"
                placeholder="维度名称"
                style="width: 150px"
              />
              <a-input-number
                v-model:value="criterion.maxScore"
                placeholder="满分"
                :min="1"
                style="width: 100px"
              />
              <a-input
                v-model:value="criterion.description"
                placeholder="描述（可选）"
                style="flex: 1"
              />
              <a-button
                type="text"
                danger
                @click="removeCriterion(index)"
              >
                <template #icon><DeleteOutlined /></template>
              </a-button>
            </div>
            <a-button type="dashed" block @click="addCriterion">
              <template #icon><PlusOutlined /></template>
              添加评分维度
            </a-button>
          </div>
        </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-space>
      </template>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from "vue";
import { message } from "ant-design-vue";
import type { FormInstance } from "ant-design-vue";
import {
  PlusOutlined,
  SearchOutlined,
  DeleteOutlined,
} from "@ant-design/icons-vue";
import {
  reviewRulesApi,
  type HomeworkReviewRule,
  type ReviewCriterion,
} from "@/api/homework";

// 列表数据
const loading = ref(false);
const dataList = ref<HomeworkReviewRule[]>([]);
const total = ref(0);
const searchName = ref("");
const searchParams = reactive({
  page: 1,
  pageSize: 10,
});

// 分页
const pagination = computed(() => ({
  current: searchParams.page,
  pageSize: searchParams.pageSize,
  total: total.value,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (t: number) => `共 ${t} 条记录`,
}));

// 行选择
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: "name",
    dataIndex: "name",
    width: 200,
  },
  {
    title: "规则描述",
    key: "description",
    width: 300,
  },
  {
    title: "关联作业",
    key: "homeworks",
    width: 250,
  },
  {
    title: "操作",
    key: "action",
    width: 150,
    fixed: "right" as const,
  },
];

// 加载数据
const fetchList = async () => {
  loading.value = true;
  try {
    const res = await reviewRulesApi.getList({
      name: searchName.value || undefined,
      page: searchParams.page,
      pageSize: searchParams.pageSize,
    });
    dataList.value = res.list;
    total.value = res.total;
  } catch (error: any) {
    message.error(error?.response?.data?.message || "获取列表失败");
  } finally {
    loading.value = false;
  }
};

// 表格变化
const handleTableChange = (pag: any) => {
  searchParams.page = pag.current;
  searchParams.pageSize = pag.pageSize;
  fetchList();
};

// 搜索
const handleSearch = () => {
  searchParams.page = 1;
  fetchList();
};

// 重置
const handleReset = () => {
  searchName.value = "";
  searchParams.page = 1;
  fetchList();
};

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

const formData = reactive<{
  name: string;
  description: string;
  criteria: ReviewCriterion[];
}>({
  name: "",
  description: "",
  criteria: [],
});

const formRules = {
  name: [{ required: true, message: "请输入规则名称" }],
  criteria: [
    {
      validator: async () => {
        if (formData.criteria.length === 0) {
          return Promise.reject("请至少添加一个评分维度");
        }
        for (const c of formData.criteria) {
          if (!c.name || !c.maxScore) {
            return Promise.reject("请完善评分维度信息");
          }
        }
        return Promise.resolve();
      },
    },
  ],
};

// 新增
const handleAdd = () => {
  editingId.value = null;
  formData.name = "";
  formData.description = "";
  formData.criteria = [{ name: "", maxScore: 100, description: "" }];
  drawerVisible.value = true;
};

// 编辑
const handleEdit = (record: HomeworkReviewRule) => {
  editingId.value = record.id;
  formData.name = record.name;
  formData.description = record.description || "";
  const criteria = record.criteria;
  formData.criteria =
    typeof criteria === "string" ? JSON.parse(criteria) : criteria || [];
  drawerVisible.value = true;
};

// 添加评分维度
const addCriterion = () => {
  formData.criteria.push({ name: "", maxScore: 100, description: "" });
};

// 移除评分维度
const removeCriterion = (index: number) => {
  formData.criteria.splice(index, 1);
};

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

    const submitData = {
      name: formData.name,
      description: formData.description,
      criteria: formData.criteria,
    };

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

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

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

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

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

.criteria-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.criterion-item {
  display: flex;
  gap: 8px;
  align-items: center;
}
</style>
