<template>
  <div>
    <div class="tw-bg-white tw-p-5 tw-rounded-xl tw-mb-5">
      <a-input v-model:value="curProject.name" disabled style="width: 200px" />
      <span class="tw-mr-4"></span>
      <ProjectCourseSelect v-model:value="courseId" :projectId="projectId" />
      <span class="tw-mr-4"></span>
      <a-button class="query-btn" @click="search">查询</a-button>
      <span class="tw-mr-4"></span>
      <a-button @click="exportExcel">导出excel</a-button>
      <span class="tw-mr-4"></span>
      <!-- <a-button @click="exportReport">导出报告</a-button> -->

      <div class="tw-float-right tw-flex tw-gap-2">
        <!-- <a-button @click="goProjectPapers(projectId)"> 试卷列表 </a-button> -->
        <a-button @click="goBack">返回</a-button>
      </div>
    </div>

    <div class="tw-bg-white tw-p-5 tw-rounded-xl">
      <!-- <a-radio-group v-model:value="activeTab">
        <a-radio-button value="1">试卷特征量数</a-radio-button>
        <a-radio-button value="2">科目成绩（总分）频率分布</a-radio-button>
        <a-radio-button value="3">科目成绩占初试总分权重</a-radio-button>
      </a-radio-group> -->
      <div class="tw-mb-4"></div>
      <div v-if="activeTab === '1'">
        <a-table
          style="width: 100%; overflow-x: scroll"
          rowKey="id"
          :scroll="{ x: 1200 }"
          :columns="columns"
          :data-source="data"
          :pagination="{
            pageSize: pageSize,
            current: pageNo,
            total: totalElements,
            showTotal: () => ``,
          }"
          @change="tableChange"
        >
          <template #course="{ record }">
            <a>{{ `${record.courseName}(${record.courseCode})` }}</a>
          </template>
          <template #action="{ record }">
            <span>
              <!-- <a-button @click="openModal">说明</a-button> -->
              <a-button @click="goPaperAnalysis(record)">详情</a-button>
            </span>
          </template>
        </a-table>
      </div>

      <div v-if="activeTab === '2'"><ScoreRate :courseId="courseId" /></div>
      <div v-if="activeTab === '3'">
        <ScoreFirstTryRate :courseId="courseId" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useMainStore } from "@/store";
import { goBack, downloadFileURL } from "@/utils/utils";
import { onMounted } from "vue";
import { useRoute } from "vue-router";
import router from "@/router";
import { getSasPaperList } from "@/api/allAnalysisPage";
import { getProjectList } from "@/api/projectManagementPage";
// import EventBus from "@/plugins/eventBus";
import ScoreRate from "./ScoreRate.vue";
import ScoreFirstTryRate from "./ScoreFirstTryRate.vue";

import { SASPaper, Project } from "@/types";

type PaginationType = {
  current: number;
  pageSize: number;
};

type FilterType = {
  name: string;
  address: string;
};

type SorterType = {
  field: string;
  order: string;
};

const store = useMainStore();
store.currentLocation = "项目管理 / 项目列表 / 结果查询";

// let rootOrgId = $ref(undefined as unknown as number);
let courseId = $ref(undefined as unknown as number);
const route = useRoute();
const projectId = +route.params.projectId;
let curProject = $ref<Project>({} as Project);

let activeTab = $ref("1");

let data = $ref<SASPaper[]>([]);
let pageSize = $ref<number>(10);
let pageNo = $ref(1);
let totalElements = $ref(0);
let sortColName = $ref("");
let sortOrder = $ref("");

async function search() {
  pageNo = 1;
  await fetchData();
}

async function exportExcel() {
  let params: Record<string, any> = {
    projectId,
    courseId,
    pageNo,
    pageSize,
  };
  if (sortOrder && sortColName) {
    params = { ...params, sortColName, sortOrder };
  }
  await downloadFileURL("/api/ess/sasPaper/export", params);
}

interface fetchParamType {
  courseId?: number;
  projectId: number;
  pageNo?: number;
  pageSize?: number;
  sortColName?: string;
  sortOrder?: string;
}

