<script setup>
import { computed, reactive } from "vue";
import SignImage from "./SignImage.vue";
import { getJobStuInfo, fileUpload, submitManualAnswer } from "@/api";
import {
  NumToChineseNumerals,
  formatTitleToPaper,
  getScoreColor,
} from "@/utils";
import { Select, CloseBold } from "@element-plus/icons-vue";
import Question from "@/components/Question";
import { cloneDeep } from "lodash-es";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  jobId: {
    type: String,
    default: "",
  },
  stuId: {
    type: String,
    default: "",
  },
  scoreRate: {
    type: Number,
    default: 0,
  },
  status: {
    type: Number,
    default: 0,
  },
});
const emits = defineEmits(["update:modelValue", "onRefresh"]);

const isShow = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emits("update:modelValue", val);
  },
});

const jobData = ref({});
const qData = ref([]); // 试题详情
const showQData = ref([]); // 显示的试题详情
const isOnlyError = ref(false); // 只看错题

function clear() {
  jobData.value = {};
  qData.value = [];
  showQData.value = [];
  isOnlyError.value = false;
}

async function handleOpen() {
  clear();
  const res = await getJobStuInfo({
    jobId: props.jobId,
    stuId: props.stuId,
  });
  jobData.value = {
    ...res.data,
    contentDetails: [],
  };

  res.data.contentDetails.forEach((c) => {
    c.titleList.forEach((i) => {
      i.formatTitle = formatTitleToPaper([i])[0];
      if (i.autoMarkFlag === 0) return;
      if (!i.children) return;
      if (!i.answer) return;
      const answer = i.answer?.split(",");
      const submitAnswer = i.submitAnswer?.split(",") || [];
      i.childrenTitle = answer.map((a, idx) => ({
        titleNo: `${i.titleNo}-${idx + 1}`,
        submitAnswer: submitAnswer[idx],
        answer: a,
        markFlag:
          i.children[idx]?.markFlag === undefined
            ? a === submitAnswer[idx]
            : i.children[idx]?.markFlag,
      }));
    });
  });
  qData.value = res.data.contentDetails;
  showQData.value = qData.value;
}

function onOnlyErrorChange(val) {
  if (!val) {
    showQData.value = qData.value;
    return;
  }
  showQData.value = cloneDeep(qData.value)
    .map((i) => {
      i.titleList = i.titleList.filter((j) => j.markFlag === 0);
      return i;
    })
    .filter((i) => i.titleList.length > 0);
}

const signImageDia = reactive({
  show: false,
  src: "",
  data: {},
});

// 批改/查看图片
function handleEditPic(src, data) {
  signImageDia.show = true;
  signImageDia.src = src;
  signImageDia.data = data;
}
// ----- 本地处理
// 图片批注结果
// async function onSave(file, info) {
//   const reader = new FileReader();
//   reader.onload = (e) => {
//     const imageUrl = e.target.result;
//     if (!info.judge) {
//       info.judge = [file];
//       info.judgeUrl = [imageUrl];
//     } else {
//       info.judge.push(file);
//       info.judgeUrl.push(imageUrl);
//     }
//   };
//   reader.readAsDataURL(file);
// }
// // 删除图片批注
// async function handleDel(idx, info) {
//   info.judge = info.judge.filter((i, index) => index !== idx);
//   info.judgeUrl = info.judgeUrl.filter((i, index) => index !== idx);
// }
// const loading = ref(false);
// async function handleSubmit() {
//   loading.value = true;
//   try {
//     const arr = [];
//     for (let i = 0; i < qData.value.length; i++) {
//       if (![1, 2, 3].includes(qData.value[i].titleList[0].titleChannelType)) {
//         // 手动批改
//         const titleList = qData.value[i].titleList;
//         for (let j = 0; j < titleList.length; j++) {
//           const jTem = titleList[j];
//           const obj = {
//             answerScore: jTem.answerScore,
//             jobStuId: jTem.jobStuId,
//             id: jTem.jobStuTittleId,
//             markAnswer: jTem.markAnswer,
//           };
//           if (jTem.judge && jTem.judge.length) {
//             const res = await Promise.allSettled(
//               jTem.judge.map((s) => fileUpload({ file: s }))
//             );
//             obj.markAnswerPic = res
//               .filter((i) => i.status === "fulfilled")
//               .map((i) => i.value.data.url)
//               .join(",");
//           }
//           arr.push(obj);
//         }
//       }
//     }
//     await submitManualAnswer(arr);
//     isShow.value = false;
//     emits("onRefresh");
//   } catch (err) {
//     console.log(err);
//   } finally {
//     loading.value = false;
//   }
// }

