<template>
  <div class="patrol-warning-detail warning-detail">
    <div class="warning-detail-head">
      <h2>预警详情</h2>
      <el-button size="mini" icon="el-icon-arrow-left" @click="goBack">
        返回列表
      </el-button>
    </div>

    <div class="warning-detail-body">
      <div class="detail-body-head">
        <div class="detail-body-head-left">
          <p>
            <i class="icon icon-person"></i>
            <span>{{ detailInfo.examStudentName }}</span>
          </p>
          <p>
            <span>证件号：</span><span>{{ detailInfo.identity }}</span>
          </p>
          <p>
            <span>科目（代码）：</span
            ><span>{{ detailInfo.courseNameCode }}</span>
          </p>
        </div>
        <div class="detail-body-head-right">
          <el-button
            type="primary"
            title="查看上一个"
            :disabled="holding"
            @click="changeStudent(0)"
          >
            <i class="icon icon-arrow-left"></i>
          </el-button>
          <el-button
            type="primary"
            title="查看下一个"
            :disabled="holding"
            @click="changeStudent(1)"
          >
            <i class="icon icon-arrow-right"></i>
          </el-button>
        </div>
      </div>
      <div class="warning-detail-main">
        <div class="warning-action">
          <div class="student-avatar">
            <img
              :src="detailInfo.basePhotoPath"
              :alt="detailInfo.examStudentName"
              v-if="detailInfo.basePhotoPath"
            />
            <div class="avatar-default" v-else>
              <i class="el-icon-user-solid"></i>
            </div>
            <div class="avatar-title">学生底照</div>
          </div>
          <div class="warning-summary">
            <div class="warning-summary-row">
              <p class="warning-summary-col">
                <i class="icon icon-bell"></i>
                <span class="line-name"
                  >系统预警
                  <em :class="{ 'color-danger': detailInfo.warningCount > 0 }"
                    >{{ detailInfo.warningCount }}次</em
                  ></span
                >
              </p>
              <p class="warning-summary-col">
                <i class="icon icon-face"></i>
                <span class="line-name"
                  >陌生人脸
                  <em>{{ detailInfo.multipleFaceCount }}次</em>
                </span>
              </p>
            </div>
            <div class="warning-summary-row">
              <p class="warning-summary-col">
                <i class="icon icon-info"></i>
                <span class="line-name"
                  >异常处理
                  <em>{{ detailInfo.exceptionCount }}次</em>
                </span>
              </p>
              <p class="warning-summary-col">
                <i class="icon icon-success"></i>
                <span class="line-name"
                  >违纪状态
                  <em :class="{ 'color-danger': isBreach }">
                    {{ isBreach ? "违纪" : "正常" }}</em
                  >
                </span>
              </p>
            </div>
            <div class="summary-bg">
              <div class="summary-bg-line"></div>
              <div class="summary-bg-line"></div>
              <div class="summary-bg-spin"></div>
              <div class="summary-bg-spin"></div>
              <div class="summary-bg-spin"></div>
              <div class="summary-bg-spin"></div>
            </div>
          </div>
        </div>
        <div class="warning-content">
          <div class="warning-videos">
            <div
              v-for="item in viewVideos"
              :key="item.liveUrl"
              class="student-video-item"
            >
              <div class="student-video-container">
                <div class="student-video-tips">{{ item.name }}</div>
                <flv-media :ref="item.ref" :live-url="item.liveUrl"></flv-media>
              </div>
            </div>
          </div>
          <!-- track -->
          <div class="warning-track">
            <h3 class="warning-track-title">
              <i class="icon icon-track"></i>考试轨迹
            </h3>
            <div
              class="warning-track-item"
              v-for="log in detailInfo.examStudentLogList"
              :key="log.id"
            >
              <div
                :class="[
                  'warning-track-type',
                  log.viewType === 'common' ? 'type-common' : 'type-exception',
                ]"
              >
                <i :class="['icon', `icon-track-${log.viewType}`]"></i>
              </div>
              <div class="warning-track-body">
                <div class="warning-track-info">
                  <div class="warning-track-info-title">
                    <template v-if="log.type === 'BREACH_HANDLE'">
                      <span v-if="log.breachLogStatus">已撤销</span>
                    </template>
                    <h3>{{ log.title }}</h3>
                  </div>
                  <p v-if="log.desc">{{ log.desc }}</p>
                  <p>
                    时间段：
                    <span v-if="log.startTime">{{ log.startTime }} ~ </span>
                    <span>{{ log.endTime }}</span>
                  </p>
                  <p v-if="log.durationTime">
                    持续时长约：{{ log.durationTime }}
                  </p>
                </div>
                <ul class="warning-track-media" v-if="log.photos">
                  <li v-for="(photo, pindex) in log.photos" :key="pindex">
                    <img :src="photo" @click="toViewImg(photo)" />
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- image-preview -->
    <simple-image-preview
      :cur-image="curImage"
      ref="SimpleImagePreview"
    ></simple-image-preview>
  </div>
