<template>
  <div class="markmain pull-left scroll" id="student_paper">
    <el-tabs :active-name="activeName">
      <el-tab-pane label="考生答卷" name="first">
        <div v-if="this.examType != 'OFFLINE'">
          <div id="main-source" v-if="this.studentPaper.id != ''">
            <div
              class="paper"
              v-if="!this.markSign"
              v-html="this.studentPaper.studentSubjectiveHtml"
            ></div>
            <div class="paper" v-show="this.markSign">
              <div class="fixed marktitle signTitle">
                <el-button-group class="itemTitle">
                  <el-button type="info" size="small">
                    <span class>当前题</span>
                  </el-button>
                  <el-button type="info" size="small">
                    <span class>{{ itemTitle }}</span>
                  </el-button>
                </el-button-group>
                <!--
                  <el-button type="primary" size="small" @click="saveMarkSign">保存轨迹</el-button>
                -->
                <el-button type="danger" size="small" @click="delMarkSign"
                  >清除轨迹</el-button
                >
                <el-button type="danger" size="small" @click="delAllMarkSign"
                  >清除全部轨迹</el-button
                >
              </div>
              <div>
                <canvas id="canvas" width="800px" height="800px"></canvas>
              </div>
            </div>
          </div>
        </div>
        <div v-if="this.examType == 'OFFLINE'">
          <div v-if="this.studentPaper.id != ''">
            <div v-html="getPdfUrl()" style="float: left;"></div>
            <div
              v-if="
                this.studentPaper.studentSubjectiveHtml &&
                  this.studentPaper.studentSubjectiveHtml != '' &&
                  this.studentPaper.studentSubjectiveHtml.indexOf('.pdf') > -1
              "
              style="float: right;margin-right: 20px;"
              class="no-print"
            >
              <el-button size="small" type="success" @click="pdfDown();"
                >下载</el-button
              >
            </div>
          </div>
        </div>
      </el-tab-pane>
      <template v-if="this.examType == 'OFFLINE'">
        <el-tab-pane label="标答" name="second">
          <div id="answer-source" v-if="this.examType == 'OFFLINE'">
            <div style="float: right;margin-right: 20px;" class="no-print">
              <el-button size="small" type="success" @click="printAnswer();"
                >打印</el-button
              >
            </div>
            <div
              class="paper"
              id="answer-content"
              v-html="this.answerHtml"
            ></div>
          </div>
        </el-tab-pane>
      </template>
    </el-tabs>
  </div>
