<template>
  <div>
    <div class="tw-bg-white tw-rounded-xl">
      <div class="tw-mt-4"></div>
      分数间隔
      <a-select v-model:value="scoreGap">
        <a-select-option :value="1">1</a-select-option>
        <a-select-option :value="5">5</a-select-option>
        <a-select-option :value="10">10</a-select-option>
        <a-select-option :value="20">20</a-select-option>
        <a-select-option :value="50">50</a-select-option>
      </a-select>
      <div class="tw-mt-4"></div>

      <a-collapse :activeKey="courses[0]?.id">
        <a-collapse-panel
          v-for="course in courses"
          :key="course.id"
          :header="course.courseName + '(' + course.courseCode + ')'"
        >
          <div class="tw-flex tw-justify-between tw-items-center tw-my-4">
            <h3 class="section-title">等距（{{ scoreGap }}分）分组频数分布</h3>
            <!-- <a-button @click="openModal1">说明</a-button> -->
          </div>
          <div class="tw-flex tw-gap-4" style="max-height: 500px">
            <div class="tw-overflow-auto">
              <table class="custom-table" style="width: 400px">
                <tr>
                  <th>分数段</th>
                  <th>频数</th>
                  <th>频率（%）</th>
                  <th>累计频数</th>
                  <th>累计频数（%）</th>
                </tr>
                <tr
                  v-for="(seg, index2) in course.segements"
                  :key="index2 + scoreGap * 100000"
                >
                  <td>
                    <span v-if="index2 < course.segements.length - 1"
                      >{{ scoreGap * index2 }}-{{
                        scoreGap * (index2 + 1)
                      }}</span
                    >
                    <span v-else>{{ seg[0] }}</span>
                  </td>
                  <td>{{ seg[1] }}</td>
                  <td v-number-to-percent>{{ seg[2] }}%</td>
                  <td>{{ seg[3] }}</td>
                  <td v-number-to-percent>{{ seg[4] }}%</td>
                </tr>
              </table>
            </div>

            <div style="flex-grow: 1; min-height: 260px">
              <v-chart
                class="chart"
                :option="segementsLine(course)"
                :autoresize="true"
              />
            </div>
          </div>

          <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(course)">
                分段设置
              </a-button>
              <!-- <a-button @click="openModal2">说明</a-button> -->
            </div>
          </div>
          <div
            v-if="course.rangeConfig"
            class="tw-flex tw-gap-4"
            style="max-height: 500px"
          >
            <div class="tw-overflow-auto">
              <table class="custom-table" style="width: 400px">
                <tr>
                  <th>分数段</th>
                  <th>频数</th>
                  <th>频率（%）</th>
                  <th>累计频数</th>
                  <th>累计频数（%）</th>
                </tr>
                <tr
                  v-for="(seg, index3) in course.rangeSegements"
                  :key="index3"
                >
                  <td>{{ seg[0] }}</td>
                  <td>{{ seg[1] }}</td>
                  <td v-number-to-percent>{{ seg[2] }}%</td>
                  <td>{{ seg[3] }}</td>
                  <td v-number-to-percent>{{ seg[4] }}%</td>
                </tr>
              </table>
            </div>

            <div style="flex-grow: 1; min-height: 260px">
              <v-chart
                class="chart"
                :option="rangeSegementsLine(course)"
                :autoresize="true"
              />
            </div>
          </div>
          <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,
  setSasCourseRangeConfig,
} from "@/api/allAnalysisPage";
// import EventBus from "@/plugins/eventBus";
import { message } from "ant-design-vue";
import { RANGE_POINT_TYPE } from "@/constants/constants";
import { EChartsOption } from "echarts";
import CommonRangeConfig from "@/components/CommonRangeConfig.vue";
import { RangeConfig, SasCourse } from "@/types";

// 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 courses = $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.scoreRange = Object.values(
      // eslint-disable-next-line
      JSON.parse(<string>(<unknown>v.scoreRange) || "{}")
    );
    return v;
  });
  res.data = res.data.map((v) => {
    v.rangeConfig = JSON.parse(<string>(<unknown>v.rangeConfig) || "0") || [
      {
        type: "ZERO",
        baseScore: 0,
        adjustScore: 0,
      },
    ];
    return v;
  });
  res.data = res.data.map((v) => {
    let acc = 0;
    if (Array.isArray(v.scoreRange))
      v.scoreRangeAcc = v.scoreRange.map((_v, i, a) => {
        acc += a[i];
        return acc;
      });
    v.scoreRangeTotal = acc;
    return v;
  });
  // console.log(res.data);
  courses = res.data;
}

