<template>
  <div class="patrol-warning-detail warning-detail">
    <div class="warning-detail-head">
      <div class="warning-detail-title">
        <h2>预警详情</h2>
        <el-button size="mini" icon="el-icon-arrow-left" @click="goBack">
          返回列表
        </el-button>
      </div>
      <div class="warning-detail-student">
        <div class="student-head">
          <div class="student-head-left">
            <p><i class="icon icon-user-act"></i></p>
            <p>
              <span>姓名：</span><span>{{ detailInfo.examStudentName }}</span>
            </p>
            <p>
              <span>证件号：</span><span>{{ detailInfo.identity }}</span>
            </p>
            <p>
              <span>科目（代码）：</span
              ><span>{{ detailInfo.courseNameCode }}</span>
            </p>
          </div>
          <div class="student-head-right">
            <el-button
              class="el-icon-btn"
              size="mini"
              type="primary"
              icon="el-icon-arrow-left"
              title="查看上一个"
              @click="changeStudent(0)"
              :disabled="holding"
            ></el-button>
            <el-button
              class="el-icon-btn"
              size="mini"
              type="primary"
              icon="el-icon-arrow-right"
              title="查看下一个"
              @click="changeStudent(1)"
              :disabled="holding"
            ></el-button>
          </div>
        </div>
        <div class="student-views">
          <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>
          <div class="student-video">
            <div class="student-video-item">
              <flv-media
                ref="FirstViewVideo"
                :live-url="firstViewVideo.liveUrl"
                v-if="firstViewVideoReady"
              ></flv-media>
              <div class="student-video-none" v-else>
                <i class="el-icon-video-camera-solid"></i>
              </div>
            </div>
            <div class="student-video-item">
              <flv-media
                ref="SecondViewVideo"
                :live-url="secondViewVideo.liveUrl"
                v-if="secondViewVideoReady"
              ></flv-media>
              <div class="student-video-none" v-else>
                <i class="el-icon-video-camera-solid"></i>
              </div>
            </div>
          </div>
        </div>
        <div class="student-exception">
          <ul>
            <li v-for="(log, index) in exceptionSummary" :key="index">
              <i>{{ index + 1 }}</i>
              <h4>{{ log.title }}</h4>
              <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> -->
            </li>
          </ul>
        </div>
      </div>
    </div>

    <div class="warning-detail-body">
      <div class="warning-body-head clear-float">
        <div class="warning-body-head-action">
          <h3>考试轨迹</h3>
        </div>
        <div class="warning-body-head-info summary-line">
          <p class="summary-line-item">
            <i class="line-point line-point-danger"></i>
            <span class="line-name">系统预警</span>
            <span>{{ detailInfo.warningCount }}次</span>
          </p>
          <p class="summary-line-item">
            <i class="line-point line-point-danger"></i>
            <span class="line-name">陌生人脸</span>
            <span>{{ detailInfo.multipleFaceCount }}次</span>
          </p>
          <p class="summary-line-item">
            <i class="line-point line-point-danger"></i>
            <span class="line-name">异常处理</span>
            <span>{{ detailInfo.exceptionCount }}次</span>
          </p>
          <p class="summary-line-item">
            <span></span>
            <span>
              <b>违纪状态：</b>
              <b :class="{ 'color-danger': isBreach }">
                {{ isBreach ? "违纪" : "正常" }}
              </b>
            </span>
          </p>
        </div>
      </div>
      <div class="warning-body-main">
        <div
          class="warning-history"
          v-for="log in detailInfo.examStudentLogList"
          :key="log.id"
        >
          <div class="warning-history-info">
            <h3>{{ log.title }}</h3>
            <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>
          <div
            :class="[
              'warning-history-type',
              log.viewType === 'common' ? 'type-common' : 'type-exception',
            ]"
          >
            <i
              :class="[
                'icon',
                {
                  'icon-current-step': log.viewType === 'common',
                  'icon-warning-act': log.viewType === 'warning',
                  'icon-net-break': log.viewType === 'exception',
                },
              ]"
            ></i>
          </div>
          <div class="warning-history-media">
            <ul class="media-list" v-if="log.photos">
              <li v-for="(photo, pindex) in log.photos" :key="pindex">
                <img :src="photo" />
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

export default {
  name: "patrol-warning-detail",
  components: { FlvMedia },
  data() {
    return {
      recordId: this.$route.params.recordId,
      detailInfo: {},
      curDetail: {},
      serialIds: [],
      exceptionSummary: [],
      firstViewVideo: {
        liveUrl: "",
      },
      secondViewVideo: {
        liveUrl: "",
      },
      firstViewVideoReady: false,
      secondViewVideoReady: false,
      holding: false,
    };
  },
  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.recordId = this.$route.params.recordId;
      await this.getInvigilateDetail().catch(() => {});
      await this.getStudentVideo().catch(() => {});
      this.holding = false;
    },
    async getStudentVideo() {
      const res = await warningStudentDetail({ recordId: this.recordId });
      const records = res.data.data.map((item, index) => {
        const domain = this.liveDomains[index] || "";
        item.liveUrl = item.liveUrl
          ? `${domain}/live/${item.liveUrl.toLowerCase()}.flv`
          : "";
        item.name = item.source;
        return item;
      });
      console.log(records.map((item) => item.liveUrl));
      this.firstViewVideo = records[0] || {};
      this.secondViewVideo = records[2] || {};

      if (records.length) this.initSubscribeVideo();
    },
    async getInvigilateDetail() {
      const res = await invigilateDetail(this.recordId);
      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",
        ],
      };
      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
          );
        }
        return info;
      });
      return logs;
    },
    changeStudent(type) {
      let index = this.detailIds.indexOf(this.recordId);
      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: {
          recordId: this.detailIds[index],
        },
      });
    },
    // video relative
    initSubscribeVideo() {
      if (this.firstViewVideo.liveUrl) this.firstViewVideoReady = true;
      if (this.secondViewVideo.liveUrl) this.secondViewVideoReady = true;
    },
    closeSubscribeVideo() {
      this.firstViewVideoReady = false;
      this.secondViewVideoReady = false;
    },
    goBack() {
      window.history.go(-1);
    },
  },
};
</script>
