<template>
  <div class="mark-action grade-action">
    <!-- 查询 -->
    <div class="action-search" v-if="rights.search">
      <Select
        class="search-select"
        v-model="filter.codeType"
        placeholder="密号类型"
      >
        <Option
          v-for="(val, key) in CODE_TYPE"
          :key="key"
          :value="key"
          :label="val"
        ></Option>
      </Select>
      <Input
        class="search-input"
        v-model.trim="filter.code"
        placeholder="输入密号"
      >
      </Input>
      <Button size="small" type="primary" class="search-btn" @click="searchCode"
        >查询</Button
      >
    </div>
    <!-- 改档处理状态查询 -->
    <div class="action-grade-change-search" v-if="rights.gradeChangeSearch">
      <Select
        v-model="applyChangeLevelStatus"
        placeholder="类型"
        style="width: 100px"
      >
        <Option
          v-for="(val, key) in CHANGE_LEVEL_STATUS"
          :key="key"
          :value="key * 1"
          :label="val"
        ></Option>
      </Select>
      <Button
        size="small"
        type="primary"
        class="search-btn"
        @click="searchGradeChange"
        >查询</Button
      >
    </div>
    <!-- 头部信息 ------ -->
    <!-- 试卷状态 -->
    <!-- 状态：已评，待评，改档，改档打分 -->
    <div class="action-paper-state">
      <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>试卷密号：</span><span>NO.{{ curPaperOrTask.sn }}</span>
      </p>
    </div>
    <!-- 改档信息 -->
    <div class="action-grade-change" v-if="rights.gradeChange">
      <p>
        <span>原始档位：</span><span>{{ curPaperOrTask.originLevel }}</span>
      </p>
      <p>
        <span>申请档位：</span><span>{{ curPaperOrTask.redoLevel }}</span>
      </p>
    </div>
    <div
      :class="[
        'action-grade-change-status',
        { 'action-grade-change-status-error': curPaperOrTask.auditStatus === 0 }
      ]"
      v-if="rights.gradeChange && IS_ADMIN"
    >
      <p>{{ curPaperOrTask.auditStatus === 1 ? "同意改档" : "不同意改档" }}</p>
    </div>

    <!-- 档位信息 -->
    <!-- 已评/待评（已评档位），改档打分（已评档位） -->
    <div class="action-grade-info" v-if="rights.gradeInfo">
      <h3 class="grade-info-name">
        {{ curPaperLevel }}
      </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-info action-mark-info" v-if="rights.markInfo">
      <p class="grade-info-name" v-if="curPaperScore">
        {{ curPaperScore }}
      </p>
      <p class="grade-info-name grade-info-none" v-else>未打分</p>
    </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-mark-list" v-if="rights.levelList">
      <div
        class="action-mark-item"
        v-for="(score, index) in scores"
        :key="index"
      >
        <div
          :class="[
            'action-mark-item-content',
            { 'action-item-content-disabled': btnClicked }
          ]"
          @click="selectScore(score)"
        >
          <p>{{ score }}</p>
        </div>
      </div>
    </div>
    <div class="action-grade-pass" v-if="rights.levelList">
      <Button @click="toPass">跳过</Button>
    </div>

    <!-- 评卷记录 -->
    <div class="action-grade-history" v-if="rights.markHis">
      <h3>评卷记录</h3>
      <div class="grade-history-list">
        <div
          class="grade-history-item"
          v-for="(his, hindex) in gradingHistory"
          :key="hindex"
        >
          <p>{{ his.name }}</p>
          <p>{{ his.value }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { markHistoryList } from "@/api";
import { CODE_TYPE, CHANGE_LEVEL_STATUS } from "@/constants/enumerate";
// 三种情况：
// 管理员(ADMIN)，科组长(MARK_LEADER)，评卷员(MARKER)
// 管理员：查询，头部信息，评卷记录
// 科组长：查询，头部信息，选择档位，评卷记录
// 评卷员：头部信息，选择分数
/*
[paper template]
{
  "id": 42,
  "sn": "5314987744",
  "redoLevel": null,
  "level": "B",
  "score": null,
  "result": "88",
  "originLevel": null,
  "markerId": 52,
  "marker": "zj-pj-01",
  "updatedOn": 1595812145000,
  "imgSrc": "http://192.168.10.145:9000/images/34/SC/1/1901130046.jpg?random=f5549bb0-ba58-4cd3-a88e-0559be4e06e5",
  "thumbSrc": "http://192.168.10.145:9000/thumbs/34/SC/1/1901130046.jpg?random=e7f880b8-4cb6-4963-8e66-532f0f8bdeb0",
  "markByLeader": false,
  "oldRejected": false,
  "paperId": 116,
  "randomSeqNew": 4987744,
  "randomSeq": null,
  "serialNumber": "B1",
  "displayNumber": true,
  "shift": false,
  "shiftScore": false,
  "rejected": false,
  "sample": false
}
[marktask template]
{
  "id": 38,
  "sn": "5314266469",
  "redoLevel": null,
  "level": "A",
  "score": null,
  "result": "96",
  "originLevel": null,
  "markerId": 52,
  "marker": "zj-pj-01",
  "updatedOn": 1595812012000,
  "imgSrc": "http://192.168.10.145:9000/images/34/SC/1/1901130043.jpg?random=bffc061c-7a80-42a4-ad56-36ec6eba0d45",
  "thumbSrc": "http://192.168.10.145:9000/thumbs/34/SC/1/1901130043.jpg?random=da743f9d-8d46-4499-bb6f-b9c26e003ba2",
  "markByLeader": true,
  "oldRejected": false,
  "paperId": 113,
  "randomSeqNew": 4266469,
  "randomSeq": null,
  "serialNumber": "A1",
  "displayNumber": true,
  "shift": false,
  "shiftScore": false,
  "rejected": false,
  "sample": true
}
*/

const initRights = {
  search: false,
  gradeChangeSearch: false,
  gradeChange: false,
  gradeInfo: false,
  markInfo: false,
  gradeList: false,
  levelList: false,
  markHis: false
};

export default {
  name: "mark-action",
  props: {
    curPaperOrTask: {
      type: Object,
      default() {
        return {};
      }
    },
    levels: {
      type: Array,
      default() {
        return [];
      }
    },
    userRole: {
      type: String,
      default: "MARKER"
    }
  },
  data() {
    return {
      rights: {
        ...initRights
      },
      roleRight: {
        ADMIN: {
          done: ["search", "gradeHis", "gradeInfo", "markInfo"],
          shift: ["search", "gradeChangeSearch", "gradeChange"]
        },
        MARK_LEADER: {
          undo: ["search", "gradeList", "gradeInfo", "markInfo"],
          done: ["search", "gradeList", "gradeHis", "gradeInfo", "markInfo"],
          shift: ["search", "gradeList", "gradeChange"]
        },
        MARKER: {
          done: ["levelList", "gradeInfo", "markInfo"],
          undo: ["levelList", "gradeInfo"],
          shift: ["gradeList", "gradeChange"],
          shiftScore: ["levelList", "gradeInfo"]
        }
      },
      filter: {
        codeType: "examNumber",
        code: ""
      },
      CODE_TYPE,
      CHANGE_LEVEL_STATUS,
      applyChangeLevelStatus: null,
      stepDict: {
        undo: "待评",
        done: "已评",
        shift: "改档",
        shiftScore: "改档打分"
      },
      stepType: "",
      stepLabel: "",
      curPaperLevel: "",
      curPaperScore: "",
      scores: [],
      gradingHistory: [],
      curLevel: {},
      setT: null,
      btnClicked: false
    };
  },
  computed: {
    IS_ADMIN() {
      return this.userRole === "ADMIN";
    },
    IS_MARKER() {
      return this.userRole === "MARKER";
    },
    IS_MARK_LEADER() {
      return this.userRole === "MARK_LEADER";
    }
  },
  watch: {
    curPaperOrTask(val) {
      this.rebuildRight();
    }
  },
  mounted() {
    this.rebuildRight();
  },
  methods: {
    getStepType() {
      const paper = this.curPaperOrTask;
      if (paper.shift && paper.shiftScore && !paper.level) return "shift";
      if (!paper.shift && paper.shiftScore) return "shiftScore";
      if (this.IS_MARKER) {
        if (!paper.result) return "undo";
        if (paper.result) return "done";
      } else {
        if (paper.score !== null) return "done";
        if (paper.score === null) return "undo";
      }
    },
    rebuildRight() {
      const curPaperScore = this.IS_MARKER
        ? this.curPaperOrTask.result
        : this.curPaperOrTask.score;
      this.curPaperScore = curPaperScore !== null ? curPaperScore + "" : "";
      this.stepType = this.getStepType();
      this.stepLabel = this.stepDict[this.stepType];
      this.rights = { ...initRights };
      const roleRights = this.roleRight[this.userRole][this.stepType] || [];
      roleRights.map(key => {
        this.rights[key] = true;
      });

      if (this.curPaperOrTask.level) {
        this.curLevel = this.levels.find(
          level => level.name === this.curPaperOrTask.level
        );
        this.curPaperLevel =
          this.curPaperOrTask["displayNumber"] && this.stepType !== "shiftScore"
            ? this.curPaperOrTask["serialNumber"]
            : this.curLevel.name;
        this.updateScoreList();
      }
      if (this.rights.gradeHis) {
        this.getMarkHistory();
      }
    },
    updateScoreList() {
      let scores = [];
      const { minScore, maxScore } = this.curLevel;
      for (let i = minScore; i <= maxScore; i++) {
        scores.push(i);
      }
      this.scores = scores;
    },
    async getMarkHistory() {
      const data = await markHistoryList(this.curPaperOrTask.id, "SCORE");
      this.gradingHistory = data.map(item => {
        return {
          id: item.markerId,
          name: item.marker,
          value: item.result || "未评"
        };
      });
    },
    selectLevel(level) {
      if (this.curPaperOrTask.level === level.name) return;

      if (this.btnClicked) return;
      this.btnClicked = true;

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

      // 科组长改档
      this.$emit("on-leader-level", {
        paperId: this.curPaperOrTask.id,
        curLevel: this.curPaperOrTask.level,
        selectedLevel: level.name
      });
    },
    selectScore(score) {
      if (this.btnClicked) return;
      this.btnClicked = true;

      this.setT = setTimeout(() => {
        this.btnClicked = false;
      }, 500);
      // 评卷员打分
      this.$emit("on-select-score", score * 1);
    },
    toPass() {
      this.$emit("on-pass");
    },
    searchCode() {
      this.$emit("on-code-search", this.filter);
    },
    searchGradeChange() {
      this.$emit("on-grade-change-search", this.applyChangeLevelStatus);
    }
  }
};
</script>
