<template>
  <div class="app-container">
    <Filter
      v-model="filterData"
      :config="filterConfig"
      :actions="[]"
      style="margin-bottom: 16px"
      @change="handleFilterChange"
    />
    <div class="box">
      <div class="label">得分能力</div>
      <div class="content">
        <div class="chart" ref="chartRef"></div>
        <div class="info">
          <div class="info-item">
            <div class="info-item-label">得分能力综合评估</div>
            <div class="info-item-value">
              {{ levelToText[stability.level] }}
            </div>
          </div>
          <div class="info-item">
            <div class="info-item-label">得分能力稳定性</div>
            <div class="info-item-value">
              {{ stabilityToText[stability.stability] }}
            </div>
          </div>
        </div>
        <el-alert
          title="注：得分能力是通过均分、得分率等数据综合计算得出，反映学生对该科目知识掌握程度和答题能力。"
          type="info"
        />
      </div>
    </div>
    <div class="box">
      <div class="label">知识点</div>
      <div class="content">
        <div class="radio-box">
          <el-radio-group v-model="active" @change="getList">
            <el-radio-button
              v-for="(item, index) in type"
              :key="index"
              :label="item"
              :value="index"
            />
          </el-radio-group>
        </div>
        <Table
          :xbTable="xbTable"
          @tablePageChange="handleTablePageChange"
          :autoScroll="false"
        >
          <template #scoreRate="{ row }">
            <span
              :style="{
                color: getScoreColor(row?.scoreRate),
              }"
            >
              {{ row?.scoreRate / 100 }}%
            </span>
          </template>
        </Table>
      </div>
    </div>
    <div class="box">
      <div id="error-label" class="label">错题</div>
      <div class="content error-box">
        <Filter
          v-model="errorFilterData"
          :config="errorFilterConfig"
          :actions="[]"
          style="margin-bottom: 16px"
          @change="handleErrorFilterChange"
        />
        <div
          class="questions-item"
          v-for="(q, qIdx) in errorTitleData"
          :key="q.id"
        >
          <table border="1">
            <thead>
              <tr>
                <th v-if="q.subjectTitleVo.answerStatistics?.children?.length">
                  题号
                </th>
                <th>满分人数</th>
                <th>非满分人数</th>
                <th>得分率</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td style="color: #67c23a">
                  {{ q.fullScoreNum }}
                </td>
                <td style="color: #f56c6c">
                  {{ q.nonFullScoreNum }}
                </td>
                <td
                  :style="{
                    color: getScoreColor(q.scoreRate),
                  }"
                >
                  {{ q.scoreRate / 100 }}%
                </td>
              </tr>
              <template
                v-if="q.subjectTitleVo.answerStatistics?.children?.length"
              >
                <tr v-for="i in q.subjectTitleVo.answerStatistics.children">
                  <td>{{ q.subjectTitleVo.qNo }}-{{ i.titleNo }}</td>
                  <td style="color: #67c23a">
                    {{ i.fullScoreStuNum }}
                  </td>
                  <td style="color: #f56c6c">
                    {{ i.totalStuNum - i.fullScoreStuNum }}
                  </td>
                  <td :style="{ color: getScoreColor(i.scoreRate) }">
                    {{ i.scoreRate / 100 }}%
                  </td>
                </tr>
              </template>
            </tbody>
          </table>
          <Question
            :data="q.subjectTitleVo"
            :index="q.subjectTitleVo.qNo"
            :showMore="false"
          />
        </div>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="errorPage.pageNum"
            v-model:page-size="errorPage.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="errorPage.total"
            @size-change="handleErrorSizeChange"
            @current-change="handleErrorCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import Filter from "@/components/Filter/index.vue";
import Table from "@/components/Table/index.vue";
import { useRoute } from "vue-router";
import { onMounted, reactive } from "vue";
import Question from "@/components/Question";
import {
  getSubjectList,
  getScoringAbility,
  getJobKnowledge,
  getErrorTitle,
} from "@/api";
import { getScoreColor, formatTitleToPaper } from "@/utils";
import * as echarts from "echarts";

const props = defineProps({
  filter: {
    type: Object,
    default: () => ({}),
  },
});

const type = {
  0: "薄弱",
  1: "合格",
  2: "良好",
  3: "优秀",
};
const active = ref("0");

const filterData = ref({}); //过滤
const filterConfig = computed(() => [
  {
    comName: "el-select",
    label: "学科",
    prop: "subjectId",
    clearable: false,
    showAll: false,
    options: subjectList.value,
    selectConfig: {
      label: "name",
      value: "id",
    },
  },
]);
function handleFilterChange(e) {
  errorFilterData.value.time = [];
  init();
}

// 查询学科
const subjectList = ref([]);
async function initSubjectList() {
  const res = await getSubjectList();
  subjectList.value = res;
  filterData.value.subjectId = res[0]?.id || "";
}

// 得分能力图表
const chartRef = ref();
const chart = ref();
const levelToText = {
  0: "优秀",
  1: "良好",
  2: "中等",
  3: "弱",
};
const stabilityToText = {
  0: "稳定",
  1: "相对波动",
};
const stability = reactive({
  level: "",
  stability: "",
});
async function getScoringAbilityData() {
  const { data: res } = await getScoringAbility({
    classId: props.filter.classId,
    subjectId: filterData.value.subjectId,
    sourceType: 1,
  });
  if (res.jobScoringAbilityDataVoList) {
    chart.value.setOption({
      xAxis: {
        data: res.jobScoringAbilityDataVoList.map((i) => i.submitDate),
      },
      series: [
        {
          data: res.jobScoringAbilityDataVoList.map((i) => i.scoreRate / 100),
        },
      ],
    });
  }
  stability.level = res.level;
  stability.stability = res.stability;
}