// --- 远程处理
// 图片批注结果
async function onSave(file, info) {
  info.markLoading = true;
  try {
    const res = await fileUpload({ file });
    info.markAnswerPic = `${info.markAnswerPic || ""}${
      info.markAnswerPic ? "," : ""
    }${res.data.url}`;
  } finally {
    info.markLoading = false;
  }
}
// 删除图片批注
async function handleDel(idx, info) {
  info.markAnswerPic = info.markAnswerPic
    .split(",")
    .filter((i, index) => index !== idx)
    .join(",");
}
const loading = ref(false);
async function handleSubmit() {
  loading.value = true;
  try {
    const arr = [];
    for (let i = 0; i < qData.value.length; i++) {
      if (qData.value[i].titleList[0].autoMarkFlag === 0) {
        // 手动批改
        const titleList = qData.value[i].titleList;
        for (let j = 0; j < titleList.length; j++) {
          const jTem = titleList[j];
          const obj = {
            answerScore: jTem.answerScore || 0,
            jobStuId: jTem.jobStuId,
            id: jTem.jobStuTittleId,
            markAnswer: jTem.markAnswer,
            markAnswerPic: jTem.markAnswerPic,
          };
          arr.push(obj);
        }
      }
    }
    await submitManualAnswer(arr);
    isShow.value = false;
    emits("onRefresh");
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
}
</script>
<template>
  <el-dialog
    v-model="isShow"
    style="width: 800px"
    :close-on-press-escape="false"
    @open="handleOpen"
  >
    <template #header>
      <div class="header">
        {{ status === 3 ? "查看" : "批改" }}
        <el-checkbox
          v-if="status === 3"
          v-model="isOnlyError"
          @change="onOnlyErrorChange"
          >只看错题</el-checkbox
        >
      </div>
    </template>
    <div class="info space-between">
      <div class="item">班级：{{ jobData?.className || "-" }}</div>
      <div class="item">姓名：{{ jobData.stuName || "-" }}</div>
      <div class="item">
        分数：
        <span :style="{ color: getScoreColor(scoreRate) }">
          {{ jobData.markScore || 0 }} / {{ scoreRate / 100 }} %
        </span>
      </div>
      <div class="item">答题时长：{{ jobData.costTimeInfo || "-" }}</div>
    </div>
    <div class="structure">
      <div class="main">
        <div v-for="(i, idx) in showQData" class="structure-item">
          <h2 class="structure-item-title">
            {{ NumToChineseNumerals[idx] }}、{{ i.contentName }}
          </h2>
          <template v-for="(item, idx) in i.titleList" :key="idx">
            <!-- 客观题 -->
            <template v-if="item.autoMarkFlag === 1">
              <Question
                :data="item.formatTitle"
                :index="item.formatTitle.qNo"
                :showMore="false"
              />
              <table border="1" class="objective-ques">
                <thead>
                  <tr>
                    <th v-if="item.childrenTitle">题号</th>
                    <th>学生答案</th>
                    <th>参考答案</th>
                    <th>系统批改结果</th>
                    <th v-if="!item.childrenTitle">得分</th>
                  </tr>
                </thead>
                <tbody>
                  <template v-if="item.childrenTitle">
                    <tr>
                      <td>{{ item.titleNo }}</td>
                      <td></td>
                      <td></td>
                      <td>得分：{{ item.answerScore }}</td>
                    </tr>
                    <tr v-for="c in item.childrenTitle" :key="c.titleNo">
                      <td>{{ c.titleNo }}</td>
                      <td>{{ c.submitAnswer }}</td>
                      <td>{{ c.answer }}</td>
                      <td>
                        <el-icon v-if="c.markFlag" color="#67C23A"
                          ><Select
                        /></el-icon>
                        <el-icon v-else color="#F56C6C"><CloseBold /></el-icon>
                      </td>
                    </tr>
                  </template>
                  <tr v-else>
                    <td>{{ item.submitAnswer }}</td>
                    <td v-html="item.answer" style="max-width: 200px"></td>
                    <td>
                      <el-icon v-if="item.markFlag" color="#67C23A"
                        ><Select
                      /></el-icon>
                      <el-icon v-else color="#F56C6C"><CloseBold /></el-icon>
                    </td>
                    <td>{{ item.answerScore }}</td>
                  </tr>
                </tbody>
              </table>
            </template>
            <!-- 主观题 -->
            <div v-else class="subjective-ques">
              <div class="subjective-ques-item">
                <Question
                  :data="item.formatTitle"
                  :index="item.formatTitle.qNo"
                  :showMore="false"
                />
                <el-input-number
                  v-model="item.answerScore"
                  :min="0"
                  :max="item.score"
                  value-on-clear="min"
                  controls-position="right"
                  :step="0.5"
                  step-strictly
                  style="margin-right: 16px"
                />
                总分：{{ item.score }}分
                <div class="pic-list">
                  <div>学生答案：</div>
                  <div v-if="item.submitAnswer" class="pic-box">
                    {{ item.submitAnswer }}
                  </div>
                  <div v-if="item.submitAnswerPic" class="pic-box">
                    <div
                      v-for="pic in item.submitAnswerPic.split(',')"
                      class="pic"
                    >
                      <el-image
                        style="width: 100px; height: 100px"
                        :src="pic"
                        fit="cover"
                        @click="handleEditPic(pic, item)"
                      />
                    </div>
                  </div>
                </div>
                <!-- 本地缓存 -->
                <!-- <div v-if="item.judge && item.judge.length" class="pic-list">
                <div>老师评价：</div>
                <div class="pic-box">
                  <div v-for="(pic, idx) in item.judgeUrl" class="pic">
                    <el-image
                      style="width: 100px; height: 100px"
                      :src="pic"
                      fit="cover"
                      :preview-src-list="item.judgeUrl"
                    />
                    <el-icon
                      color="#F56C6C"
                      size="28"
                      @click.stop="handleDel(idx, item)"
                    >
                      <Delete />
                    </el-icon>
                  </div>
                </div>
              </div> -->
                <!-- 服务处理 -->
                <div class="pic-list">
                  <div style="width: 100%">
                    <div>老师批改：</div>
                    <el-input
                      v-model="item.markAnswer"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入"
                      style="margin: 16px 0"
                    />
                  </div>
                  <div v-loading="item.markLoading" class="pic-box">
                    <template v-if="item.markAnswerPic">
                      <div
                        v-for="(pic, idx) in item.markAnswerPic.split(',')"
                        class="pic"
                      >
                        <el-image
                          style="width: 100px; height: 100px"
                          :src="pic"
                          fit="cover"
                          :preview-src-list="item.markAnswerPic.split(',')"
                        />
                        <el-icon
                          color="#F56C6C"
                          size="28"
                          @click.stop="handleDel(idx, item)"
                        >
                          <Delete />
                        </el-icon>
                      </div>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="btns">
      <el-button
        v-if="jobData.status !== 3"
        :loading="loading"
        type="primary"
        @click="handleSubmit"
        >批改完毕</el-button
      >
      <el-button @click="isShow = false"
        >{{ jobData.status === 3 ? "关闭" : "取消" }}
      </el-button>
    </div>
  </el-dialog>
  <SignImage
    v-model="signImageDia.show"
    :src="signImageDia.src"
    :data="signImageDia.data"
    @onSave="onSave"
  ></SignImage>
</template>
<style scoped lang="scss">
.info {
  font-weight: bold;
  font-size: 16px;
  .item {
    margin: 0 36px 12px 0;
  }
}
.structure {
  &-item {
    table {
      width: calc(100% - 24px);
      margin: 0 12px;
    }
  }

  .subjective-ques {
    &-item {
      .questions-item {
        margin: 16px 0;
      }
    }
  }
}
.space-between {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  .item {
    flex-shrink: 0;
  }
}
.pic-list {
  display: flex;
  flex-wrap: wrap;
  padding: 18px;
  .pic-box {
    margin-left: 24px;
    flex: 1;
    // display: flex;
    justify-content: center;
    // flex-wrap: wrap;
    display: grid;
    grid-template-columns: repeat(auto-fill, 100px);
    grid-template-rows: 100px;
    gap: 16px;
  }
  .pic {
    width: 100%;
    height: 100%;
    cursor: pointer;
    position: relative;
    img {
      width: 100%;
      height: 100%;
      object-fit: fill;
    }
    &:hover {
      .el-icon {
        opacity: 1;
        visibility: visible;
      }
    }
    .el-icon {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: #fcd3d3;
      border-radius: 50%;
      padding: 4px;
      opacity: 0;
      visibility: hidden;
      transition: all 0.3s ease-in-out;
    }
  }
}
table {
  border-collapse: collapse;
  text-align: center;
  width: 100%;
  tr {
    height: 35px;
  }
}
h3 {
  color: #000;
}
.btns {
  text-align: center;
  margin-top: 24px;
}

.header {
  font-size: 20px;
  .el-checkbox {
    margin-left: 20px;
  }
}
</style>
