<template>
  <div class="online-patrol">
    <div class="part-box-head">
      <div class="part-box-head-left"><h1>在线巡考</h1></div>
    </div>
    <div class="part-filter">
      <div class="part-filter-form">
        <el-form ref="FilterForm" label-position="left" inline>
          <el-form-item>
            <el-select
              v-model="filter.examId"
              placeholder="请选择批次"
              @change="examChange"
            >
              <el-option
                v-for="item in examBatchs"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="filter.examActivityId"
              placeholder="请选择场次"
              clearable
            >
              <el-option
                v-for="item in examActivities"
                :key="item.id"
                :value="item.id"
                :label="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="filter.roomCode"
              placeholder="请选择考场"
              clearable
            >
              <el-option
                v-for="item in examRooms"
                :key="item.id"
                :value="item.roomCode"
                :label="item.roomName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="filter.status" placeholder="考试状态" clearable>
              <el-option
                v-for="(val, key) in STUDENT_ONLINE_STATUS"
                :key="key"
                :value="key"
                :label="val"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="filter.monitorStatusSource"
              placeholder="通讯故障"
              clearable
            >
              <el-option
                v-for="(val, key) in BOOLEAN_TYPE"
                :key="key"
                :value="key * 1"
                :label="val"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model.trim="filter.name"
              placeholder="姓名"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model.trim="filter.identity"
              placeholder="证件号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="陌生人脸">
            <el-input-number
              style="width: 52px;"
              v-model.trim="filter.minMultipleFaceCount"
              placeholder="下限"
              :controls="false"
            ></el-input-number>
            <span class="line-split">-</span>
            <el-input-number
              style="width: 52px;"
              v-model.trim="filter.maxMultipleFaceCount"
              placeholder="上限"
              :controls="false"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="异常处理">
            <el-input-number
              style="width: 52px;"
              v-model.trim="filter.minExceptionCount"
              placeholder="下限"
              :controls="false"
            ></el-input-number>
            <span class="line-split">-</span>
            <el-input-number
              style="width: 52px;"
              v-model.trim="filter.maxExceptionCount"
              placeholder="上限"
              :controls="false"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="预警数">
            <el-input-number
              style="width: 52px;"
              v-model.trim="filter.minWarningCount"
              placeholder="下限"
              :controls="false"
            ></el-input-number>
            <span class="line-split">-</span>
            <el-input-number
              style="width: 52px;"
              v-model.trim="filter.maxWarningCount"
              placeholder="上限"
              :controls="false"
            ></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="toSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="part-filter-info">
        <summary-line
          class="part-filter-info-main"
          data-type="trouble"
          :exam-id="filter.examId"
          v-if="filter.examId"
        ></summary-line>
      </div>
    </div>

    <el-table ref="TableList" :data="dataList">
      <el-table-column prop="roomName" label="考场（代码）">
        <span slot-scope="scope"
          >{{ scope.row.roomName }}({{ scope.row.roomCode }})</span
        >
      </el-table-column>
      <el-table-column prop="identity" label="证件号"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="courseName" label="科目（代码）">
        <span slot-scope="scope"
          >{{ scope.row.courseName }}({{ scope.row.courseCode }})</span
        >
      </el-table-column>
      <el-table-column prop="remainTime" label="剩余时间"></el-table-column>
      <el-table-column prop="progress" label="进度">
        <span slot-scope="scope">{{ scope.row.progress }}%</span>
      </el-table-column>
      <el-table-column prop="clientWebsocketStatus" label="通讯">
        <template slot-scope="scope">
          <right-or-wrong
            :status="CLIENT_WEBSOCKET_STATUS[scope.row.clientWebsocketStatus]"
          ></right-or-wrong>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间">
        <span slot-scope="scope">
          {{ scope.row.updateTime | datetimeFilter }}
        </span>
      </el-table-column>
      <el-table-column prop="exceptionCount" label="异常处理"></el-table-column>
      <el-table-column
        prop="multipleFaceCount"
        label="陌生人脸"
      ></el-table-column>
      <el-table-column prop="warningCount" label="预警数"></el-table-column>
      <el-table-column prop="breachStatus" label="违纪">
        <template slot-scope="scope">
          <span :class="{ 'color-danger': !scope.row.breachStatus }">
            {{ !scope.row.breachStatus ? "违纪" : "正常" }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            class="btn-table-icon"
            type="primary"
            icon="icon icon-view"
            @click="toDetail(scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="part-page">
      <el-pagination
        background
        layout="prev, pager, next,total,sizes,jumper"
        :current-page="current"
        :total="total"
        :page-size.sync="size"
        @size-change="toPage(1)"
        @current-change="toPage"
      >
      </el-pagination>
    </div>

    <div class="patrol-analysis part-box">
      <div class="patrol-analysis-legend" v-if="statData.length">
        <div
          class="legend-item"
          v-for="item in statInfo"
          :key="item.key"
          @click="orderChange(item)"
        >
          <i class="legend-item-symbol"></i>
          <i class="legend-item-name">{{ item.name }}</i>
          <i
            :class="['legend-item-order', `legend-item-order-${item.order}`]"
          ></i>
        </div>
      </div>
      <echart-render
        :chart-data="statData"
        chart-type="barGroup"
        :chart-click="barGroupClick"
      ></echart-render>
    </div>
  </div>
</template>

<script>
import {
  patrolList,
  patrolReportList,
  examBatchList,
  examActivityRoomList,
} from "@/api/invigilation";
import {
  BOOLEAN_TYPE,
  STUDENT_ONLINE_STATUS,
  CLIENT_WEBSOCKET_STATUS,
} from "@/constant/constants";
import EchartRender from "../common/EchartRender";
import SummaryLine from "../common/SummaryLine";
import RightOrWrong from "../common/RightOrWrong";
import { mapState, mapMutations, mapActions } from "vuex";

export default {
  name: "OnlinePatrol",
  components: { EchartRender, SummaryLine, RightOrWrong },
  data() {
    return {
      filter: {
        examId: "",
        examActivityId: null,
        roomCode: null,
        monitorStatusSource: null,
        status: null,
        name: "",
        identity: "",
        maxMultipleFaceCount: undefined,
        minMultipleFaceCount: undefined,
        maxExceptionCount: undefined,
        minExceptionCount: undefined,
        maxWarningCount: undefined,
        minWarningCount: undefined,
      },
      BOOLEAN_TYPE,
      STUDENT_ONLINE_STATUS,
      CLIENT_WEBSOCKET_STATUS,
      current: 1,
      total: 0,
      size: 10,
      examBatchs: [],
      examActivities: [],
      examRooms: [],
      examCourses: [],
      dataList: [],
      statInfo: [
        {
          name: "通讯故障",
          order: "none",
          key: "error",
        },
        {
          name: "预警数",
          order: "none",
          key: "waiting",
        },
      ],
      statData: [],
      cacheDetailIds: [],
    };
  },
  computed: {
    ...mapState("invigilation", ["detailIds"]),
  },
  mounted() {
    this.initData();
  },
  methods: {
    ...mapActions("invigilation", ["updateDetailIds"]),
    ...mapMutations("invigilation", ["setDetailIds"]),
    async initData() {
      await this.getExamBatchList();
      this.filter.examId = this.examBatchs[0] ? this.examBatchs[0].id : "";
      if (!this.filter.examId) return;
      this.toSearch();
      this.getExamActivityRoomList();
    },
    async getList() {
      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };

      const res = await patrolList(datas);
      this.dataList = res.data.data.records.map((item) => {
        item.progress = item.progress ? Math.round(item.progress * 100) : 0;
        return item;
      });
      this.total = res.data.data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    async toSearch() {
      this.current = 1;
      await this.getList();

      this.getPatrolReportList();

      if (this.total > this.size) {
        this.updateDetailIds({
          filterData: this.filter,
          fetchFunc: patrolList,
        });
      } else {
        const ids = this.dataList.map((item) => item.examRecordId);
        this.setDetailIds([...new Set(ids)]);
      }
    },
    async getExamBatchList() {
      const res = await examBatchList();
      this.examBatchs = res.data.data;
    },
    async getExamActivityRoomList() {
      if (!this.filter.examId) return;
      const res = await examActivityRoomList(this.filter.examId);
      this.examActivities = res.data.data.examActivitys;
      this.examRooms = res.data.data.examRooms;
      this.examCourses = res.data.data.examCourses;
    },
    examChange() {
      this.filter.examActivityId = null;
      this.filter.roomCode = null;
      this.filter.courseCode = null;
      this.getExamActivityRoomList();
    },
    toDetail(row) {
      this.$router.push({
        name: "PatrolWarningDetail",
        params: { recordId: row.examRecordId },
      });
    },
    async getPatrolReportList() {
      const res = await patrolReportList(this.filter);
      this.statData = res.data.data.map((item) => {
        return {
          ...item,
          name: item.roomName,
          warning: item.warningCount,
          error: item.clientWebsocketStatusCount,
        };
      });
      // 默认预警数倒叙排列
      this.statInfo.map((elem) => {
        elem.order = "none";
      });
      this.orderChange(this.statInfo[1]);
    },
    orderChange(statItem) {
      const orderInfo = {
        none: "desc",
        desc: "asc",
        asc: "desc",
      };

      this.statInfo.map((elem) => {
        if (elem.key !== statItem.key) elem.order = "none";
      });
      statItem.order = orderInfo[statItem.order];

      this.statData.sort((a, b) => {
        return statItem.order === "desc"
          ? b[statItem.key] - a[statItem.key]
          : a[statItem.key] - b[statItem.key];
      });
    },
    barGroupClick(params) {
      if (params.componentType !== "series") return;

      this.cacheDetailIds = [...this.detailIds];
      const row = this.statData[params.dataIndex];
      console.log(row);
      this.$router.push({
        name: "PatrolExamDetail",
        params: {
          examId: this.filter.examId,
          roomCode: row.roomCode,
          roomName: row.roomName,
        },
      });
    },
  },
  beforeRouteLeave(to, from, next) {
    if (to.name !== "PatrolExamDetail" && to.name !== "PatrolWarningDetail") {
      this.$destroy();
    }
    next();
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === "PatrolExamDetail") {
      next((vm) => vm.$nextTick(() => vm.setDetailIds(vm.cacheDetailIds)));
    } else {
      next();
    }
  },
};
</script>

