<template>
  <div class="mark-action grade-action">
    <!-- 查询 -->
    <div class="action-search" v-if="rights.search">
      <Input v-model.trim="filter.code" placeholder="请输入号码">
        <Select
          v-model="filter.codeType"
          placeholder="类型"
          slot="prepend"
          style="width: 100px"
        >
          <Option
            v-for="(val, key) in CODE_TYPE"
            :key="key"
            :value="key"
            :label="val"
          ></Option>
        </Select>
        <Button icon="ios-search" slot="append" @click="searchCode"></Button>
      </Input>
    </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 icon="ios-search" slot="append" @click="searchGradeChange"
        >查询</Button
      >
    </div>
    <!-- 头部信息 ------ -->
    <!-- 试卷状态 -->
    <!-- 状态：已评，待评，改档，改档打分 -->
    <div class="action-paper-state">
      <p class="paper-state-cont">{{ step.typeName }}</p>
    </div>
    <!-- 试卷信息 -->
    <div class="action-paper-info">
      <p v-if="IS_ADMIN">{{ curPaper.examNumber }}</p>
      <p>No.{{ curPaper.sn }}</p>
    </div>
    <!-- 改档信息 -->
    <div class="action-grade-change" v-if="rights.gradeChange">
      <p>原档位：{{ curPaper.originLevel }}</p>
      <p>申请档位：{{ curPaper.redoLevel }}</p>
    </div>
    <div class="action-grade-change-status" v-if="rights.gradeChange">
      <p>已同意</p>
    </div>
    <!-- 档位信息 -->
    <!-- 已评/待评（已评档位），改档打分（已评档位） -->
    <div class="action-grade-info" v-if="rights.gradeInfo">
      <h3 class="grade-info-name">{{ curLevel.name }}</h3>
      <p class="grade-info-range">
        <span>{{ curLevel.minScore }}</span>
        <span>~</span>
        <span>{{ curLevel.maxScore }}</span>
      </p>
    </div>
    <!-- 打分信息 -->
    <div class="action-mark-info" v-if="rights.markInfo">
      <p>{{ curPaper.score }}</p>
    </div>
    <!-- 选择分数 / 档位 -->
    <div class="action-grade-list" v-if="rights.gradeList && IS_MARK_LEADER">
      <div
        class="action-grade-list-item"
        v-for="(level, index) in levels"
        :key="index"
      >
        <p @click="selectLevel(level)">{{ level.name }}</p>
        <p>{{ level.range[0] }}~{{ level.range[1] }}</p>
      </div>
    </div>
    <div
      class="action-grade-list action-mark-list"
      v-if="rights.gradeList && !IS_MARK_LEADER"
    >
      <div
        class="action-grade-list-item"
        v-for="(score, index) in scores"
        :key="index"
      >
        <p @click="selectScore(score)">{{ score }}</p>
      </div>
    </div>
    <!-- <div class="action-grade-pass" v-if="rights.gradeList && IS_MARKER">
      <Button type="primary" @click="toPass">跳过</Button>
    </div> -->

    <!-- 评卷记录 -->
    <div class="action-grade-history" v-if="rights.markHis">
      <h3>评卷记录</h3>
      <div class="action-grade-list grade-history-list">
        <div
          class="action-grade-list-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": 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,
  gradeChangeSearch: false,
  gradeChange: false,
  gradeInfo: false,
  markInfo: false,
  gradeList: false,
  markHis: false
};

export default {
  name: "mark-action",
  props: {
    curPaper: {
      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: {
          done: ["search", "gradeList", "gradeHis", "gradeInfo", "markInfo"],
          shift: ["search", "gradeList", "gradeChange"]
        },
        MARKER: {
          done: ["gradeList", "gradeInfo", "markInfo"],
          undo: ["gradeList", "gradeInfo"],
          shift: ["gradeList", "gradeChange"],
          shiftScore: ["gradeList", "gradeInfo"]
        }
      },
      filter: {
        codeType: "examNumber",
        code: ""
      },
      CODE_TYPE,
      CHANGE_LEVEL_STATUS,
      applyChangeLevelStatus: null,
      stepDict: {
        undo: "待评",
        done: "已评",
        level: "改档",
        levelScore: "改档打分"
      },
      stepType: "",
      stepLabel: "",
      scores: [],
      gradingHistory: [],
      curLevel: {}
    };
  },
  computed: {
    IS_ADMIN() {
      return this.userRole === "ADMIN";
    },
    IS_MARKER() {
      return this.userRole === "MARKER";
    },
    IS_MARK_LEADER() {
      return this.userRole === "MARK_LEADER";
    }
  },
  watch: {
    curPaper(val) {
      this.rebuildRight();
    }
  },
  mounted() {
    this.rebuildRight();
  },
  methods: {
    getStepType() {
      const paper = this.curPaper;
      if (paper.level) return "done";
      // TODO:
      // if (paper.arbitrated) return "arbitrate";
      // if (paper.rejected) return "reject";
      // if (!paper.rejected && !paper.arbitrated && !paper.level) return "undo";
      return;
    },
    rebuildRight() {
      this.stepType = this.getStepType();
      this.stepLabel = this.stepDict[this.stepType];
      this.rights = { ...initRights };
      const roleRights = this.roleRight[this.userRole][this.step.type] || [];
      roleRights.map(key => {
        this.rights[key] = true;
      });

      if (this.curPaper.level) {
        this.curLevel = this.levels.find(
          level => level.name === this.curPaper.level
        );
        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.curPaper.id, "SCORE");
      this.gradingHistory = data.map(item => {
        return {
          id: item.markerId,
          name: item.marker,
          value: item.result || "未评"
        };
      });
    },
    selectLevel(level) {
      // 科组长改档
      this.$emit("on-leader-level", {
        curPaperId: this.curPaper.id,
        curLevel: this.curPaper.level,
        selectedLevel: level.name
      });
    },
    selectScore(score) {
      // 评卷员打分
      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>