// 知识点模块
const xbTable = ref({
  loading: false,
  columns: [
    { prop: "knowledgeName", label: "知识点" },
    { slot: "scoreRate", label: "平均得分率" },
    {
      prop: "titleNum",
      label: "出题次数",
    },
  ],
  tableData: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 30,
  },
});
/** 查询列表 */
function getList() {
  xbTable.value.loading = true;
  getJobKnowledge({
    ...xbTable.value.pagination,
    type: active.value,
    classId: props.filter.classId,
    subjectId: filterData.value.subjectId,
    sourceType: 1,
  })
    .then((res) => {
      xbTable.value.tableData = res.rows;
      xbTable.value.pagination.total = res.total;
    })
    .finally(() => {
      xbTable.value.loading = false;
    });
}

// 表格分页
function handleTablePageChange(val) {
  xbTable.value.pagination.pageSize = val.limit;
  xbTable.value.pagination.pageNum = val.page;
  getList();
}

// 错题模块
const errorFilterData = ref({}); //过滤
const errorFilterConfig = computed(() => [
  {
    comName: "el-date-picker",
    label: "时间",
    type: "datetimerange",
    prop: "time",
    startPlaceholder: "开始时间",
    endPlaceholder: "结束时间",
    format: "YYYY-MM-DD HH:mm",
    valueFormat: "YYYY-MM-DD HH:mm",
    defaultTime: [
      new Date(2000, 1, 1, 0, 0, 0),
      new Date(2000, 1, 1, 23, 59, 59),
    ],
  },
]);
function handleErrorFilterChange(e) {
  getErrorTitleData();
}
const errorPage = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 10,
});
const errorTitleData = ref();
async function getErrorTitleData() {
  const res = await getErrorTitle({
    ...errorPage,
    startTime: errorFilterData.value.time?.[0],
    endTime: errorFilterData.value.time?.[1],
    classId: props.filter.classId,
    subjectId: filterData.value.subjectId,
  });

  res.rows.forEach((i) => {
    i.subjectTitleVo = formatTitleToPaper([i.subjectTitleVo])[0];
  });
  errorTitleData.value = res.rows;
  errorPage.total = res.total;
}
function handleErrorSizeChange(e) {
  errorPage.pageSize = e;
  getErrorTitleData();
  window.scrollTo({
    top: document.getElementById("error-label").offsetTop,
    behavior: "smooth",
  });
}
function handleErrorCurrentChange(e) {
  errorPage.pageNum = e;
  getErrorTitleData();
  window.scrollTo({
    top: document.getElementById("error-label").offsetTop,
    behavior: "smooth",
  });
}

function init() {
  getList();
  getScoringAbilityData();
  getErrorTitleData();
}

onMounted(async () => {
  await initSubjectList();
  init();
  chart.value = echarts.init(chartRef.value);
  chart.value.setOption({
    xAxis: {
      type: "category",
      data: [],
    },
    yAxis: {
      type: "value",
      min: 0,
      max: 100,
      interval: 20,
    },
    series: [
      {
        data: [],
        type: "line",
        smooth: true,
        label: {
          show: true,
          position: "outside",
          formatter: "{c}",
        },
        markLine: {
          symbol: "none",
          animation: false,
          data: [
            {
              yAxis: 85,
              name: "优秀",
              lineStyle: { color: "green", width: 1, opacity: 0.5 },
            },
            {
              yAxis: 70,
              name: "良好",
              lineStyle: { color: "orange", width: 1, opacity: 0.5 },
            },
            {
              yAxis: 60,
              name: "一般",
              lineStyle: { color: "red", width: 1, opacity: 0.5 },
            },
          ],
        },
      },
    ],
  });
});

defineExpose({
  init,
});
</script>
<style scoped lang="scss">
.app-container {
  .box {
    background: #fff;
    font-size: 16px;
    margin-bottom: 16px;
    .label {
      padding: 0 16px;
      margin-bottom: 16px;
      border-left: 4px solid #409eff;
    }
    .content {
      .chart {
        height: 400px;
      }

      .info {
        display: flex;
        align-items: center;
        justify-content: space-around;
        .info-item {
          padding: 16px;
          .info-item-label {
            font-size: 14px;
            color: #999;
            margin-bottom: 16px;
          }
          .info-item-value {
            text-align: center;
            font-size: 24px;
            color: #303133;
          }
        }
      }

      .radio-box {
        text-align: center;
        margin-bottom: 16px;
      }

      .questions-item {
        border: 1px solid transparent;
        background: #fff;
        margin-bottom: 40px;
        padding: 16px;
        position: relative;

        :deep(.questions-item-content) {
          margin-top: 0;
        }

        table {
          width: 50%;
          margin-bottom: 32px;
          border-collapse: collapse;
          text-align: center;
          tr {
            height: 35px;
          }
        }
      }
    }

    .error-box {
      :deep(.pagination-container) {
        position: relative;
        .el-pagination {
          right: 50%;
          transform: translateX(50%);
        }
      }
    }
  }
}
</style>
