<template>
  <div class="grade-action">
    <!-- 头部信息 ------ -->
    <!-- 试卷状态 -->
    <!-- 状态：已评，待评，打回，仲裁 -->
    <div class="action-paper-state" v-if="stepType === 'reject'">
      <p class="paper-state-cont">
        {{ curPaperOrTask.isRejectedByLeader ? "科组长打回" : "自动打回" }}
      </p>
      <p class="paper-state-intro">
        <span v-if="curPaperOrTask.rejectedCount"
          >共打回{{ curPaperOrTask.rejectedCount }}次</span
        >
      </p>
    </div>
    <div class="action-paper-state" v-else>
      <p class="paper-state-cont">{{ stepLabel }}</p>
    </div>

    <!-- 试卷信息 -->
    <div class="action-paper-info">
      <p>
        <span v-if="IS_MARKER">任务密号：</span>
        <span v-else>试卷密号：</span>
        <span v-if="curPaperOrTask.sn && !isBatchAction">
          NO.{{ curPaperOrTask.sn }}
        </span>
        <span v-else>--</span>
      </p>
    </div>

    <!-- 选择档位 -->
    <h3
      class="action-grade-info-title"
      v-if="IS_MARK_LEADER && markLeaderOnlyRight && rights.gradeList"
    >
      当前操作：{{ markLeaderOnlyRight.name }}
    </h3>
    <div class="action-grade-list" v-if="rights.gradeList">
      <div
        class="action-grade-item"
        v-for="(level, index) in levels"
        :key="index"
      >
        <div
          :class="[
            'action-grade-item-content',
            {
              'action-item-content-disabled': btnClicked,
              'is-active': keyInput == level.name
            }
          ]"
          @click="selectLevel(level)"
        >
          <p>{{ level.name }}</p>
          <p>{{ level.minScore }}~{{ level.maxScore }}</p>
        </div>
      </div>
    </div>
    <div v-if="ribbonSet.keyboardMark" class="action-grade-keyboard">
      <div class="keyboard-input">{{ keyInput }}</div>
      <div class="keyboard-clear" @click="clearKeyInput">
        <Icon type="md-trash" />
      </div>
    </div>

    <!-- 档位信息 -->
    <!-- 已评（已评档位），打回（建议档位） -->
    <h3
      class="action-grade-info-title"
      v-if="IS_MARKER && stepType === 'reject'"
    >
      <span>原分档档位：{{ curPaperOrTask.originLevel || "" }}</span>
      <span
        v-if="
          paramsSet.autoCallbackShowDeviation &&
            curPaperOrTask.deviationDirection &&
            curPaperOrTask.deviationDirection !== '0'
        "
        :class="[
          'grade-info-deviation',
          {
            'grade-info-deviation-error':
              curPaperOrTask.deviationDirection * 1 > 0
          }
        ]"
        >{{ curPaperOrTask.deviationDirection * 1 > 0 ? "偏高" : "偏低" }}</span
      >
    </h3>
    <h3
      class="action-grade-info-title"
      v-if="curPaperOrTask.rejected && curPaperOrTask.isRejectedByLeader"
    >
      建议档位：
    </h3>
    <div class="action-grade-info" v-if="rights.gradeInfo && curLevel.name">
      <h3 class="grade-info-name">{{ curLevel.name }}</h3>
      <div class="grade-info-range">
        <p>分数范围</p>
        <p>
          <span>{{ curLevel.minScore }}</span>
          <span>~</span>
          <span>{{ curLevel.maxScore }}</span>
        </p>
      </div>
    </div>

    <!-- 跳过 -->
    <div
      class="action-grade-pass"
      v-if="rights.gradePass && IS_MARKER"
      @click="toPass"
    >
      跳过
    </div>

    <!-- 评卷记录 -->
    <div class="action-grade-history" v-if="rights.gradeHis">
      <h3>评卷记录</h3>
      <div class="grade-history-list">
        <div
          class="grade-history-item"
          v-for="his in gradingHistory"
          :key="his.id"
        >
          <p>{{ his.loginName }}</p>
          <p>{{ his.value }}</p>
        </div>
      </div>
    </div>

    <!-- 查询 -->
    <div class="action-search" v-if="rights.search">
      <Select
        class="search-select"
        v-model="filter.codeType"
        placeholder="密号类型"
      >
        <Option
          v-for="item in codeTypes"
          :key="item.key"
          :value="item.key"
          :label="item.val"
        ></Option>
      </Select>
      <Input
        class="search-input"
        v-model.trim="filter.code"
        placeholder="输入密号"
        clearable
      >
      </Input>
      <Button size="small" type="primary" class="search-btn" @click="searchCode"
        >查询</Button
      >
    </div>
  </div>
</template>

<script>
import { markHistoryList } from "@/api";
import { CODE_TYPE } from "@/constants/enumerate";
import { mapState } from "vuex";

