<template>
  <el-dialog
    title=""
    class="page_full_dialog"
    v-model="dialogVisible"
    fullscreen
    height="100%"
  >
    <div class="header_container">
      <div class="header_back" @click="CloseDialog()">
        <i class="iconfont icon_return"></i>返回
      </div>
      <div class="header_title">批量查看</div>
    </div>
    <div class="container">
      <div class="container_title">
        <div class="title_left">
          <span class="span_item" v-if="groupTitle">{{ groupTitle }} /</span>
          <el-tooltip
            v-if="groupName"
            effect="dark"
            :disabled="groupName.length <= 10"
            :content="groupName"
            placement="top"
          >
            <span class="span_item"
              >{{
                groupName.length > 10
                  ? groupName.slice(0, 10) + "..."
                  : groupName
              }}
              /</span
            >
          </el-tooltip>
          <span class="span_item" v-if="questionTitle"
            >{{ questionTitle }} /</span
          >
          <span class="span_item" v-if="classTitle">{{ classTitle }}</span>
          <span class="score">得分：{{ optionTitle }}分</span>
          <div class="icon_zoom in" @click="ZoomIn">
            <img src="@/assets/icon/icon_zoom_in.webp" />
            <span>放大</span>
          </div>
          <div class="icon_zoom" @click="ZoomOut">
            <img src="@/assets/icon/icon_zoom_out.webp" />
            <span>缩小</span>
          </div>
        </div>
      </div>
      <div class="container_card">
        <div
          :class="['item_card', `row${rowCount}`]"
          v-for="(item, index) in studentList"
          :key="index"
          :style="{ width: `calc((100% - 54px) / ${rowCount})` }"
        >
          <div class="item_card_title">
            {{ item.studentName }}&nbsp;&nbsp;{{ item.className }}
          </div>
          <div class="item_card_img">
            <!-- 确保 StudentQuestionImg 也是 Vue 3 组件 -->
            <StudentQuestionImg
              :key="rowCount"
              :paperData="item"
              :isBatch="true"
            ></StudentQuestionImg>
            <div class="item_hover">
              <div class="show_view" @click="ShowQuestionCard(item, index)">
                <img src="@/assets/icon/pic_show_view.png" />
                <span>查看</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="preview_modal" v-if="showPreview"></div>
    <div class="preview_dialog" v-if="showPreview">
      <div class="close_btn" @click="ClosePreview">
        <el-icon class="el-icon-close"><Close /></el-icon>
      </div>
      <!-- 上一页 -->
      <div
        :class="['prev_btn', { disable: previewIndex <= 0 }]"
        @click.stop="PrevStudent"
      >
        <el-icon class="el-icon-arrow-left"><ArrowLeft /></el-icon>
      </div>
      <div class="preview_content">
        <StudentQuestionImg
          :paperData="previewData"
          :isBatch="true"
        ></StudentQuestionImg>
      </div>
      <!-- 下一页 -->
      <div
        :class="['next_btn', { disable: previewIndex === count }]"
        @click.stop="NextStudent"
      >
        <el-icon class="el-icon-arrow-right"><ArrowRight /></el-icon>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import StudentQuestionImg from "@/components/StudentQuestionImg.vue"; // 学生小题答题卡组件
import { findCardListNew } from "@/api/analysis";

// 定义 Props 接口
interface Props {
  showDialog: boolean;
  groupTitle?: string;
  groupName?: string;
  questionTitle?: string;
  classTitle?: string;
  optionTitle?: string;
  subjectId?: string; // 科目id
  questionId?: string; // 试题id
  platformNumbers?: string[]; // 学籍id
}

// 定义学生数据项接口 (根据实际 API 返回结构调整)
interface StudentItem {
  studentName: string;
  className: string;
  [key: string]: any; // 允许其他属性
}

// 定义 Props
const props = withDefaults(defineProps<Props>(), {
  showDialog: false,
  groupTitle: "",
  groupName: "",
  questionTitle: "",
  classTitle: "",
  optionTitle: "",
  subjectId: "",
  questionId: "",
  platformNumbers: () => [],
});

// 定义 Emits
const emit = defineEmits<{
  (e: "CloseDialog"): void;
}>();

// 响应式数据
const rowCount = ref<number>(4); // 默认一排放4个
const studentList = ref<StudentItem[]>([]);
const count = ref<number>(-1); // 初始化为-1，因为 length - 1，空列表时为-1
const showPreview = ref<boolean>(false);
const previewIndex = ref<number>(0);
const previewData = ref<StudentItem>({} as StudentItem);

// 内部使用的 dialog 可见性状态，用于 v-model
// 注意：如果父组件严格控制 showDialog，这里可能需要通过 watch 同步，或者直接使用 props.showDialog 并在 emit 中关闭
// 为了保持与原逻辑一致（watch showDialog），我们这里主要依赖 props.showDialog 触发加载
// 但 el-dialog 需要双向绑定。通常做法是：
// 1. 父组件传 v-model:showDialog
// 2. 这里使用 computed 或者 watch 同步
// 鉴于原代码是 :visible.sync，Vue3 + ElementPlus 推荐 v-model。
// 如果父组件还没改，这里可能需要一个局部变量并 watch props
const dialogVisible = ref(props.showDialog);

watch(
  () => props.showDialog,
  (val) => {
    dialogVisible.value = val;
    if (val) {
      resetState();
      FindCardList();
    }
  },
);

// 当内部关闭对话框时（例如点击遮罩层或ESC，如果允许），需要同步回父组件
// 但原代码只有 CloseDialog 按钮触发 emit，所以这里暂时不处理 el-dialog 自带的 close 事件，
// 除非需要在点击遮罩时关闭。如果需要，请添加 @close="handleDialogClose"

