import { mapState } from "vuex";
import {
  getInviTypesOption,
  getInviAreaOption,
  getInviTimeOption,
  getInviMapOption,
} from "./chartOpt";
import {
  examInvigilationCount,
  examInvigilationWarnDistribution,
  examInvigilationWarnTrend,
  examInvigilationVideoRandomList,
  examInvigilationWarnMessage,
  examinationMonitorMapList,
  examinationMonitorAreaList,
} from "@/api/invigilation";
// import {
//   examInvigilationCount,
//   examInvigilationWarnDistribution,
//   examInvigilationWarnTrend,
//   examInvigilationVideoRandomList,
//   examInvigilationWarnMessage,
//   examinationMonitorMapList,
//   examinationMonitorAreaList,
// } from "./datas";
import { calcSum } from "@/utils/utils";

export default {
  data() {
    return {
      colorType: "dark",
      schoolName: "",
      summary: {
        onlineCount: "",
        waitingCount: "",
        examingCount: "",
        breachCount: "",
        warnCount: "",
        id: "",
        name: "",
        code: "",
      },
      studentVideoList: [],
      inviMapList: [],
      inviMapChartOption: null,
      inviTypesList: [],
      inviTypesChartOption: null,
      inviAreaList: [],
      inviAreaChartOption: null,
      inviTimeList: [],
      inviTimeChartOption: null,
      inviStudentWainList: [],
      curMapAreaInd: 0,
      videoIsLargeView: false,
      // setTs
      setTsMap: {
        summary: [],
        common: [],
        studengWain: [],
        timeTrend: [],
        areaMap: [],
        areaMapDet: [],
      },
    };
  },
  computed: {
    ...mapState("invigilation", ["liveDomains"]),
    isFullScreen() {
      return this.$store.state.isFullScreen;
    },
  },
  mounted() {
    this.initData();
  },
  beforeDestroy() {
    this.clearSetTs();
  },
  methods: {
    initData() {
      this.intervalSummary();
      this.intervalCommonData();
      this.intervalStudentWain();
      this.intervalTimeTrend();
      this.intervalMap();
    },
    addSetTime(typeName, action, time = 1 * 1000) {
      this.setTsMap[typeName].push(setTimeout(action, time));
    },
    clearSetTs(typeName) {
      if (typeName) {
        if (!this.setTsMap[typeName] || !this.setTsMap[typeName].length) return;
        this.setTsMap[typeName].forEach((t) => clearTimeout(t));
        this.setTsMap[typeName] = [];
        return;
      }
      Object.keys(this.setTsMap).forEach((k) => {
        this.setTsMap[k].forEach((t) => clearTimeout(t));
        this.setTsMap[k] = [];
      });
    },
    videoAllMuted() {
      this.$refs.InvigilationStudent.forEach((refInst) => {
        refInst.mutedPlayer(true);
      });
    },
    videoViewChange(isLarge) {
      this.videoIsLargeView = isLarge;
    },
    // interval
    async intervalSummary() {
      const typeName = "summary";
      this.clearSetTs(typeName);

      await this.getSummary();
      this.addSetTime(typeName, this.intervalSummary, 3 * 1000);
    },
    async intervalCommonData() {
      const typeName = "common";
      this.clearSetTs(typeName);

      await this.getInviTypesList();
      await this.getInviAreaList();
      await this.getStudentVideoList();

      this.addSetTime(typeName, this.intervalCommonData, 10 * 1000);
    },
    async intervalStudentWain() {
      const typeName = "studengWain";
      this.clearSetTs(typeName);

      await this.getStudentWainList();
      this.addSetTime(typeName, this.intervalStudentWain, 5 * 1000);
    },
    async intervalTimeTrend() {
      const typeName = "timeTrend";
      this.clearSetTs(typeName);

      await this.getInviTimeList();
      this.addSetTime(typeName, this.intervalTimeTrend, 60 * 1000);
    },
    async intervalMap() {
      const typeName = "areaMap";
      this.clearSetTs(typeName);

      await this.getMapList();
      this.intervalMapDet();
      let inTime = this.inviMapList.length * 5 * 1000;
      inTime = inTime || 60 * 1000;
      this.addSetTime(typeName, this.intervalMap, inTime);
    },
    intervalMapDet() {
      const typeName = "areaMapDet";
      this.clearSetTs(typeName);
      if (!this.inviMapList.length) return;

      if (this.curMapAreaInd !== 0) {
        this.$refs.InviMapChart.dispatchAction({
          type: "hideTip",
        });
        this.$refs.InviMapChart.dispatchAction({
          type: "mapUnSelect",
          dataIndex: this.curMapAreaInd - 1,
        });
      }
      this.$refs.InviMapChart.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: this.curMapAreaInd,
      });
      this.$refs.InviMapChart.dispatchAction({
        type: "mapSelect",
        dataIndex: this.curMapAreaInd,
      });

      this.curMapAreaInd++;
      if (this.curMapAreaInd >= this.inviMapList.length) {
        this.curMapAreaInd = 0;
      } else {
        this.addSetTime(typeName, this.intervalMapDet, 5 * 1000);
      }
    },
    // fetch action
    getMaxNum(nums) {
      return Math.max.apply(null, nums);
    },
    transformAreaName(name) {
      return name.replace("省", "").replace("市", "");
    },
    async getSummary() {
      // interval 3s
      const res = await examInvigilationCount();
      const data = res.data.data;
      this.summary = Object.assign({}, this.summary, data);
    },
    async getStudentVideoList() {
      if (this.videoIsLargeView) return;
      // interval 10s
      const res = await examInvigilationVideoRandomList({ randomNum: 4 });
      const domainLen = this.liveDomains.length;
      this.studentVideoList = res.data.data.map((item, index) => {
        const domain = domainLen ? this.liveDomains[index % domainLen] : "";
        item.liveUrl = item.monitorLiveUrl
          ? `${domain}/live/${item.monitorLiveUrl.toLowerCase()}.flv`
          : "";
        item.progress = item.progress ? Math.round(item.progress * 100) : 0;
        return item;
      });
    },
    async getMapList() {
      // interval list 5s
      const res = await examinationMonitorMapList();
      const dataList = res.data.data;
      this.inviMapList = dataList.map((item) => {
        item.selected = false;
        item.province = this.transformAreaName(item.province);
        return item;
      });
      this.inviMapChartOption = getInviMapOption(this.inviMapList);
    },
    async getInviTypesList() {
      // interval 10s
      const res = await examInvigilationWarnDistribution();
      const dataList = res.data.data;
      const maxNum = this.getMaxNum(dataList.map((item) => item.warnCount));
      let inviTypesList = dataList.map((item) => {
        return {
          ...item,
          percentage: Math.floor((100 * item.warnCount) / maxNum),
        };
      });
      inviTypesList.sort((a, b) => b.warnCount - a.warnCount);
      this.inviTypesList = inviTypesList;
      this.inviTypesChartOption = getInviTypesOption(this.inviTypesList);
    },
    async getInviAreaList() {
      // interval 10s
      const res = await examinationMonitorAreaList();
      const dataList = res.data.data;
      const maxNum = this.getMaxNum(dataList.map((item) => item.warnCount));
      let inviAreaList = dataList.map((item) => {
        item.province = this.transformAreaName(item.province);
        return {
          ...item,
          percentage: Math.floor((100 * item.warnCount) / maxNum),
        };
      });
      inviAreaList.sort((a, b) => b.warnCount - a.warnCount);
      this.inviAreaList = inviAreaList.slice(0, 5);
      const otherAreaCount = calcSum(
        inviAreaList.slice(5).map((item) => item.warnCount)
      );
      const chartDataList = [
        ...this.inviAreaList,
        { country: "中国", province: "其他", warnCount: otherAreaCount },
      ];

      this.inviAreaChartOption = getInviAreaOption(chartDataList);
    },
    async getInviTimeList() {
      // interval 60s
      const res = await examInvigilationWarnTrend();
      const dataList = res.data.data;
      this.inviTimeList = dataList;
      this.inviTimeChartOption = getInviTimeOption(dataList, this.colorType);
    },
    async getStudentWainList() {
      // // interval 5s
      const res = await examInvigilationWarnMessage();
      const dataList = res.data.data;
      this.inviStudentWainList = dataList;
    },
  },
};