// 三种情况：
// 管理员(ADMIN)，科组长(MARK_LEADER)，评卷员(MARKER)
// 管理员：查询，头部信息，评卷记录
// 科组长：查询，头部信息，选择档位，评卷记录
// 评卷员：头部信息，选择档位

// MARK_LEADER / ADMIN: curPaperOrTask => paper
// MARKER: curPaperOrTask => task
//
/*
[paper template]
{
  "id": 165,
  "sn": "029947536",
  "examNumber": "1901040084",
  "level": "A",
  "score": null,
  "redoLevel": null,
  "updatedOn": 1591767742000,
  "imgSrc": "",
  "thumbSrc": "",
  "markByLeader": false,
  "markedLogic": true,
  "areaCode": "2",
  "inspectScore": null,
  "inspectLevel": null,
  "inspector": null,
  "sheetSrc": null,
  "stage": "LEVEL",
  "test": 0,
  "paperTest": 0,
  "markResults": [],
  "rejected": false,
  "arbitrated": false,
  "sample": false,
  "tagged": false,
  "missing": false,
  "manual": false
}
[marktask template]
{
  "id": 511,
  "sn": "4929446110",
  "redoLevel": null,
  "level": "A",
  "score": null,
  "result": "100",
  "originLevel": null,
  "markerId": 49,
  "marker": "pj061001",
  "updatedOn": 1594775592000,
  "imgSrc": "",
  "thumbSrc": "",
  "markByLeader": true,
  "oldRejected": false,
  "paperId": 168,
  "randomSeqNew": 9446110,
  "randomSeq": null,
  "rejected": false,
  "sample": true
}
*/

const initRights = {
  search: false,
  gradeInfo: false,
  gradeList: false,
  gradePass: false,
  gradeHis: false
};

