<style scoped>
.scoreboard {
  width: 25%;
  border-left: 3px solid #20a0ff;
  min-height: 600px;
}
.scroll {
  overflow: auto;
  height: 300px;
}
.itemScroll {
  overflow: auto;
  height: 150px;
}
.scoreScroll {
  overflow: auto;
  height: 100px;
}
.scoretitle {
  margin-right: 20px;
  margin-bottom: 20px;
}
li {
  list-style-type: none;
}
.scorebutton {
  width: 40px;
  height: 40px;
}
.titlebutton {
  width: 50px;
  height: 56px;
}
.actionbutton {
  width: 80px;
  height: 30px;
}
.score {
  color: red;
  display: block;
}
.totalScore {
  color: red;
  text-align: center;
}
.clear {
  clear: both;
}
.backcolor {
  background-color: #e4eaec;
}
.board-margin {
  margin-left: 20px;
}
.sub-btn {
  margin-right: 15px;
}
.active-btn {
  background-color: #4cb0f9;
  border-color: #4cb0f9;
  color: #fff;
}
.box-card {
  margin-bottom: 30px;
  text-align: center;
}
.score-input {
  background-color: #ecf0f5;
  border: 1px solid #000;
  border-top: 0;
  border-left: 0;
  border-right: 0;
  box-sizing: border-box;
  color: #1f2d3d;
  font-size: 20px;
  height: 30px;
  width: 60px;
  padding: 2px 10px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  outline: none;
}
</style>
<template>
  <div class="scoreboard pull-right">
    <div class="board-margin">
      <div class="pull-right">
        <el-switch
          v-model="isMouseMode"
          on-text="鼠标"
          off-text="键盘"
          on-color="#4cb0f9"
          off-color="#13ce66"
        ></el-switch>
      </div>
      <h3 class="totalScore">总分：{{ this.totalScore }}分</h3>
      <!-- 鼠标模式 -->
      <div v-if="isMouseMode">
        <el-tabs :active-name="activeName">
          <el-tab-pane label="评分" name="first">
            <ul class="itemScroll">
              <li
                :key="resultItem.markItem.id"
                v-for="(resultItem, index) in resultItems"
                class="pull-left scoretitle"
              >
                <a
                  v-bind:class="{ 'active-btn': itemClass[index] }"
                  :id="resultItem.markItem.id"
                  @click="
                    itemClick(
                      resultItem.markItem.id,
                      $event,
                      resultItem.markItem.orders
                    );
                  "
                  class="button button-border button-box button-primary button-small titlebutton"
                >
                  <label class=""
                    >{{ resultItem.markItem.mainNumber }}({{
                      resultItem.markItem.orders
                    }})</label
                  >
                  <label class="score">{{ resultItem.score }}分</label>
                </a>
              </li>
              <li class="clear"></li>
            </ul>
          </el-tab-pane>
        </el-tabs>

        <el-tabs :active-name="markType" v-if="markTypeView">
          <el-tab-pane label="打分" name="mouse">
            <ul class="scoreScroll">
              <li
                :key="score"
                v-for="score in itemScores"
                class="pull-left scoretitle"
              >
                <button
                  @click="scoreClick(score);"
                  class="button button-primary button-box scorebutton"
                >
                  <label>{{ score }}</label>
                </button>
              </li>
            </ul>
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- 键盘模式 -->
      <div v-if="!isMouseMode">
        <el-tabs :active-name="activeName">
          <el-tab-pane label="评分" name="first">
            <ul class="scroll">
              <li
                :key="resultItem.markItem.id"
                v-for="(resultItem, index) in resultItems"
                class="pull-left scoretitle"
              >
                <div class="box-card">
                  <div>
                    <el-button-group>
                      <el-button size="small" type="primary">
                        <span style="font-size:15px;font-weight:bold">
                          {{ resultItem.markItem.mainNumber }}({{
                            resultItem.markItem.orders
                          }})
                        </span>
                      </el-button>
                      <el-button size="small" type="primary">
                        <span style="font-size:15px;font-weight:bold">
                          <span>{{ resultItem.markItem.maxScore }}分</span>
                        </span>
                      </el-button>
                      <el-button size="small" type="primary">
                        <span style="font-size:15px;font-weight:bold;"
                          >间隔:{{ resultItem.markItem.scoreInterval }}
                        </span>
                      </el-button>
                    </el-button-group>
                  </div>
                  <div
                    style="text-align:center;font-size:15px;font-weight:bold"
                  >
                    <input
                      :id="getItemId(resultItem.markItem.id)"
                      @focus="scoreFocus(resultItem);"
                      @keydown.enter="scoreEnter(index, resultItem);"
                      @keydown.up="scoreUp(index, resultItem);"
                      @keydown.down="scoreDown(index, resultItem);"
                      @change="scoreChange(index, resultItem.score);"
                      v-model="resultItem.score"
                      class="score-input"
                    />
                    分
                  </div>
                </div>
              </li>
              <li class="clear"></li>
            </ul>
          </el-tab-pane>
        </el-tabs>
      </div>

      <el-tabs :active-name="activeName">
        <el-tab-pane label="备注" name="first">
          <ul class="scoreScroll">
            <li>
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入内容"
                v-model="textarea"
                :value="this.markRemarkInfo"
              >
              </el-input>
            </li>
          </ul>
        </el-tab-pane>
      </el-tabs>

      <el-tabs :active-name="op">
        <el-tab-pane label="操作" name="first">
          <ul v-if="problemView">
            <span v-if="tagFlag">
              <el-radio-group
                v-model="markedResult.tag"
                @change="processTagPaper"
              >
                <li
                  class="pull-left scoretitle"
                  v-for="tag in tags"
                  :key="tag.code"
                >
                  <el-radio :label="tag.code">{{ tag.name }}</el-radio>
                </li>
              </el-radio-group>
            </span>
            <span v-if="!tagFlag">
              <el-radio-group v-model="unusualType" @change="processTagPaper">
                <li
                  class="pull-left scoretitle"
                  v-for="tag in tags"
                  :key="tag.code"
                >
                  <el-radio :label="tag.code" :key="tag.code">{{
                    tag.name
                  }}</el-radio>
                </li>
              </el-radio-group>
            </span>
            <li class="clear"></li>
          </ul>
          <ul>
            <li class="pull-left scoretitle" v-if="paperMark">
              <el-button
                id="subMarkBtn"
                :loading="loading"
                type="primary"
                size="large"
                @keydown.enter="submitMark"
                @click="submitMark"
                ><span class="sub-btn">提</span><span>交</span></el-button
              >
            </li>
            <li class="pull-left scoretitle" v-if="paperMark">
              <el-button type="danger" size="large" @click="problemClick"
                >问题卷</el-button
              >
            </li>
            <li class="pull-left scoretitle" v-if="paperMark && problemView">
              <el-button type="danger" size="large" @click="resetProblem"
                >清除问题卷</el-button
              >
            </li>
          </ul>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script>