</template>
<script>
import { Drawing } from "../canvas/mark_sign";
import { EVENTHUB } from "../constants/constants";
import printJS from "print-js";
export default {
  data() {
    return {
      activeName: "first",
      drawing: {},
      tmpSignScores: this.signScores,
      tmpMarkSign: this.markSign
    };
  },
  props: [
    "paperMarkSign",
    "studentPaper",
    "markSign",
    "signOption",
    "signScores",
    "signItem",
    "examType",
    "answerHtml"
  ],
  methods: {
    getPdfUrl() {
      var url = this.studentPaper.studentSubjectiveHtml;
      var content = "";
      if (url) {
        if (url != "" && url.indexOf(".pdf") > -1) {
          content =
            "<embed src='" + url + "'  width='800px' height='800px'></embed>";
        }
        if (url != "" && url.indexOf(".zip") > -1) {
          content = "<a href='" + url + "'>下载</a>";
        }
      }
      return content;
    },
    createMarkDraw() {
      console.log("create");
      var drawing = {};
      this.signOption.data = this.studentPaper.studentSubjectiveHtml;
      drawing = new Drawing("canvas", this.signOption);
      this.drawing = drawing;
    },
    intMarkDraw() {
      console.log("init");
      if (this.markSign) {
        this.clearScoreLoc();
        this.clearScores();
        this.setMarkDrawHtml();
        this.setSignLocation();
      }
    },
    setMarkDrawHtml() {
      this.drawing.setHtml(this.studentPaper.studentSubjectiveHtml);
    },
    saveMarkSign() {
      if (this.drawing.canvas && this.signItem.id) {
        localStorage.removeItem(this.paperKey);
        localStorage.setItem(this.paperKey, JSON.stringify(this.paperSigns));
        this.$notify({
          message: "轨迹保存成功",
          type: "success"
        });
      } else {
        this.$notify({
          message: "请选择给分步骤",
          type: "error"
        });
      }
    },
    setSignLocation() {
      let signStorage = localStorage.getItem(this.paperKey);
      console.log("signStorage", signStorage);
      if (typeof signStorage == "string") {
        let paperSigns = JSON.parse(signStorage);
        if (
          this.drawing.scoreLoc.length == 0 ||
          paperSigns.length > this.drawing.scoreLoc.length
        ) {
          this.drawing.setLocation(paperSigns, "localStorage");
        } else {
          this.drawing.setLocation(this.drawing.scoreLoc, "cache");
        }
      } else {
        this.drawing.setLocation(this.drawing.scoreLoc, "cache");
      }
      this.setSignItemId();
    },
    setSignItemId() {
      var signItem = Object.assign({}, this.signItem);
      this.drawing.setItemId(signItem.id);
    },
    setSignScores() {
      let signStorage = localStorage.getItem(this.paperKey);
      if (typeof signStorage == "string") {
        let paperSigns = JSON.parse(signStorage);
        if (paperSigns.length > 0) {
          for (let [index, paperSign] of paperSigns.entries()) {
            console.log("score index:", index);
            if (paperSign.itemId == this.signItem.id) {
              this.tmpSignScores.push(paperSign.score);
            }
          }
        }
      }
      console.log("signScores", this.signScores);
    },
    delMarkSign() {
      if (this.drawing.canvas) {
        this.removeItemSign();
        this.clearScores();
        this.drawing.ResetDrawAll();
        this.setSignLocation();
        this.$notify({
          message: "轨迹清除成功",
          type: "success"
        });
      }
    },
    removeItemSign() {
      let signStorage = localStorage.getItem(this.paperKey);
      if (typeof signStorage == "string") {
        let paperSigns = JSON.parse(signStorage);
        this.removeLS(paperSigns);
        this.removeCache();
      } else {
        this.removeCache();
      }
    },
    removeLS(paperSigns) {
      for (let i = paperSigns.length - 1; i >= 0; i--) {
        if (paperSigns[i].itemId == this.signItem.id) {
          paperSigns.splice(i, 1);
        }
      }
      if (paperSigns.length > 0) {
        localStorage.removeItem(this.paperKey);
        localStorage.setItem(this.paperKey, JSON.stringify(paperSigns));
      } else {
        localStorage.removeItem(this.paperKey);
        this.clearScoreLoc();
      }
    },
    removeCache() {
      for (let i = this.drawing.scoreLoc.length - 1; i >= 0; i--) {
        if (this.drawing.scoreLoc[i].itemId == this.signItem.id) {
          this.drawing.scoreLoc.splice(i, 1);
        }
      }
    },
    delAllMarkSign() {
      if (this.drawing.canvas) {
        localStorage.removeItem(this.paperKey);
        this.clearScores();
        this.clearScoreLoc();
        this.drawing.ResetDrawAll();
        this.$notify({
          message: "轨迹全部清除成功",
          type: "success"
        });
      }
    },
    changeMarkSign() {
      if (this.signItem) {
        this.drawing.ResetDrawAll();
        console.log("paperSign", localStorage.getItem(this.paperKey));
        this.setSignLocation();
        this.setSignScores();
      }
    },
    //清除分数
    clearScores() {
      this.tmpSignScores.splice(0, this.tmpSignScores.length);
      this.$emit("clearScores");
    },
    //清除分数坐标
    clearScoreLoc() {
      this.drawing.clearScoreLoc();
    },
    //打印
    printAnswer() {
      printJS({ printable: "answer-content", type: "html" });
    },
    pdfDown() {
      var url = this.studentPaper.studentSubjectiveHtml;
      if (url != "undefined" && url != "") {
        url = new URL(url);
        url = url.pathname;
        url = decodeURIComponent(url);
        let xhr = new XMLHttpRequest();
        xhr.responseType = "blob";
        xhr.open("GET", url, true);
        xhr.onload = function() {
          if (this.status === 200) {
            let blob = this.response;
            let reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onload = function(e) {
              let a = document.createElement("a");
              a.download = url.substr(url.lastIndexOf("/") + 1);
              a.href = e.target.result;
              document.body.appendChild(a);
              a.click();
              a.parentNode.removeChild(a);
            };
          }
        };
        xhr.send();
      } else {
        this.$notify({
          message: "离线url为空",
          type: "warning"
        });
      }
    }
  },
  computed: {
    itemTitle() {
      if (!this.markSign) return "无";
      var title = "无";
      if (this.signItem.id) {
        title =
          Number.parseInt(this.signItem.mainNumber) +
          1 +
          "(" +
          this.signItem.orders +
          ")";
      }
      return title;
    },
    itemKey() {
      if (!this.markSign) return "";
      return this.studentPaper.id + "-" + this.signItem.id;
    },
    paperKey() {
      if (!this.markSign) return "";
      return this.studentPaper.id;
    },
    paperSigns() {
      if (!this.markSign) return [];
      var paperSigns = [];
      if (this.drawing.scoreLoc.length > 0) {
        for (let scoreLoc of this.drawing.scoreLoc) {
          paperSigns.push({
            loc: scoreLoc.loc,
            score: scoreLoc.score,
            itemId: scoreLoc.itemId
          });
        }
      }
      return paperSigns;
    }
  },
  watch: {
    signItem(val) {
      if (this.markSign) {
        console.log("signItem", val);
        this.changeMarkSign();
      }
    },
    studentPaper() {
      if (this.markSign) {
        this.intMarkDraw();
      }
    },
    tmpSignScores(val) {
      this.$emit("changeSignScores", val);
    },
    signScores(val) {
      this.tmpSignScores = val;
    },
    markSign() {
      this.intMarkDraw();
    },
    paperSigns(val) {
      this.$emit("changePaperSign", val);
    }
  },
  updated() {},
  mounted() {
    //this.createMarkDraw();
  },
  created() {
    EVENTHUB.$on("positionDiv", function(id) {
      let o = document.getElementById("student_paper");
      o.scrollTop = 0;
      var height = 0;
      let outObject = document.getElementById("anchor-" + id);
      if (outObject) {
        if (outObject.currentStyle) {
          height = parseInt(outObject.currentStyle["marginTop"]);
        } else {
          height = parseInt(
            document.defaultView.getComputedStyle(outObject, null)["marginTop"]
          );
        }
        var y = document.getElementById("anchor-" + id).offsetTop - height / 2;
        o.scrollTop = y - 5;
      }
    });
  }
};
</script>
<style scoped>
.markmain {
  width: 74%;
}
.scroll {
  overflow: auto;
  height: 600px;
}
.marktitle {
  margin-right: 20px;
  margin-bottom: 20px;
}
.signTitle {
  margin-left: 35%;
}
.itemTitle {
  margin-right: 10px;
}
.titlefont {
  font-size: 15px;
}
li {
  list-style-type: none;
}
.markbutton {
  width: 40px;
  height: 40px;
}
img {
  width: 100%;
  height: 100%;
}
.paper {
  width: 90%;
  min-height: 600px;
}
.fixed {
  position: fixed;
}
</style>
