<template>
  <div class="page_dialog">
    <el-dialog
      :title="title"
      center
      v-model="isShowDialog"
      @close="CloseDialog"
      width="830px"
    >
      <div class="dialog_center">
        <div class="center_header">
          <div class="header_left left_center">
            <span class="left_count">
              <template v-if="tableTitle">{{ tableTitle }}</template>
              总计：{{ studentList.length }}人
            </span>
          </div>
          <div class="header_right report_button">
            <el-button
              class="button_task_select"
              :loading="exportLoading"
              @click="ExportExcel"
            >
              <img
                v-if="!exportLoading"
                src="@/assets/icon/export_icon.webp"
                alt="导出Excel"
              />导出Excel
            </el-button>
          </div>
        </div>
        <div class="page_jg_20"></div>
        <div class="page_table table_row_42">
          <el-table
            :data="studentListData"
            border
            v-loading="tableLoading"
            element-loading-text="加载中..."
            :element-loading-spinner="loadingSvgIcon"
            element-loading-background="#ffffff"
          >
            <el-table-column
              type="index"
              align="center"
              label="序号"
              width="60"
            >
              <template #default="{ $index }">
                {{ (pageData.pageNum - 1) * pageData.pageSize + $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="schoolName"
              v-if="filterObject.examLevel == 1"
              label="学校"
              min-width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              align="center"
              prop="studentUserCode"
              label="学号"
              min-width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              align="center"
              prop="studentUserName"
              label="姓名"
              min-width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              align="center"
              prop="className"
              label="行政班"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ row.className || "-" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="teachClassName"
              align="center"
              label="教学班"
              v-if="filterObject.subjectGroupType === 0"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ row.teachClassName || "-" }}
              </template>
            </el-table-column>
            <el-table-column
              v-if="isAssign == 0"
              prop="score"
              align="center"
              label="得分"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              v-if="isAssign == 1"
              prop="score"
              align="center"
              label="原始分"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              v-if="isAssign == 1"
              prop="rateScore"
              align="center"
              label="赋分"
              show-overflow-tooltip
            ></el-table-column>
            <!-- 只有试卷分析显示 -->
            <el-table-column
              v-if="studentParam?.groupTitle"
              prop="questionScore"
              align="center"
              :label="`${studentParam.groupTitle}得分`"
              show-overflow-tooltip
            ></el-table-column>
          </el-table>
        </div>
        <div class="page_pagination" v-if="pageData.total > pageData.pageSize">
          <el-pagination
            @current-change="ChangePage"
            layout="prev, pager, next"
            :page-size="pageData.pageSize"
            :current-page="pageData.pageNum"
            :total="pageData.total"
          ></el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, getCurrentInstance } from "vue";
import {
  publicExport,
  horizontalDistributionStudentInfo,
  contrastStudentInfo,
  questionStudentInfo,
  questionGroupStudentInfo,
} from "@/api/analysis";
import {
  downloadExcel,
  GetExcelFileName,
  studentListStaticHeaderData,
} from "@/utils/exportExcel";
import { loadingSvgIcon } from "@/utils/common";
import { useAnalysisStore } from "@/store/analysis";
const analysisStore = useAnalysisStore();
const filterObject = computed(() => analysisStore.filterObject || {});
/** 考试名称计算属性 */
const getExamName = computed(() => {
  return analysisStore.analysisExamInfo.examName || "";
});
// ================= Props & Emits =================
const props = defineProps({
  title: { type: String, default: "" },
  showDialog: { type: Boolean, default: false },
  tableTitle: { type: String, default: "" },
  studentRegistrationCode: { type: Array, default: () => [] },
  examId: { type: [String, Number], default: "" },
  subjectCode: { type: [String, Number], default: "" },
  apiName: { type: String, default: "" },
  studentParam: { type: Object, default: () => ({}) },
});
const apiMap = {
  horizontalDistributionStudentInfo,
  contrastStudentInfo,
  questionStudentInfo,
  questionGroupStudentInfo,
  // 后续有其他接口也在这里添加
};
const emit = defineEmits(["CloseDialog"]);

// ================= 响应式数据 (Data) =================
const isShowDialog = ref(false);
const studentList = ref([]);
const pageData = reactive({
  pageSize: 10,
  pageNum: 1,
  total: 0,
});
const exportLoading = ref(false);
const isAssign = ref(0);
const tableLoading = ref(true);
const studentListData = computed(() => {
  const tableData = studentList.value;
  const { pageSize, pageNum } = pageData;
  const start = (pageNum - 1) * pageSize;
  const end = start + pageSize;
  return tableData.slice(start, end);
});