</template>

<script>
import SimpleImagePreview from "@/components/imagePreview/SimpleImagePreview";
import FlvMedia from "../common/FlvMedia";
import { invigilateDetail, warningStudentDetail } from "@/api/invigilation";
import {
  formatDate,
  timeNumberToText,
  objTypeOf,
  snakeToHump,
} from "@/utils/utils";
import { mapState } from "vuex";

export default {
  name: "patrol-warning-detail",
  components: { FlvMedia, SimpleImagePreview },
  data() {
    return {
      examRecordId: this.$route.params.examRecordId,
      detailInfo: {},
      curDetail: {},
      serialIds: [],
      exceptionSummary: [],
      viewVideos: [],
      viewVideoReady: false,
      holding: false,
      curImage: { imgSrc: "" },
    };
  },
  computed: {
    ...mapState("invigilation", ["detailIds", "liveDomains"]),
    isBreach() {
      return (
        !this.detailInfo.breachStatus && this.detailInfo.breachStatus !== null
      );
    },
  },
  watch: {
    $route: {
      handler() {
        this.initData();
      },
    },
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      this.examRecordId = this.$route.params.examRecordId;
      await this.getInvigilateDetail().catch(() => {});
      await this.getStudentVideo().catch(() => {});
      this.holding = false;
    },
    async getStudentVideo() {
      this.viewVideos = [];
      const res = await warningStudentDetail({
        examRecordId: this.examRecordId,
      });
      const orderSources = [
        "CLIENT_CAMERA",
        "CLIENT_SCREEN",
        "MOBILE_FIRST",
        "MOBILE_SECOND",
      ];
      const sourceNames = {
        CLIENT_CAMERA: "电脑摄像头",
        CLIENT_SCREEN: "考生屏幕",
        MOBILE_FIRST: "手机主机位",
        MOBILE_SECOND: "手机辅机位",
      };

      let records = {};
      res.data.data.forEach((item, index) => {
        const domain = this.liveDomains[index] || this.liveDomains[0];
        item.liveUrl = item.liveUrl
          ? `${domain}/live/${item.liveUrl.toLowerCase()}.flv`
          : "";
        item.name = sourceNames[item.source];
        item.ref = snakeToHump(item.source) + "Video";
        records[item.source] = item;
      });

      orderSources.forEach((source) => {
        if (records[source]) {
          this.viewVideos.push(records[source]);
        }
      });
      // 展示所有
      // this.viewVideos = orderSources.map((source) => {
      //   return (
      //     records[source] || {
      //       liveUrl: null,
      //       source,
      //       name: sourceNames[source],
      //       ref: snakeToHump(source) + "Video",
      //     }
      //   );
      // });
      this.initSubscribeVideo();
    },
    async getInvigilateDetail() {
      const res = await invigilateDetail(this.examRecordId);
      this.detailInfo = res.data.data;
      this.detailInfo.examStudentLogList = this.parseStudentLogs(
        this.detailInfo.examStudentLogList
      );
      this.exceptionSummary = this.detailInfo.examStudentLogList
        .filter((item) => item.viewType === "warning")
        .slice(0, 3);
    },
    parseStudentLogs(examStudentLogList) {
      const statusTypes = {
        common: [
          "FIRST_START",
          "RESUME_START",
          "IN_PROCESS",
          "PREPARE",
          "ANSWERING",
          "BREAK_OFF",
          "RESUME_PREPARE",
          "FINISHED",
          "FIRST_PREPARE",
        ],
        warning: [
          "FACE_COUNT_ERROR",
          "FACE_COMPARE_ERROR",
          "EYE_CLOSE_ERROR",
          "LIVENESS_ACTION_ERROR",
          "REALNESS",
          "NONE",
          // exception:
          "NET_TIME_OUT",
          "MACHING_STOP",
          "NET_TIME_BREAK",
          "SOFTWARE_STOP",
          "POWER_CUT",
          "BREACH_HANDLE",
          "BREACH_REVOKE",
        ],
      };
      const transformInfo = {
        FIRST_START: "身份识别",
        ANSWERING: "进入考试",
        RESUME_START: "身份识别",
      };
      let statusTypeMap = {};
      Object.keys(statusTypes).map((k) => {
        statusTypes[k].map((item) => {
          statusTypeMap[item] = k;
        });
      });

      const logs = examStudentLogList.map((item) => {
        let info = { ...item };
        info.endTime = formatDate("HH:mm:ss", new Date(info.createTime));
        info.viewType = statusTypeMap[info.type] || "common";
        const content = info.info.split(/【|】/);
        if (content.length === 3) {
          info.title = content[1];
          info.desc = content[2];
        } else {
          info.title = transformInfo[info.type] || content[0];
        }
        if (info.remark && info.remark.includes('{"')) {
          info.remark = JSON.parse(info.remark);
          if (info.remark["MIN_CREATE_TIME"]) {
            info.startTime = formatDate(
              "HH:mm:ss",
              new Date(info.remark["MIN_CREATE_TIME"])
            );
            info.durationTime = timeNumberToText(
              info.createTime - info.remark["MIN_CREATE_TIME"]
            );
          }

          let photos = [];
          Object.keys(info.remark).map((key) => {
            if (key.includes("PHOTO")) {
              const kPhotos =
                objTypeOf(info.remark[key]) === "array"
                  ? info.remark[key]
                  : [info.remark[key]];
              photos = [...photos, ...kPhotos];
            }
          });
          info.photos = photos;
        } else if (info.updateTime) {
          info.startTime = formatDate("HH:mm:ss", new Date(info.createTime));
          info.endTime = formatDate("HH:mm:ss", new Date(info.updateTime));
          info.durationTime = timeNumberToText(
            info.updateTime - info.createTime
          );
        }

        // 撤销违纪的特别处理
        if (item.type === "BREACH_HANDLE" && item.title.includes('{"')) {
          const tinfo = JSON.parse(item.title);
          info.breachLogStatus = tinfo.breachLogStatus;
        }
        return info;
      });
      return logs;
    },
    changeStudent(type) {
      let index = this.detailIds.indexOf(this.examRecordId);
      if (type) {
        if (index >= this.detailIds.length - 1) {
          this.$message.error("当前没有下一个学生了");
          return;
        }
        index++;
      } else {
        if (index <= 0) {
          this.$message.error("当前没有上一个学生了");
          return;
        }
        index--;
      }

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

      this.closeSubscribeVideo();
      console.log(this.detailIds[index]);

      this.$router.replace({
        name: "PatrolWarningDetail",
        params: {
          examRecordId: this.detailIds[index],
        },
      });
    },
    toViewImg(photo) {
      this.curImage = { imgSrc: photo };
      this.$refs.SimpleImagePreview.open();
    },
    // video relative
    initSubscribeVideo() {
      this.viewVideoReady = true;
    },
    closeSubscribeVideo() {
      this.viewVideoReady = false;
    },
    videoMutedChange() {
      this.viewVideos
        .filter((vv) => vv.liveUrl)
        .forEach((vv) => {
          let res = this.$refs[vv.ref][0].mutedPlayer(true);
          if (res) vv.muted = true;
        });
    },
    goBack() {
      window.history.go(-1);
    },
  },
};
</script>