export default {
  name: "grade-action",
  props: {
    curPaperOrTask: {
      type: Object,
      default() {
        return {};
      }
    },
    levels: {
      type: Array,
      default() {
        return [];
      }
    },
    paramsSet: {
      type: Object,
      default() {
        return {};
      }
    },
    isBatchAction: {
      type: Boolean,
      default: false
    },
    // 是否处于粗分档
    isRoughLevel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      curUserRoleType: this.$ls.get("user", { role: "" }).role,
      rights: {
        ...initRights
      },
      cacheRights: null,
      roleRight: {
        ADMIN: {
          done: ["search", "gradeHis", "gradeInfo"],
          reject: ["search", "gradeInfo", "gradeHis"],
          arbitrate: ["search", "gradeHis"]
        },
        MARK_LEADER: {
          undo: ["gradeList", "gradePass", "gradeInfo"],
          done: ["gradeList", "gradeHis", "gradeInfo"],
          reject: ["gradeList", "gradePass", "gradeInfo", "gradeHis"],
          arbitrate: ["gradeList", "gradePass", "gradeHis"],
          batch: ["gradeList"]
        },
        MARKER: {
          done: ["gradeList", "gradeInfo"],
          undo: ["gradeList", "gradePass"],
          reject: ["gradeList", "gradePass", "gradeInfo"],
          batch: ["gradeList"]
        },
        STANDARD: ["gradeInfo"]
      },
      filter: {
        codeType: "examNumber",
        code: ""
      },
      codeTypes: [],
      stepDict: {
        undo: "待评",
        done: "已评",
        reject: "打回",
        arbitrate: "待仲裁",
        sample: "标准卷",
        batch: "批量操作"
      },
      stepType: "",
      stepLabel: "",
      gradingHistory: [],
      curLevel: {},
      setT: null,
      btnClicked: false,
      keyInput: null,
      // 科组长权限
      markLeaderOnlyRight: null
    };
  },
  computed: {
    ...mapState("marker", ["ribbonSet"]),
    IS_ADMIN() {
      return this.curUserRoleType === "ADMIN";
    },
    IS_MARKER() {
      return this.curUserRoleType === "MARKER";
    },
    IS_MARK_LEADER() {
      return this.curUserRoleType === "MARK_LEADER";
    }
  },
  watch: {
    curPaperOrTask() {
      this.rebuildRight();
    },
    isBatchAction(val) {
      if (val) {
        this.stepType = "batch";
        this.stepLabel = this.stepDict[this.stepType];
        const roleRights =
          this.roleRight[this.curUserRoleType][this.stepType] || [];
        this.rights = { ...initRights };
        roleRights.map(key => {
          this.rights[key] = true;
        });
      } else {
        this.rebuildRight();
      }
      this.keyInput = null;
    },
    "ribbonSet.keyboardMark": {
      immediate: true,
      handler(val) {
        if (val) {
          document.addEventListener("keydown", this.keyEvent);
        } else {
          this.keyInput = null;
          document.removeEventListener("keydown", this.keyEvent);
        }
      }
    }
  },
  mounted() {
    this.markLeaderOnlyRight = this.$ls.get("user", {
      markLeaderOnlyRight: null
    }).markLeaderOnlyRight;

    this.codeTypes = Object.entries(CODE_TYPE)
      .map(([key, val]) => {
        return {
          key,
          val
        };
      })
      .filter(item => item.key !== "examNumber");
    // .filter(item => this.IS_ADMIN || item.key !== "examNumber");
    this.rebuildRight();
  },
  methods: {
    getStepType() {
      const info = this.curPaperOrTask;
      if (info.sample) return "sample";
      if (info.level) return "done";
      if (info.arbitrated) return "arbitrate";
      if (info.rejected) return "reject";
      if (!info.rejected && !info.arbitrated && !info.level) return "undo";
      return;
    },
    rebuildRight() {
      if (this.setT) clearTimeout(this.setT);

      let roleRights = [];
      this.stepType = this.getStepType();
      this.stepLabel = this.stepDict[this.stepType];
      if (this.stepType === "sample") {
        roleRights = this.roleRight.STANDARD;
      } else {
        roleRights = this.roleRight[this.curUserRoleType][this.stepType] || [];
      }
      this.rights = { ...initRights };
      roleRights.map(key => {
        this.rights[key] = true;
      });
      this.getCurLevel();
      if (this.rights.gradeHis) {
        this.getMarkHistory();
      }
      this.btnClicked = false;
      this.keyInput = null;
    },
    getCurLevel() {
      const levelName = this.curPaperOrTask.rejected
        ? this.curPaperOrTask.redoLevel
        : this.curPaperOrTask.level;
      if (levelName) {
        this.curLevel = this.levels.find(item => item.name === levelName);
      } else {
        this.curLevel = {};
      }
    },
    async getMarkHistory() {
      // 只有科组长和超管才会展示评卷记录
      const data = await markHistoryList(this.curPaperOrTask.id, "LEVEL");
      this.gradingHistory = data.map(item => {
        let level = item.result || "未评";
        if (this.stepType === "reject" && !item.result) {
          level = `${level}(${item.originLevel})`;
        }
        return {
          id: item.id,
          markerId: item.markerId,
          name: item.marker,
          loginName: item.loginName,
          value: level
        };
      });
    },
    selectLevel(level) {
      if (this.isBatchAction) {
        if (this.btnClicked) return;
        this.btnClicked = true;
        this.setT = setTimeout(() => {
          this.btnClicked = false;
        }, 500);
        this.$emit("on-batch-level", level);
        return;
      }

      if (this.IS_MARKER && this.curPaperOrTask.level === level.name) return;
      if (this.btnClicked) return;
      this.btnClicked = true;

      if (this.IS_MARK_LEADER) {
        this.setT = setTimeout(() => {
          this.btnClicked = false;
        }, 500);

        this.$emit(
          "on-leader-level",
          {
            paperIds: this.curPaperOrTask.id + "",
            curLevel: this.curPaperOrTask.level,
            selectedLevel: level.name,
            markLeaderOnlyRight: this.markLeaderOnlyRight
          },
          this.gradingHistory.map(item => {
            return {
              id: item.markerId,
              name: item.loginName
            };
          })
        );
        return;
      }

      this.$emit("on-select-level", level);
    },
    toPass() {
      this.$emit("on-pass");
    },
    searchCode() {
      if (!this.filter.code || !this.filter.codeType) {
        this.$Message.error("请设置密号类型和密号！");
        return;
      }
      this.$emit("on-code-search", this.filter);
    },
    // keyboard submit
    keyEvent(e) {
      this.$Message.destroy();
      if (this.btnClicked) return;
      // if (!this.ribbonSet.keyboardMark) return;
      if (!e.altKey && !e.shiftKey && !e.ctrlKey) {
        const validKeys = ["F5", "ArrowLeft", "ArrowRight"];
        if (validKeys.includes(e.key)) return;

        if (e.key === "Enter" && this.ribbonSet.needEnterSubmit) {
          e.preventDefault();
          this.toKeySubmit();
          return;
        }
        const keyInput = e.key.toUpperCase();
        if (this.getKeyInputLevel(keyInput)) {
          e.preventDefault();
          this.keyInput = keyInput;

          if (!this.ribbonSet.needEnterSubmit) {
            this.toKeySubmit();
          }
        } else {
          this.$Message.error("按键无效");
        }
      }
    },
    getKeyInputLevel(key) {
      return this.levels.find(item => item.name === key);
    },
    toKeySubmit() {
      if (!this.keyInput) return;
      const level = this.getKeyInputLevel(this.keyInput);
      this.selectLevel(level);
    },
    clearKeyInput() {
      this.keyInput = null;
    }
  },
  beforeDestroy() {
    if (this.setT) clearTimeout(this.setT);
    if (this.ribbonSet.keyboardMark)
      document.removeEventListener("click", this.keyEvent);
  }
};
</script>
