<template>
  <div>
    <div class="tw-bg-white tw-p-5 tw-rounded-xl tw-mb-5">
      <ProjectsSelect
        v-if="rootOrgId"
        v-model:value="contrastProjectId"
        :rootOrgId="rootOrgId"
        placeholder="请选择参照项目"
      />
      <span class="tw-mr-4"></span>
      <ProjectsSelect
        v-if="rootOrgId"
        v-model:value="projectIds"
        :rootOrgId="rootOrgId"
        placeholder="请选择分析项目"
        style="width: 400px !important"
      />
      <span class="tw-mr-4"></span>
      <a-button class="query-btn" @click="clickSearch">对比</a-button>
    </div>

    <div class="tw-bg-white tw-p-5 tw-rounded-xl">
      <a-table
        rowKey="id"
        :customRow="customRow"
        :columns="columns"
        :data-source="data"
        :scroll="{ x: 1200, y: 800 }"
        :pagination="{
          hideOnSinglePage: true,
          pageSize: pageSize,
          current: pageNo,
          total: totalElements,
          showTotal: () => ``,
          onChange: (pageNoChanged, pageSizeChanged) => {
            pageNo = pageNoChanged;
            pageSize = pageSizeChanged;
          },
        }"
      >
        <template #courseName="{ record }">
          <a-tooltip placement="topLeft">
            <template #title
              >{{ record.courseName }}({{ record.courseCode }})</template
            >
            {{ record.courseName }}({{ record.courseCode }})
          </a-tooltip>
          <!-- <a>{{ record.courseName }}({{ record.courseCode }})</a> -->
        </template>
        <template #projectName="{ record }">
          <a-tooltip placement="topLeft">
            <template #title>{{ record.projectName }}</template>
            {{ record.projectName }}
          </a-tooltip>
          <!-- <a>{{ record.courseName }}({{ record.courseCode }})</a> -->
        </template>
        <!-- <template #action="{ record }">
          <span>
            <a-button
              v-if="record.projectId !== contrastProjectId"
              @click="goCompareDetail(record.courseCode)"
              >查看详情</a-button
            >
          </span>
        </template> -->
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getProjectCompareList } from "@/api/projectCompareManagementPage";
import router from "@/router";
import { useMainStore } from "@/store";
import type { SASPaper } from "@/types";
import { message, Button } from "ant-design-vue";
import { watch, onMounted, toRaw, h } from "vue";

const store = useMainStore();
store.currentLocation = "项目管理 / 关联分析";

let rootOrgId = $ref(undefined as unknown as number);

let projectIds: number[] = $ref([]); //$ref([4, 5]);
let contrastProjectId = $ref(undefined as unknown as number); //$ref(4);

let data = $shallowRef<SASPaper[]>([]);
let pageSize = $ref(1000);
let pageNo = $ref(1);
let totalElements = $ref(0);

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

watch(() => [pageNo, pageSize], fetchData);
watch(
  () => [projectIds, contrastProjectId],
  () => (data = [])
);

async function fetchData() {
  if (projectIds.length === 0) {
    void message.warn("请选择对比项目");
    return;
  }
  if (typeof contrastProjectId !== "number") {
    void message.warn("请选择参照项目");
    return;
  }
  const res = await getProjectCompareList({
    projectIds,
    contrastProjectId,
    pageSize,
    pageNo,
  });
  // console.log(res);
  let resData = filterData(res.data.content, projectIds.length + 1);
  console.log(resData);

  data = resData.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;
}

function filterData(data: SASPaper[], groupCount: number) {
  let curCourseId: number | null = null;
  let curCourseList: SASPaper[] = [];
  let nData = [];

  data.forEach((item) => {
    if (item.courseId !== curCourseId) {
      curCourseId = item.courseId;
      if (curCourseList.length > 1 && curCourseList.length <= groupCount) {
        nData.push(...curCourseList);
      }
      curCourseList = [];
    }
    curCourseList.push(item);
  });

  if (curCourseList.length > 1 && curCourseList.length < groupCount) {
    nData.push(...curCourseList);
  }
  return nData;
}