async function fetchData() {
  let params: fetchParamType = {
    projectId,
    courseId,
    pageNo,
    pageSize,
  };
  if (sortOrder && sortColName) {
    params = { ...params, sortColName, sortOrder };
  }
  const res = await getSasPaperList(params);
  // console.log(res);
  data = res.data.content.map((v) => {
    v.avgScore = Math.round(v.avgScore * 100) / 100;
    v.stdev = Math.round(v.stdev * 100) / 100;
    v.coefficient = Math.round(v.coefficient * 100) / 100;
    v.reliability1 = Math.round(v.reliability1 * 100) / 100;
    v.reliability2 = Math.round(v.reliability2 * 100) / 100;
    v.difficulty = Math.round(v.difficulty * 100) / 100;
    return v;
  });
  pageNo = res.data.pageNo;
  pageSize = res.data.pageSize;
  totalElements = res.data.totalElements;
}

const columns = [
  {
    title: "科目",
    dataIndex: "course",
    slots: { customRender: "course" },
    width: 200,
    ellipses: true,
  },
  {
    title: "试卷类型",
    dataIndex: "paperType",
    width: 100,
  },
  {
    title: "起始计算分",
    dataIndex: "startScore",
    width: 100,
  },
  {
    title: "样本数",
    dataIndex: "totalCount",
    sorter: true,
    width: 100,
  },
  {
    title: "满分",
    dataIndex: "totalScore",
    width: 100,
  },
  {
    title: "最高分",
    dataIndex: "maxScore",
    width: 100,
  },
  {
    title: "最低分",
    dataIndex: "minScore",
    width: 100,
  },
  {
    title: "全距",
    dataIndex: "allRange",
    sorter: true,
    width: 100,
  },
  {
    title: "平均分",
    dataIndex: "avgScore",
    sorter: true,
    width: 100,
  },
  {
    title: "标准差",
    dataIndex: "stdev",
    sorter: true,
    width: 100,
  },
  {
    title: "差异系数",
    dataIndex: "coefficient",
    sorter: true,
    width: 100,
  },
  {
    title: "信度",
    dataIndex: "reliability1",
    sorter: true,
    width: 100,
  },
  // {
  //   title: "信度2",
  //   dataIndex: "reliability2",
  // },
  {
    title: "难度",
    dataIndex: "difficulty",
    sorter: true,
    width: 100,
  },
  {
    title: "操作",
    key: "action",
    slots: { customRender: "action" },
    width: 100,
    fixed: "right",
  },
];

onMounted(async () => {
  // rootOrgId = store.userInfo.rootOrgId;
  await getProject();
  await search();
  // if (sessionStorage.getItem("allAnalysisReload")) {
  //   activeTab = "2";
  //   sessionStorage.removeItem("allAnalysisReload");
  // }
});

async function goPaperAnalysis(record: SASPaper) {
  await router.push(`/project/${projectId}/paperAnalysis/${record.paperId}`);
}

async function tableChange(
  pagination: PaginationType,
  filters: FilterType[],
  sorter: SorterType
) {
  // console.log(pagination, sorter);

  pageNo = pagination.current;
  pageSize = pagination.pageSize;

  if (sorter.order) {
    sortColName = sorter.field;
    sortOrder = sorter.order.slice(0, -3).toUpperCase();
  } else {
    sortColName = "";
    sortOrder = "";
  }
  await fetchData();
}
// async function goProjectPapers(id: number) {
//   await router.push("/project/papers/" + id);
// }

// function openModal() {
//   EventBus.emit("SHOW_SETTING", "DESCRIBE010");
// }

// async function toReport(record: SASPaper) {
//   await router.push({
//     name: "PaperReport",
//     params: {
//       viewType: "view",
//       projectId: projectId,
//       paperId: record.paperId,
//     },
//   });
// }

async function getProject() {
  const res = await getProjectList({
    id: projectId,
    rootOrgId: -1,
    pageNo: 1,
    pageSize: 1,
  });
  curProject = res.data.content[0];
}
</script>
