<template>
  <div>
    <div class="tw-bg-white tw-rounded-xl">
      <div class="tw-mt-4"></div>

      <a-collapse v-model:activeKey="activeKey">
        <a-collapse-panel
          v-for="(item, index) in data"
          :key="index"
          :header="item.courseName + '(' + item.courseCode + ')'"
        >
          <div class="tw-flex tw-justify-between tw-items-center tw-my-4">
            <h3 class="section-title">本科目成绩占初试总分权重</h3>
            <div class="tw-flex tw-gap-2">
              <a-button @click="openRangeConfigModal(item)">分段设置</a-button>
              <a-button @click="openModal1">说明</a-button>
            </div>
          </div>
          <table v-if="item.totalRangeConfig" class="custom-table">
            <tr>
              <th>初试总分分数段</th>
              <th>人数占比（%）</th>
              <th>初试总分平均分</th>
              <th>本科目成绩平均分</th>
              <th>本科目难度</th>
              <th>占总分权重（%）</th>
            </tr>
            <tr v-for="(item2, index2) in item.totalScoreRange" :key="index2">
              <td>
                {{
                  scoreTitle(item.totalScoreRangeTitle[index2]) || "全体考生"
                }}
              </td>
              <td v-number-to-percent>
                {{ item2.countRate }}
              </td>
              <td v-round-number>
                {{ item2.avgTotalScore }}
              </td>
              <td v-round-number>
                {{ item2.avgScore }}
              </td>
              <td v-round-number>
                {{ item2.difficulty }}
              </td>
              <td v-number-to-percent>
                {{ item2.scoreRate }}
              </td>
            </tr>
          </table>
          <div v-else>请先进行分段设置。</div>
        </a-collapse-panel>
      </a-collapse>
    </div>

    <CommonRangeConfig
      ref="rangeConfigRef"
      :projectId="projectId"
      :courseId="selectedCourseId"
      :rangeConfig="selectedRangeConfig"
      @updated="handleRangeConfigUpdate"
    />
  </div>
</template>

<script setup lang="ts">
// import { useMainStore } from "@/store";
import { onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import {
  getSasCourseList,
  setSasCourseTotalRangeConfig,
} from "@/api/allAnalysisPage";
import EventBus from "@/plugins/eventBus";
import { message } from "ant-design-vue";
import { RANGE_POINT_TYPE } from "@/constants/constants";
import { RangeConfig, SasCourse } from "@/types";

let activeKey = $ref(["0"]);
// const store = useMainStore();

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

let data = $ref<SasCourse[]>([]);
async function fetchData() {
  const res = await getSasCourseList({
    projectId,
    courseId: props.courseId,
  });
  // console.log(Object.keys(JSON.parse(res.data[0].scoreRange)));
  res.data = res.data.map((v) => {
    v.totalScoreRange = JSON.parse(
      <string>(<unknown>v.totalScoreRange) || "{}"
    );
    v.totalScoreRangeTitle = JSON.parse(
      <string>(<unknown>v.totalScoreRangeTitle) || "{}"
    );
    return v;
  });
  data = res.data;
}

onMounted(async () => {
  // rootOrgId = store.userInfo.rootOrgId;
  await fetchData();
});

watch(() => [props.courseId], fetchData);

let selectedRangeConfig = $ref([]);
let selectedCourseId = $ref(0);

let rangeConfigRef = $ref(null);

const openRangeConfigModal = (item: SasCourse) => {
  selectedCourseId = item.courseId;
  selectedRangeConfig = JSON.parse(item.totalRangeConfig || "0") || [
    {
      type: "ZERO",
      baseScore: 0,
      adjustScore: 0,
    },
  ];
  // @ts-ignore https://github.com/vuejs/vue-next/issues/4397
  // eslint-disable-next-line @typescript-eslint/no-unsafe-call
  rangeConfigRef.showModal();
};

async function handleRangeConfigUpdate(rangeConfig: RangeConfig) {
  await setSasCourseTotalRangeConfig({
    courseId: selectedCourseId,
    projectId: projectId,
    rangeConfig: JSON.stringify(rangeConfig),
  });
  void message.success({ content: "操作成功" });
}

function scoreTitle(rangeConfig: RangeConfig) {
  if (!rangeConfig) return false;
  if (rangeConfig.type === "ZERO") return "0-";

  return `${rangeConfig.baseScore + rangeConfig.adjustScore}(${
    RANGE_POINT_TYPE[rangeConfig.type]
  }${rangeConfig.adjustScore > 0 ? "+" : ""}${rangeConfig.adjustScore})-`;
}

function openModal1() {
  EventBus.emit("SHOW_SETTING", "DESCRIBE040");
}
</script>

<style scoped></style>