<style lang="scss" scoped>
.patrol-analysis {
  height: 355px;
  margin-top: 20px;
  position: relative;
}
.patrol-analysis-legend {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 99;

  .legend-item {
    display: inline-block;
    vertical-align: middle;
    color: #626a82;
    font-size: 0;
    cursor: pointer;

    &:not(:last-child) {
      margin-right: 40px;
    }
    &:hover {
      color: #202b4b;
    }

    > i {
      display: inline-block;
      font-size: 14px;
      vertical-align: middle;
      font-style: normal;
    }

    &-symbol {
      height: 8px;
      width: 8px;
      border-radius: 50%;
    }
    &-name {
      margin: 0 8px;
    }
    &-order {
      width: 6px;
      height: 8px;
      background-image: url(../../../assets/icon-order-none.png);
      background-size: 100% 100%;

      &-desc {
        background-image: url(../../../assets/icon-order-desc.png);
      }
      &-asc {
        background-image: url(../../../assets/icon-order-asc.png);
      }
    }

    &:nth-of-type(1) {
      .legend-item-symbol {
        background: #5fc9fa;
      }
    }
    &:nth-of-type(2) {
      .legend-item-symbol {
        background: #fe5863;
      }
    }
    &:nth-of-type(3) {
      .legend-item-symbol {
        background: #feca57;
      }
    }
  }
}
</style>