import { mapActions } from "vuex";
import { USER_SIGNOUT } from "../../portal/store/user";
import { mapState } from "vuex";
import { CORE_API, MARKING_API } from "../constants/constants";
export default {
  data() {
    return {
      activeName: "first",
      markType: "mouse",
      isMouseMode: true,
      op: "first",
      maxScore: 0,
      markItemId: "",
      resultItem: {
        markItem: {},
        score: 0
      },
      markTypeView: false,
      problemView: false,
      markBack: false,
      markSame: false,
      markBlank: false,
      markDiff: false,
      curIndex: 0,
      steps: [],
      loading: false,
      tmpSignItem: this.signItem,
      tags: [],
      unusualType: "",
      scoreError: [],
      textarea: ""
    };
  },
  props: [
    "paperMarkSign",
    "signScores",
    "signChange",
    "signOption",
    "markSign",
    "markRange",
    "studentPaperId",
    "markTaskId",
    "resultItems",
    "markedResult",
    "paperMark"
  ],
  methods: {
    ...mapActions([USER_SIGNOUT]),
    resetProblem() {
      if (this.markedResult.tag) {
        this.markedResult.tag = "";
      }
      if (this.unusualType) {
        this.unusualType = "";
      }
    },
    //处理问题卷
    processTagPaper() {
      if (!this.markedResult.id) {
        if (this.unusualType) {
          for (let resultItem of this.resultItems) {
            resultItem.score = 0;
          }
        }
      } else {
        if (this.markedResult.tag) {
          for (let resultItem of this.resultItems) {
            resultItem.score = 0;
          }
        }
      }
    },
    getTags() {
      this.$http.get(MARKING_API + "/markResults/tag").then(response => {
        this.tags = response.data;
        //移除科目错误
        for (let i = 0; i < this.tags.length; i++) {
          if (this.tags[i].code === "SUBJECT_ERROR") {
            this.tags.splice(i, 1);
          }
        }
      });
    },
    saveMarkSign() {
      localStorage.removeItem(this.paperKey);
      localStorage.setItem(this.paperKey, JSON.stringify(this.paperMarkSign));
    },
    checkItemClass(resultItem) {
      if (resultItem.score.length > 0) {
        return true;
      } else {
        return false;
      }
    },
    itemClick(id, event, order) {
      this.markTypeView = true;
      this.resultItems.find((value, index) => {
        if (value.markItem.id === id) {
          this.maxScore = value.markItem.maxScore;
          this.markItemId = value.markItem.id;
          if (value.score.length > 0) {
            this.resultItem = value;
          } else {
            this.resultItem = {
              markItem: value.markItem,
              score: ""
            };
          }
          this.curIndex = index;
        }
      });
      this.showItemTitle();
      if (this.markSign) {
        this.tmpSignItem = this.resultItem.markItem;
        this.signScores.splice(0, this.signScores.length);
      }
      this.positionDiv(order);
    },
    positionDiv(order) {
      this.$emit("positionDiv", order);
    },
    showItemTitle() {
      var title =
        this.resultItem.markItem.mainNumber +
        "(" +
        this.resultItem.markItem.orders +
        ")";
      this.$message({
        showClose: true,
        message: "当前选择题目为" + title,
        type: "info",
        duration: 1000
      });
    },
    checkSignScore(score) {
      var sum = 0;
      for (let signScore of this.signScores) {
        sum += signScore;
      }
      if (sum + score > this.maxScore) {
        return false;
      } else {
        return true;
      }
    },
    checkScore(resultItem) {
      var score = resultItem.score + "";
      var maxScore = resultItem.markItem.maxScore + "";
      var scoreInterval = resultItem.markItem.scoreInterval + "";
      if (score.trim().length === 0) {
        this.$notify({
          message: "分数不能为空",
          type: "error",
          duration: 1000
        });
        return false;
      } else {
        let regex = scoreInterval == 1 ? "^\\d+$" : "^\\d+(\\.[5])?$";
        if (!score.match(regex)) {
          this.$notify({
            message: "分数必须为数字，且格式要正确(包括间隔分)",
            type: "error",
            duration: 1000
          });
          return false;
        } else {
          if (parseFloat(score) > parseFloat(maxScore)) {
            this.$notify({
              message: "分数不能超过" + maxScore + "分",
              type: "error",
              duration: 1000
            });
            return false;
          }
        }
      }
      return true;
    },
    scoreClick(score) {
      //轨迹模式处理分值问题
      if (this.markSign) {
        if (this.checkSignScore(score)) {
          this.signScores.push(score);
          this.signOption.score = score;
          this.resultItem.score = this.signScoreSum;
          this.resultItems[this.curIndex].score = this.signScoreSum;
        } else {
          this.$notify({
            message: "轨迹总分不能超过满分",
            type: "error"
          });
        }
      } else {
        //正常模式
        this.resultItem.score = score;
        this.resultItems[this.curIndex].score = score;
      }
    },
    //键盘打分板change事件
    scoreChange(index, score) {
      this.resultItem.score = score;
      this.resultItems[index].score = score;
    },
    //键盘打分板聚焦后试卷跳转对应试题
    scoreFocus(resultItem) {
      var order = resultItem.markItem.orders;
      this.positionDiv(order);
    },
    //键盘打分板下键跳转下一题
    scoreDown(index, resultItem) {
      var curItemId = this.resultItems[index].markItem.id;
      var curItemInput = "item" + curItemId;
      if (!this.checkScore(resultItem)) {
        document.getElementById(curItemInput).focus();
        return;
      }
      if (index === this.resultItems.length - 1) {
        return;
      } else {
        var nextResultItem = this.resultItems[index + 1];
        var nextItemId = nextResultItem.markItem.id;
        var nextItemInput = "item" + nextItemId;
        var order = nextResultItem.markItem.orders;
        document.getElementById(nextItemInput).focus();
        this.positionDiv(order);
      }
    },
    //键盘打分板上键跳转上一题
    scoreUp(index, resultItem) {
      var curItemId = this.resultItems[index].markItem.id;
      var curItemInput = "item" + curItemId;
      if (!this.checkScore(resultItem)) {
        document.getElementById(curItemInput).focus();
        return;
      }
      if (index === 0) {
        let preResultItem = this.resultItems[0];
        let preItemId = preResultItem.markItem.id;
        let preItemInput = "item" + preItemId;
        let order = preResultItem.markItem.orders;
        document.getElementById(preItemInput).focus();
        this.positionDiv(order);
      } else {
        let preResultItem = this.resultItems[index - 1];
        let preItemId = preResultItem.markItem.id;
        let preItemInput = "item" + preItemId;
        let order = preResultItem.markItem.orders;
        document.getElementById(preItemInput).focus();
        this.positionDiv(order);
      }
    },
    //键盘打分板回车后跳转下一题
    scoreEnter(index, resultItem) {
      if (!this.checkScore(resultItem)) {
        var curItemId = this.resultItems[index].markItem.id;
        var curItemInput = "item" + curItemId;
        document.getElementById(curItemInput).focus();
        return;
      }
      if (index === this.resultItems.length - 1) {
        document.getElementById("#subMarkBtn").focus();
      } else {
        var nextResultItem = this.resultItems[index + 1];
        var nextItemId = nextResultItem.markItem.id;
        var nextItemInput = "item" + nextItemId;
        var order = nextResultItem.markItem.orders;
        document.getElementById(nextItemInput).focus();
        this.positionDiv(order);
      }
    },
    getItemId(itemId) {
      return "item" + itemId;
    },
    problemClick() {
      this.problemView = !this.problemView;
    },
    checkItems() {
      var itemName = "";
      for (var resultItem of this.resultItems) {
        if (resultItem.score.length == 0) {
          itemName =
            Number.parseInt(resultItem.markItem.mainNumber) +
            "(" +
            resultItem.markItem.orders +
            ")";
          this.$notify({
            message: itemName + "没有打分，请打分",
            type: "error"
          });
          return false;
        } else {
          if (!this.checkScore(resultItem)) {
            return false;
          }
        }
      }
      return true;
    },
    submitMark() {
      if (!this.checkItems()) {
        return;
      }
      this.processTagPaper();
      this.loading = true;
      if (!this.markedResult.id) {
        console.log("提交resultItems", this.resultItems);
        this.$http
          .post(
            MARKING_API +
              "/markResults?studentPaperId=" +
              this.studentPaperId +
              "&markTaskId=" +
              this.markTaskId +
              "&tag=" +
              this.unusualType +
              "&remark=" +
              this.textarea,
            this.resultItems
          )
          .then(
            response => {
              this.saveMarkSign();
              console.log(response);
              if (response.data.id) {
                this.$notify({
                  message: "提交成功",
                  type: "success"
                });
              } else {
                this.$notify({
                  message: "提交失败",
                  type: "error"
                });
              }
              this.$emit("submitMark");
              this.loading = false;
              this.markTypeView = false;
              this.problemView = false;
              this.unusualType = "";
              //this.textarea = '';
            },
            response => {
              // 响应错误回调
              console.log(response);
              if (response.data.desc) {
                var errorInfo = response.data.desc;
                if (errorInfo.includes("超时")) {
                  this.$alert(
                    "该评卷任务已超时，请点击确定重新登录！",
                    "提示",
                    {
                      confirmButtonText: "确定",
                      callback: () => {
                        var loginUrl = sessionStorage.getItem("loginUrl");
                        this.$http
                          .post(CORE_API + "/auth/logout")
                          .then(response => {
                            console.log(response);
                            this.USER_SIGNOUT();
                            sessionStorage.clear();
                            if (loginUrl) {
                              window.location.href = loginUrl;
                            } else {
                              window.location.href = "about:blank";
                            }
                          })
                          .catch(response => {
                            console.log(response);
                            this.USER_SIGNOUT();
                            sessionStorage.clear();
                            if (loginUrl) {
                              window.location.href = loginUrl;
                            } else {
                              window.location.href = "about:blank";
                            }
                          });
                        return;
                      }
                    }
                  );
                } else {
                  this.$notify({
                    message: response.data.desc,
                    type: "error"
                  });
                  this.$emit("submitMark");
                  this.loading = false;
                  this.markTypeView = false;
                  this.problemView = false;
                  this.unusualType = "";
                  //this.textarea = '';
                }
              } else {
                this.$notify({
                  message: "提交失败",
                  type: "error"
                });
                this.$emit("submitMark");
                this.loading = false;
                this.markTypeView = false;
                this.problemView = false;
                this.unusualType = "";
                //this.textarea = '';
              }
            }
          );
      } else {
        console.log("markedResult", this.markedResult);
        this.markedResult.resultItems = this.resultItems;
        this.markedResult.remark = this.textarea;
        this.$http.put(MARKING_API + "/markResults", this.markedResult).then(
          response => {
            this.saveMarkSign();
            console.log(response);
            this.$notify({
              message: "提交成功",
              type: "success"
            });
            this.$emit("submitMark");
            this.loading = false;
            this.markTypeView = false;
            this.problemView = false;
            this.unusualType = "";
            //this.textarea = '';
          },
          response => {
            // 响应错误回调
            console.log(response);
            if (response.data.desc) {
              this.$notify({
                message: response.data.desc,
                type: "error"
              });
            } else {
              this.$notify({
                message: "提交失败",
                type: "error"
              });
            }
            this.$emit("submitMark");
            this.loading = false;
            this.markTypeView = false;
            this.problemView = false;
            this.unusualType = "";
            //this.textarea = '';
          }
        );
      }
    },
    initKeyBoardMode() {
      var itemId = this.resultItems[0].markItem.id;
      var order = this.resultItems[0].markItem.orders;
      var itemInput = "item" + itemId;
      setTimeout(function() {
        document.getElementById(itemInput).focus();
      }, 1);
      this.positionDiv(order);
    }
  },
  watch: {
    signItem(val) {
      this.tmpSignItem = val;
    },
    tmpSignItem(val) {
      this.$emit("changeSign", val);
    },
    isMouseMode(val) {
      if (!val) {
        this.initKeyBoardMode();
      }
    },
    studentPaperId() {
      if (!this.isMouseMode) {
        this.initKeyBoardMode();
      }
    },
    markRemarkInfo() {
      this.textarea = "";
      if (this.markedResult.id) {
        this.textarea = this.markedResult.markRemark;
      }
    }
  },
  computed: {
    tagFlag() {
      if (this.markedResult.id) {
        return true;
      } else {
        return false;
      }
    },
    paperKey() {
      if (!this.markSign) return "";
      return this.studentPaperId;
    },
    signScoreSum() {
      var sum = 0;
      for (let signScore of this.signScores) {
        sum += signScore;
      }
      return sum;
    },
    itemClass() {
      var itemClass = [];
      for (let resultItem of this.resultItems) {
        if (resultItem.score.length == 0) {
          itemClass.push(false);
        } else {
          itemClass.push(true);
        }
      }
      return itemClass;
    },
    totalScore() {
      var totalScore = 0;
      for (let resultItem of this.resultItems) {
        if (resultItem.score.length == 0) {
          totalScore += 0;
        } else {
          totalScore += Number.parseFloat(resultItem.score);
        }
      }
      return totalScore;
    },
    itemScores() {
      var itemScores = [];
      var scoreInterval = this.resultItem.markItem.scoreInterval;
      for (
        let i = 0, j = 0;
        i <= this.resultItem.markItem.maxScore;
        i += scoreInterval, j++
      ) {
        itemScores[j] = i;
      }
      return itemScores;
    },
    ...mapState({ user: state => state.user })
  },
  created() {
    this.getTags();
    this.markRemarkInfo();
  }
};
</script>