onMounted(async () => {
  // rootOrgId = store.userInfo.rootOrgId;
  await fetchData();
});
watch(() => [props.courseId], fetchData);

let scoreGap = $ref(10);

watch(
  () => [scoreGap, courses],
  () => {
    for (const course of courses) {
      course.segements = [];
      const validSeg = Math.round(course.totalScore / scoreGap);
      for (let score = 0; score < validSeg; score++) {
        const row = [];
        row[0] = score * scoreGap;
        let nextScore = score + 1 > validSeg ? course.totalScore : score + 1;
        // row[1] =
        //   course.scoreRangeAcc[nextScore * scoreGap - 1] -
        //   course.scoreRangeAcc[score * scoreGap];
        row[1] = course.scoreRange
          .slice(row[0], nextScore * scoreGap)
          .reduce((p, c) => p + c, 0);
        row[2] = row[1] / course.scoreRangeAcc[course.totalScore];
        const endGap =
          nextScore * scoreGap - 1 >= course.totalScore
            ? course.totalScore
            : nextScore * scoreGap - 1;
        row[3] = course.scoreRangeAcc[endGap];
        row[4] = row[3] / course.scoreRangeAcc[course.totalScore];
        course.segements.push(row);
      }
      if (validSeg * scoreGap === course.totalScore) {
        course.segements.push([
          course.totalScore,
          course.scoreRange[course.totalScore],
          course.scoreRange[course.totalScore] /
            course.scoreRangeAcc[course.totalScore],
          course.scoreRangeAcc[course.totalScore],
          1,
        ]);
      }

      course.rangeSegements = [];
      for (let i = 0; i < course.rangeConfig.length; i++) {
        const range = course.rangeConfig[i]!;
        const nextRange =
          i === course.rangeConfig.length - 1
            ? { baseScore: course.totalScore, adjustScore: 0 }
            : course.rangeConfig[i + 1];
        const row = [];
        row[0] = scoreTitle(range);
        row[1] =
          course.scoreRange
            .slice(
              range.baseScore + range.adjustScore,
              nextRange.baseScore + nextRange.adjustScore
            )
            .reduce((p, c) => p + c, 0) || 0;
        row[2] = row[1] / course.scoreRangeTotal;
        row[3] =
          course.scoreRangeAcc[
            nextRange.baseScore + nextRange.adjustScore - 1
          ] || 0;
        if (
          nextRange.baseScore + nextRange.adjustScore >=
          course.scoreRangeAcc.length
        ) {
          row[3] = course.scoreRangeAcc[course.scoreRangeAcc.length - 1];
        }
        row[4] = row[3] / course.scoreRangeTotal;

        course.rangeSegements.push(row);
      }
      // console.log(course);
    }
  },
  {
    immediate: true,
  }
);

// let scores = [];
// const scoreComputed = computed(() => {
//   const s = {};
//   // data[0].scoreRange =
//   // scores.push()
// });

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

let rangeConfigRef = $ref<InstanceType<typeof CommonRangeConfig>>();

const openRangeConfigModal = (item: SasCourse) => {
  selectedCourseId = item.courseId;
  selectedRangeConfig = JSON.parse(JSON.stringify(item.rangeConfig));
  // @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 setSasCourseRangeConfig({
    courseId: selectedCourseId,
    projectId: projectId,
    rangeConfig: JSON.stringify(rangeConfig),
  });
  void message.success({ content: "操作成功" });
  sessionStorage.setItem("allAnalysisReload", "2");
  window.location.reload();
}

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", "DESCRIBE020");
// }

// function openModal2() {
//   EventBus.emit("SHOW_SETTING", "DESCRIBE030");
// }

function segementsLine(course: SasCourse) {
  // console.log(course);
  return {
    title: {
      text: "频数",
      left: "left",
    },
    xAxis: {
      type: "category",
      data: course.segements.map((v) => v[0]),
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: course.segements.map((v) => v[1]),
        type: "line",
        smooth: true,
      },
    ],
  } as EChartsOption;
}

function rangeSegementsLine(course: SasCourse) {
  // console.log(course);
  return {
    title: {
      text: "频数",
      left: "left",
    },
    xAxis: {
      type: "category",
      data: course.rangeSegements.map((v) => v[0]),
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: course.rangeSegements.map((v) => v[1]),
        type: "line",
        smooth: true,
      },
    ],
  } as EChartsOption;
}
</script>