const resetState = () => {
  rowCount.value = 4;
  showPreview.value = false;
  previewIndex.value = 0;
  count.value = -1;
  previewData.value = {} as StudentItem;
  studentList.value = [];
};

// 方法
const FindCardList = () => {
  findCardListNew({
    examPaperId: props.subjectId,
    platformNumbers: props.platformNumbers,
    questionId: props.questionId,
  })
    .then((res) => {
      if (res.code == 200) {
        studentList.value = res?.data || [];
      } else {
        studentList.value = [];
      }
      count.value = studentList.value.length - 1;
    })
    .catch((err) => {
      console.error("Failed to fetch card list:", err);
      studentList.value = [];
      count.value = -1;
    });
};

// 显示答题卡
const ShowQuestionCard = (item: StudentItem, index: number) => {
  showPreview.value = true;
  previewIndex.value = index;
  previewData.value = item;
};

const ClosePreview = () => {
  showPreview.value = false;
};

const PrevStudent = () => {
  if (previewIndex.value <= 0) return;
  previewIndex.value--;
  previewData.value = studentList.value[previewIndex.value];
  console.log(previewIndex.value, "left");
};

const NextStudent = () => {
  if (previewIndex.value === count.value) return;
  previewIndex.value++;
  previewData.value = studentList.value[previewIndex.value];
  console.log(previewIndex.value, count.value, "right");
};

// 放大
const ZoomIn = () => {
  if (rowCount.value == 1) return;
  rowCount.value--;
};

// 缩小
const ZoomOut = () => {
  if (rowCount.value == 4) return;
  rowCount.value++;
};

// 关闭弹窗
const CloseDialog = () => {
  emit("CloseDialog");
};
</script>

<style scoped lang="scss">
.container {
  height: calc(100vh - 65px);
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  overflow-y: auto;
  background-color: #fff;

  .container_title {
    font-weight: 400;
    font-size: 16px;
    color: #999999;
    text-align: left;
    line-height: 22px;
    display: flex;
    justify-content: space-between;

    .title_left {
      display: flex;
      align-items: center;

      .span_item {
        font-weight: 400;
        font-size: 16px;
        color: #999999;
        padding-right: 5px;
      }

      .score {
        margin-left: 40px;
        font-weight: 400;
        font-size: 16px;
        color: #666666;
      }

      .icon_zoom {
        display: inline-flex;
        align-items: center;
        margin-left: 20px;
        &.in {
          margin-left: 40px;
        }
        cursor: pointer;
        img {
          width: 20px;
          height: 20px;
        }
        span {
          font-weight: 400;
          font-size: 14px;
          color: #333333;
          margin-left: 4px;
        }
      }
    }
  }

  .container_card {
    display: flex;
    flex-wrap: wrap;
    gap: 0 18px;

    .item_card {
      width: calc((100% - 54px) / 4);
      margin-top: 7px;

      &.row1 {
        .item_card_img {
          height: 320px;
        }
      }
      &.row2 {
        .item_card_img {
          height: 220px;
        }
      }
      &.row3 {
        .item_card_img {
          height: 180px;
        }
      }
      &.row4 {
        .item_card_img {
          height: 160px;
        }
      }

      .item_card_title {
        width: 100%;
        margin: 13px 0 8px;
        font-weight: 400;
        font-size: 14px;
        color: #666666;
      }

      .item_card_img {
        width: 100%;
        height: 160px;
        background: #f0f4f8;
        border-radius: 8px;
        border: 1px solid #ebeef5;
        cursor: pointer;
        position: relative;
        overflow: hidden;

        &:hover {
          .item_hover {
            display: flex;
          }
        }

        .item_hover {
          display: none;
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
          background: rgba(0, 0, 0, 0.4);
          border-radius: 8px;
          align-items: center;
          justify-content: center;

          .show_view {
            width: 68px;
            height: 36px;
            background-color: #ffffff;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;

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

            span {
              font-weight: 400;
              font-size: 14px;
              color: #606266;
            }
          }
        }
      }
    }
  }
}

.preview_modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0.5;
  background: #000000;
  z-index: 2000; /* 确保层级正确 */
}

.preview_dialog {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 80px 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2001; /* 确保层级高于 modal */

  .preview_content {
    height: 100%;
    flex: 1;
    overflow: auto;
    background: #fff;
  }

  .close_btn {
    position: absolute;
    top: 30px;
    right: 70px;
    width: 48px;
    height: 48px;
    background: rgba(0, 0, 0, 0.4);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    flex-shrink: 0;

    .el-icon-close {
      color: #ffffff;
      font-size: 23px;
    }
  }

  .prev_btn {
    width: 48px;
    height: 48px;
    background: rgba(0, 0, 0, 0.4);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 40px;
    cursor: pointer;
    flex-shrink: 0;

    &.disable {
      cursor: default;
      background: rgba(0, 0, 0, 0.3);

      .el-icon-arrow-left {
        color: #c0c4cc;
      }
    }

    .el-icon-arrow-left {
      color: #ffffff;
      font-size: 23px;
    }
  }

  .next_btn {
    width: 48px;
    height: 48px;
    background: rgba(0, 0, 0, 0.4);
    border-radius: 50%;
    margin-left: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    &.disable {
      cursor: default;
      background: rgba(0, 0, 0, 0.3);

      .el-icon-arrow-right {
        color: #c0c4cc;
      }
    }

    .el-icon-arrow-right {
      color: #ffffff;
      font-size: 23px;
    }
  }
}
</style>
