<template>
  <div class="home-page">
    <div class="hp-top">
      <div v-if="hasWaitTaskPrivilege" class="hp-top-left">
        <el-row class="tab-summary" type="flex" :gutter="10">
          <el-col :span="12">
            <div class="tab-summary-item item-wait" @click="toWaitTask">
              <i class="tab-summary-icon icon icon-wait-task"></i>
              <h4 class="tab-summary-title">待办任务</h4>
              <p class="tab-summary-cont">{{ summary.waitTaskCount }}</p>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="tab-summary-item item-done">
              <i class="tab-summary-icon icon icon-done-task"></i>
              <h4 class="tab-summary-title">已办任务</h4>
              <p class="tab-summary-cont">{{ summary.doneTaskCount }}</p>
            </div>
          </el-col>
        </el-row>
        <div class="tab-box tab-task">
          <h2 class="tab-box-title">待办任务</h2>
          <div class="tab-box-body tab-task-list">
            <div
              v-for="item in waitTaskList"
              :key="item.id"
              class="tab-task-item"
            >
              <div :class="['tab-task-item-type', `type-${item.type}`]">
                {{ typeNames[item.type] }}
              </div>
              <div
                class="tab-task-item-cont"
                :title="item.content"
                @click="toDo(item)"
              >
                {{ item.content }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="tab-box tab-shortcut hp-top-right">
        <h2 class="tab-box-title">快捷入口</h2>
        <div class="tab-box-body shortcut-list">
          <div
            v-for="(item, ind) in shortcutList"
            :key="ind"
            class="shortcut-item"
            @click="toMenu(item)"
          >
            <i :class="['icon', item.icon]"></i>
            <span class="shortcut-name">{{ item.name }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="tab-box tab-guide">
      <h2 class="tab-box-title">业务引导图</h2>
      <div class="tab-box-body guide-map">
        <div class="guide-item">
          <div class="guide-spin">命题组卷</div>
        </div>
        <div class="guide-item">
          <div class="guide-spin spin-large spin-light">试卷题卡线上审核</div>
        </div>
        <div class="guide-item guide-island">
          <div class="island-item island-top">
            <h4 class="island-title">线上考试</h4>
            <div class="island-cont">
              <div class="island-btn">
                AI防作弊考试 / 集中无纸化机考
              </div>
            </div>
          </div>
          <div class="island-item island-bottom">
            <h4 class="island-title">线下考试</h4>
            <div class="island-cont">
              <div class="island-btn">印刷+智能分拣</div>
              <div class="island-btn">高速扫描</div>
            </div>
          </div>
        </div>
        <div class="guide-item">
          <div class="guide-spin spin-small">阅卷</div>
        </div>
        <div class="guide-item">
          <div class="guide-spin spin-light">教研分析</div>
        </div>
        <div class="guide-item">
          <div class="guide-spin">归档管理</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import shortcutData from "../constants/shortcutData";
import {
  auditedTaskCount,
  waitExamTaskListPage,
  stmmsTaskListPage,
  analysisTaskListPage
} from "../modules/exam/api";
import { userSysRoles } from "../modules/stmms/api";

export default {
  name: "home-page",
  data() {
    return {
      hasWaitTaskPrivilege: false,
      summary: {
        waitTaskCount: 0,
        doneTaskCount: 0
      },
      shortcutList: [],
      taskList: [[], [], []],
      waitTaskList: [],
      waitTaskFilter: {
        pageNumber: 1,
        pageSize: 2
      },
      typeNames: {
        flow: "流程",
        stmms: "阅卷",
        analysis: "教研"
      }
    };
  },
  computed: {
    ...mapState(["privilegeMap"]),
    ...mapState("exam", ["waitTaskCount"])
  },
  created() {
    this.initShortcutList();
  },
  methods: {
    ...mapActions("exam", ["updateWaitTaskCount"]),
    async initShortcutList() {
      const validRouters = Object.keys(this.privilegeMap);
      let validShortcutData = shortcutData
        .filter(item => validRouters.includes(item.router))
        .map(item => {
          return {
            ...item
          };
        });

      const roleSource = this.$ls.get("user", {
        roleSource: []
      }).roleSource;

      // 阅卷角色查询
      if (validRouters.includes("MarkerLogin")) {
        const markerRoles = await userSysRoles();
        validShortcutData = validShortcutData.filter(
          item =>
            item.router !== "MarkerLogin" ||
            (item.router === "MarkerLogin" &&
              markerRoles.includes(item.params.trigger))
        );
      }

      // 报告角色查询
      if (validRouters.includes("AnalysisReportView")) {
        const analysisRoles = roleSource.filter(
          item => item.roleSource === "ANALYSIS"
        );
        validShortcutData = validShortcutData.filter(
          item =>
            item.router !== "AnalysisReportView" ||
            (item.router === "AnalysisReportView" &&
              analysisRoles.includes(item.params.trigger))
        );
      }

      this.shortcutList = validShortcutData;

      // 代办任务判断
      if (validRouters.includes("WaitTask")) {
        this.hasWaitTaskPrivilege = true;
        this.getWaitTaskData();
      }
    },
    async getWaitTaskData() {
      const doneTaskCount = await auditedTaskCount();
      this.summary.doneTaskCount = doneTaskCount || 0;
      await this.updateWaitTaskCount();
      this.summary.waitTaskCount = this.waitTaskCount;

      await this.getFlowWaitTaskList();
      await this.getStmmsWaitTaskList();
      await this.getAnalysisWaitTaskList();
      this.getWaitTaskList();
    },
    getWaitTaskList() {
      let waitTaskList = [];
      const hasAllTypeTask = !this.taskList.some(item => !item.length);
      if (hasAllTypeTask) {
        this.taskList.forEach(item => {
          waitTaskList.push(item[0]);
        });
        this.waitTaskList = waitTaskList;
      } else {
        this.taskList.forEach(item => {
          waitTaskList.push(...item);
        });
        this.waitTaskList = waitTaskList.slice(0, 3);
      }
    },
    async getFlowWaitTaskList() {
      const data = await waitExamTaskListPage(this.waitTaskFilter);
      const dataList = data.records.map(item => {
        const flowTaskName = item.taskName.replace(/\(.+?\)/g, "");
        return {
          ...item,
          type: "flow",
          content: `${flowTaskName}，试卷编号${item.paperNumber}，${item.courseName}（${item.courseCode}）`
        };
      });
      this.taskList[0] = dataList;
    },
    async getStmmsWaitTaskList() {
      const data = await stmmsTaskListPage(this.waitTaskFilter);
      const dataList = data.records.map(item => {
        return {
          ...item,
          type: "stmms",
          content: `${item.thirdRelateName}（${item.thirdRelateId}），试卷编号${item.paperNumber}，${item.paperType}`
        };
      });
      this.taskList[1] = dataList;
    },
    async getAnalysisWaitTaskList() {
      const data = await analysisTaskListPage(this.waitTaskFilter);
      const dataList = data.records.map(item => {
        return {
          ...item,
          type: "analysis",
          content: `${item.semesterName}，${item.examName}，${item.courseName}（${item.courseCode}）`
        };
      });
      this.taskList[2] = dataList;
    },
    toMenu(item) {
      this.$router.push({
        name: item.router,
        query: item.params
      });
    },
    toDo(item) {
      console.log(item);
      this.$ls.set(`wait_task_${item.type}`, item);
      this.$router.push({
        name: "WaitTask",
        query: {
          type: item.type
        }
      });
    },
    toWaitTask() {
      this.$router.push({
        name: "WaitTask"
      });
    }
  }
};
</script>