function cellRender(prop: keyof SASPaper) {
  return ({ record, index }: { record: SASPaper; index: number }) => {
    let getClass = "";
    if (record.projectId !== contrastProjectId) {
      const op =
        data[index - 1]?.projectId === contrastProjectId
          ? data[index - 1]
          : data[index - 2];
      if (op) {
        if (op[prop] > record[prop]) {
          getClass = "arrow-down-indicator";
        } else if (op[prop] === record[prop]) {
          getClass = "arrow-equal-indicator";
        } else {
          getClass = "arrow-up-indicator";
        }
      }
    }
    return {
      children:
        record.projectId === contrastProjectId
          ? h("span", record[prop])
          : [
              h("span", record[prop]),
              h("span", { class: getClass, innerText: "" }),
            ],
    };
  };
}

const columns = [
  {
    title: "科目",
    dataIndex: "courseName",
    slots: { customRender: "courseName" },
    fixed: "left",
    width: 140,
    ellipsis: true,
  },
  {
    title: "项目名称",
    dataIndex: "projectName",
    width: 150,
    ellipsis: true,
    slots: { customRender: "projectName" },
  },
  {
    title: "试卷名称",
    dataIndex: "paperName",
    width: 110,
  },
  {
    title: "满分",
    dataIndex: "totalScore",
  },
  {
    title: "最高分",
    // dataIndex: "maxScore",
    customRender: cellRender("maxScore"),
  },
  {
    title: "最低分",
    // dataIndex: "minScore",
    customRender: cellRender("minScore"),
  },
  {
    title: "全距",
    // dataIndex: "allRange",
    customRender: cellRender("allRange"),
  },
  {
    title: "平均分",
    // dataIndex: "avgScore",
    customRender: cellRender("allRange"),
  },
  {
    title: "标准差",
    // dataIndex: "stdev",
    customRender: cellRender("stdev"),
  },
  {
    title: "差异系数",
    // dataIndex: "coefficient",
    customRender: cellRender("coefficient"),
  },
  {
    title: "信度",
    // dataIndex: "reliability1",
    customRender: cellRender("reliability1"),
  },
  // {
  //   title: "信度2",
  //   // dataIndex: "reliability2",
  //   customRender: cellRender("reliability2"),
  // },
  {
    title: "难度",
    // dataIndex: "difficulty",
    customRender: cellRender("difficulty"),
  },
  {
    title: "操作",
    key: "action",
    fixed: "right",
    width: "140px",
    // dataIndex: "courseName",
    // slots: { customRender: "action" },
    // slots: {
    customRender: ({ record, index }: { record: SASPaper; index: number }) => {
      // console.log(text, index);
      // These two are merged into above cell
      // console.log(index, record.projectId);
      let rowSpan = 0;
      if (record.projectId === contrastProjectId) {
        rowSpan = 1;
        if (index < data.length - 1) {
          if (data[index + 1]?.projectId !== contrastProjectId) {
            rowSpan = 2;
          }
        }
        if (index < data.length - 2) {
          if (data[index + 2]?.projectId !== contrastProjectId) {
            rowSpan = 3;
          }
        }
      }
      // console.log(rowSpan);
      return {
        children: h(
          Button,
          {
            onClick: () => {
              if (rowSpan > 1)
                goCompareDetail(record.courseCode).catch(() => false);
            },
          },
          () => "查看详情"
        ),
        props: {
          rowSpan,
        },
      };
    },
    // },
  },
];

function customRow(record: SASPaper) {
  // console.log(args);
  let backgroundColor = "white";
  if (record.projectId === contrastProjectId) {
    backgroundColor = "lightgrey";
  }
  return {
    style: { backgroundColor },
  };
}

onMounted(() => {
  rootOrgId = store.userInfo.rootOrgId;
});

async function goCompareDetail(courseCode: string) {
  if (
    !(await router.push({
      path: "/project/projectCompareDetail",
      // state: { courseCode, contrastProjectId, projectIds },
    }))
  ) {
    history.replaceState(
      {
        ...history.state,
        ...{
          courseCode: toRaw(courseCode),
          contrastProjectId: toRaw(contrastProjectId),
          projectIds: toRaw(projectIds),
        },
      },
      ""
    );
  }
}
</script>

<style>
.arrow-up-indicator::before {
  content: "↑";
  color: green;
  font-weight: 700;
}
.arrow-down-indicator::before {
  content: "↓";
  color: red;
  font-weight: 700;
}
.arrow-equal-indicator::before {
  content: "↔";
  color: black;
  font-weight: 700;
}
</style>