// ================= 监听器 (Watch) =================
watch(
  () => props.showDialog,
  (newVal) => {
    isShowDialog.value = newVal;
    studentList.value = [];
    pageData.total = 0;
    pageData.pageNum = 1;
    if (newVal) {
      tableLoading.value = true;
      GetStudentList();
    }
  },
);

// ================= 方法 (Methods) =================
const GetStudentList = () => {
  tableLoading.value = true;
  let params = {
    ...filterObject.value,
    pageParam: {
      pageNum: pageData.pageNum,
      pageSize: pageData.pageSize,
    },
    ...props.studentParam,
  };

  const apiFunc = apiMap[props.apiName];
  if (!apiFunc) {
    tableLoading.value = false;
    return;
  }

  apiFunc(params)
    .then((res) => {
      if (
        res.code == 200 &&
        res.data &&
        res.data.list &&
        res.data.list.length > 0
      ) {
        const { data } = res;
        isAssign.value = data?.rateScoreStatus ?? "";
        studentList.value = data?.list || [];
        pageData.total = data?.list?.length || 0;
      } else {
        studentList.value = [];
      }
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

const ExportExcel = () => {
  exportLoading.value = true;
  const staticHeaderData = studentListStaticHeaderData(
    filterObject.value.examLevel,
    isAssign.value,
    filterObject.value.subjectGroupType === 0,
  );

  if (props.studentParam?.groupTitle) {
    staticHeaderData.push({
      display: true,
      label: `${props.studentParam.groupTitle}得分`,
      prop: "questionScore",
    });
  }

  const title = props.title.replace(/\s/g, "");
  let dataList = [];

  studentList.value.forEach((row, index) => {
    const rowData = staticHeaderData.map((item) => {
      if (item.prop == "index") {
        return index + 1;
      } else if (item.prop == "score" || item.prop == "rateScore") {
        return row[item.prop] ?? "-";
      } else {
        return row[item.prop] || "-";
      }
    });
    dataList.push(rowData);
  });
  const examName = getExamName.value;
  let params = {
    fileName: GetExcelFileName(examName, filterObject.value, title),
    examName: examName,
    sheetName: title,
    staticHeaderData: staticHeaderData,
    dynamicsHeaderData: [],
    childHeaderData: [],
    dataList: dataList,
  };

  // 调用全局挂载的导出方法
  downloadExcel(publicExport, params).finally(() => {
    exportLoading.value = false;
  });
};

const CloseDialog = () => {
  emit("CloseDialog", false);
};

const ChangePage = (val) => {
  pageData.pageNum = val;
};
</script>

<style lang="scss" scoped>
//页面表格公共样式
:deep(.page_table) {
  width: 100%;

  // 表格悬浮效果覆盖
  .el-table__body tr:hover > td {
    background-color: #eaf0ff !important; // 蓝色系悬浮背景
  }

  //表格竖着的边框线样式
  th.el-table__cell {
    border-right: 1px solid #e9e9e9;
  }
  .el-table th.el-table__cell.is-leaf,
  .el-table td.el-table__cell {
    border-bottom: 1px solid #e9e9e9;
  }

  .el-table {
    min-height: 463px;
    border: 0px;
  }
}
//表格42行高
.table_row_42 {
  :deep(.el-table) {
    thead {
      color: #333 !important;
      font-weight: 500;
      font-size: 14px;
      height: 42px !important;
    }
    .el-table__cell {
      padding: 0;
      height: 42px !important;
    }
  }
}
:deep(.report_button) {
  display: flex;
  gap: 10px;
  .el-input-group__append {
    .el-button {
      width: 100%;
      justify-content: center;
    }
  }

  .el-icon-loading {
    color: #666;
  }
  .el-button {
    margin-left: 0px;
    height: 36px;
    line-height: 36px;
    padding: 0 10px;
    display: flex;
    align-items: center;

    span {
      // padding: 0px 10px;
      display: flex;
      align-items: center;
    }

    img {
      width: 16px;
      height: 16px;
      margin-right: 4px;
    }
  }

  .el-button--default {
    color: #666;
    font-weight: 400;
    &.is-disabled {
      color: #bbbbbb;
      border-color: #bbbbbb;
    }
  }
  .el-button--primary.is-plain:hover {
    color: #2e64fa;
    background-color: #c0d1fe;
    font-size: 14px;
  }

  //其他按钮可在下面追加
  //对标任务选择按钮
  .button_task_select {
    // 去掉按钮点击后的样式
    &:active,
    &:focus {
      outline: none; // 去掉点击后的轮廓
      box-shadow: none; // 去掉点击后的阴影
      background-color: inherit; // 保持背景颜色不变
      color: #666666; // 保持文字颜色不变
      border: 1px solid #dcdfe6;
    }
  }

  .button_task_select:hover {
    background-color: #f9f9f9;
    border: 1px solid #dcdfe6;
    color: #666;
  }
}
</style>
