<template>
  <div class="grade-action">
    <!-- 查询 -->
    <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 class="action-paper-state" v-if="stepType === 'reject'">
      <p class="paper-state-cont">
        {{ curPaperOrTask.isRejectedByLeader ? "科组长打回" : "自动打回" }}
      </p>
      <p class="paper-state-intro" v-if="curPaperOrTask.rejectedCount">
        共打回{{ curPaperOrTask.rejectedCount }}次
      </p>
    </div>
    <div class="action-paper-state" v-else>
      <p class="paper-state-cont">{{ stepLabel }}</p>
    </div>
    <!-- 试卷信息 -->
    <div class="action-paper-info">
      <p v-if="IS_ADMIN">
        <span>试卷考号：</span><span>{{ curPaperOrTask.examNumber }}</span>
      </p>
      <p>
        <span v-if="IS_MARKER">任务密号：</span>
        <span v-else>试卷密号：</span>
        <span>NO.{{ curPaperOrTask.sn }}</span>
      </p>
    </div>
    <!-- 档位信息 -->
    <!-- 已评（已评档位），打回（建议档位） -->
    <h3 class="action-grade-info-title" v-if="curPaperOrTask.rejected">
      建议档位：
    </h3>
    <div class="action-grade-info" v-if="rights.gradeInfo">
      <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-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 }
          ]"
          @click="selectLevel(level)"
        >
          <p>{{ level.name }}</p>
          <p>{{ level.minScore }}~{{ level.maxScore }}</p>
        </div>
      </div>
    </div>
    <div
      class="action-grade-pass"
      v-if="rights.gradeList && 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>
</template>

<script>
import { markHistoryList } from "@/api";
import { CODE_TYPE } from "@/constants/enumerate";
// 三种情况：
// 管理员(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,
  gradeHis: false
};

export default {
  name: "grade-action",
  props: {
    curPaperOrTask: {
      type: Object,
      default() {
        return {};
      }
    },
    levels: {
      type: Array,
      default() {
        return [];
      }
    },
    userRole: {
      type: String,
      default: "MARKER"
    }
  },
  data() {
    return {
      rights: {
        ...initRights
      },
      roleRight: {
        SUPER_ADMIN: {
          done: ["search", "gradeHis", "gradeInfo"],
          reject: ["search", "gradeInfo", "gradeHis"],
          arbitrate: ["search", "gradeHis"]
        },
        ADMIN: {
          done: ["search", "gradeHis", "gradeInfo"],
          reject: ["search", "gradeInfo", "gradeHis"],
          arbitrate: ["search", "gradeHis"]
        },
        MARK_LEADER: {
          undo: ["search", "gradeList", "gradeInfo"],
          done: ["search", "gradeList", "gradeHis", "gradeInfo"],
          reject: ["search", "gradeList", "gradeInfo", "gradeHis"],
          arbitrate: ["search", "gradeList", "gradeHis"]
        },
        MARKER: {
          done: ["gradeList", "gradeInfo"],
          undo: ["gradeList"],
          reject: ["gradeList", "gradeInfo"]
        },
        STANDARD: ["gradeInfo"]
      },
      filter: {
        codeType: "examNumber",
        code: ""
      },
      codeTypes: [],
      stepDict: {
        undo: "待评",
        done: "已评",
        reject: "打回",
        arbitrate: "待仲裁",
        sample: "标准卷"
      },
      stepType: "",
      stepLabel: "",
      gradingHistory: [],
      curLevel: {},
      setT: null,
      btnClicked: false
    };
  },
  computed: {
    IS_ADMIN() {
      return this.userRole === "ADMIN" || this.userRole === "SUPER_ADMIN";
    },
    IS_MARKER() {
      return this.userRole === "MARKER";
    },
    IS_MARK_LEADER() {
      return this.userRole === "MARK_LEADER";
    }
  },
  watch: {
    curPaperOrTask(val) {
      this.rebuildRight();
    }
  },
  mounted() {
    this.codeTypes = Object.entries(CODE_TYPE)
      .map(([key, val]) => {
        return {
          key,
          val
        };
      })
      .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() {
      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.userRole][this.stepType] || [];
      }
      this.rights = { ...initRights };
      roleRights.map(key => {
        this.rights[key] = true;
      });
      this.getCurLevel();
      if (this.rights.gradeHis) {
        this.getMarkHistory();
      }
    },
    getCurLevel() {
      const levelName = this.curPaperOrTask.rejected
        ? this.curPaperOrTask.redoLevel
        : this.curPaperOrTask.level;
      if (levelName) {
        this.curLevel = this.levels.find(item => item.name === levelName);
      }
    },
    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.IS_MARKER && this.curPaperOrTask.level === level.name) return;
      if (this.btnClicked) return;
      this.btnClicked = true;

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

      if (this.IS_MARK_LEADER) {
        this.$emit(
          "on-leader-level",
          {
            paperIds: this.curPaperOrTask.id + "",
            curLevel: this.curPaperOrTask.level,
            selectedLevel: level.name
          },
          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);
    }
  },
  beforeDestroy() {
    if (this.setT) clearTimeout(this.setT);
  }
};
</script>
