<template>
  <div class="center-list">
    <div class="home-header">
      <h1>考情监控中心</h1>
    </div>
    <div class="home-left center-left">
      <div class="home-all box">
        <div class="box-body">
          <div class="all-item">
            <span>{{ curExamState.bm }}</span>
            <span>报名人数</span>
          </div>
          <div class="all-item">
            <span>{{ curExamState.ykkc }}</span>
            <span>应考考次</span>
          </div>
        </div>
      </div>
      <div class="home-category box">
        <div class="box-body">
          <div class="box-title">
            <h2>报考类型统计</h2>
          </div>
          <div class="category-chart">
            <div style="width: 100%; height: 100%" id="category_chart"></div>
            <!-- <v-chart
                            :options="categoryChartOption"
                            v-if="categoryChartOption"
                        ></v-chart> -->
          </div>
          <div class="category-bar">
            <ul>
              <li v-for="(item, index) in bkCategoryStat" :key="index">
                <span>{{ item.name }}</span>
                <span>{{ item.value }}%</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <div class="center-body">
      <div class="center-infos">
        <div class="infos-right">
          <ul>
            <!-- <li class="li-link">
                            <span>连接数：{{ curExamState.link }}</span>
                        </li> -->
            <li class="li-login">
              <span>已登录：{{ curExamState.login }}</span>
            </li>
            <!-- <li class="li-wait">
                            <span>待机：{{ curExamState.wait }}</span>
                        </li> -->
            <li class="li-error">
              <span>通讯故障：{{ curExamState.error }}</span>
            </li>
          </ul>
        </div>
        <div class="infos-left">
          <ul>
            <li
              v-for="exam in exams"
              :key="exam.examCode"
              :class="{
                'info-active': query.examCode === exam.examCode,
              }"
              :title="exam.name"
              @click="examChange(exam)"
            >
              {{ exam.name }}
            </li>
          </ul>
        </div>
      </div>
      <div class="center-query">
        <Form ref="listFilterForm" label-position="left" inline>
          <FormItem style="width: 100px">
            <Select
              v-model="query.province"
              @on-change="provChange"
              placeholder="全部省份"
              clearable
            >
              <Option
                v-for="(item, index) in provinces"
                :key="index"
                :value="item.id"
                >{{ item.name }}</Option
              >
            </Select>
          </FormItem>
          <FormItem style="width: 100px">
            <Select
              v-model="query.city"
              @on-change="cityChange"
              placeholder="全部城市"
              clearable
            >
              <Option
                v-for="(item, index) in cities"
                :key="index"
                :value="item.id"
                >{{ item.name }}</Option
              >
            </Select>
          </FormItem>
          <FormItem style="width: 100px">
            <Select
              v-model="query.placeCode"
              @on-change="placeChange"
              placeholder="全部考点"
              clearable
            >
              <Option
                v-for="(item, index) in places"
                :key="index"
                :value="item.id"
                >{{ item.name }}</Option
              >
            </Select>
          </FormItem>
          <FormItem style="width: 100px">
            <Select v-model="query.roomCode" placeholder="全部考场" clearable>
              <Option
                v-for="(item, index) in examRooms"
                :key="index"
                :value="item.id"
                >{{ item.name }}</Option
              >
            </Select>
          </FormItem>
          <FormItem style="width: 160px">
            <Input
              v-model="query.placeName"
              placeholder="考点搜索"
              clearable
            ></Input>
          </FormItem>
          <FormItem>
            <div class="btn-search" @click="toPage(1)">搜索</div>
          </FormItem>
        </Form>
      </div>
      <div class="center-table">
        <Table
          class="table"
          :columns="columes"
          :data="placeInfoList"
          disabled-hover
        ></Table>
        <Page
          class="center-page"
          :current="pageNumber"
          :total="total"
          @on-change="toPage"
        ></Page>
      </div>
    </div>

    <div class="center-place">
      <div class="box long-box">
        <div class="box-body">
          <div class="place-legend">
            <ul>
              <li><span>应考</span></li>
              <li
                v-for="(item, index) in placeLegend"
                :key="index"
                @click="sortPlace(item)"
              >
                <span
                  >{{ item.name }}
                  <b v-if="item.hasSort">{{
                    item.isSort ? "（倒序）" : "（顺序）"
                  }}</b>
                </span>
              </li>
            </ul>
          </div>
          <div style="width: 100%; height: 100%" id="place_chart"></div>
        </div>
      </div>
    </div>
    <div class="center-footer home-footer">
      <p>
        武汉启明泰和软件服务有限公司 copyright@2011-2020 www.qmth.com.cn, All
        Rights Reserved
      </p>
    </div>
  </div>
</template>

<script>
// 临时数据
// import { bkCategoryStat, placeStat, placeInfoList } from './data';

import pageMixins from "./mixins";
import { init } from "echarts";
import { axios } from "../../libs/http";

const placeLegend = [
  {
    name: "已登录",
    type: "login",
    hasSort: false,
    isSort: false,
  },
  {
    name: "通讯故障",
    type: "error",
    hasSort: false,
    isSort: false,
  },
];

export default {
  name: "center-list",
  mixins: [pageMixins],
  data() {
    return {
      query: {
        examCode: "",
        province: "",
        city: "",
        placeCode: "",
        roomCode: "",
        placeName: "",
      },
      curExamState: {
        link: 0,
        login: 0,
        wait: 0,
        error: 0,
        bm: 0,
        ykkc: 0,
      }, // 当前考试客户端状态统计数据
      provinces: [],
      cities: [],
      places: [],
      examRooms: [],
      exams: [],
      placeInfoList: [],
      // map
      placeStat: [],
      bkCategoryStat: [],
      categoryChartOption: "",
      placeChartOption: "",
      mapChartOpition: "",
      placeLegend,
      // table
      pageNumber: 1,
      total: 50,
      columes: [
        {
          title: "考试",
          key: "examName",
          minWidth: 200,
        },
        {
          title: "考点",
          key: "placeName",
          minWidth: 150,
        },
        {
          title: "考场",
          key: "roomName",
          minWidth: 150,
        },
        {
          title: "科目",
          key: "courseName",
          minWidth: 100,
        },
        {
          title: "应考人数",
          key: "ykCount",
          minWidth: 100,
        },
        {
          title: "登录数",
          key: "loginCount",
          minWidth: 100,
        },
        {
          title: "通讯故障数",
          key: "contactErrorCount",
          minWidth: 100,
        },
      ],
    };
  },
  mounted() {
    this.getExamList();
  },
  methods: {
    getExamList() {
      axios
        .post("/system/examRoomMonitor/getExamInProgress")
        .then((response) => {
          let data = response.data.data;
          if (data) {
            ``;
            this.exams = data.map((item) => {
              return {
                id: item.id,
                name: item.name,
                examCode: item.examCode,
                startTime: item.startTime,
                endTime: item.endTime,
              };
            });
            this.examChange(data[0]);
            this.setTimeMission();
          }
        });
    },
    setTimeMission() {
      const now = Date.now();
      this.exams.forEach((element) => {
        const endTime = new Date(element.endTime).getTime();
        if (endTime > now) {
          setTimeout(() => {
            this.endExam(element);
          }, endTime - now);
        }
      });
    },
    endExam(exam) {
      this.$Notice.open({
        title: "考试结束提醒",
        desc: `【${exam.name}】考试已经结束！`,
      });
      const index = this.exams.findIndex((el) => el.examCode === exam.examCode);
      this.exams.splice(index, 1);
      if (this.query.examCode === exam.examCode && this.exams.length) {
        this.examChange(this.exams[0]);
      }
    },
    getProvinceList() {
      axios
        .post("/system/examRoomMonitor/getProvinceByExamCode", {
          examCode: this.query.examCode,
        })
        .then((response) => {
          let data = response.data.data;
          if (data) {
            this.provinces = data.map((item) => {
              return {
                id: item.id,
                name: item.name,
              };
            });
          }
        });
    },
    getCityList() {
      if (!this.query.province) return;

      axios
        .post("/system/examRoomMonitor/getCityByProvince", {
          province: this.query.province,
        })
        .then((response) => {
          let data = response.data.data;
          if (data) {
            this.cities = data.map((item) => {
              return {
                id: item.id,
                name: item.name,
              };
            });
          }
        });
    },
    getPlaceList() {
      axios
        .post(
          "/system/examRoomMonitor/getPlaceByProvinceAndCityAndExamCode",
          this.query
        )
        .then((response) => {
          let data = response.data.data;
          if (data) {
            this.places = data.map((item) => {
              return {
                id: item.value,
                name: item.name,
              };
            });
          }
        });
    },
    getExamRoomList() {
      if (!this.query.placeCode) return;

      axios
        .post("/system/kj/hz/getRoomByPlaceCode", {
          placeCode: this.query.placeCode,
          examCode: this.query.examCode,
        })
        .then((response) => {
          let data = response.data.data;
          if (data) {
            this.examRooms = data.map((item) => {
              return {
                id: item.value,
                name: item.name,
              };
            });
          }
        });
    },
    getBkStatList() {
      axios
        .post("/system/examRoomMonitor/queryCountInfo", {
          ...this.query,
        })
        .then((response) => {
          let data = response.data.data;
          if (data) {
            this.curExamState = {
              link: data.countLj,
              login: data.countDl,
              wait: data.countDj,
              error: data.countGz,
              bm: data.countBm,
              ykkc: data.countYkkc,
            };
          }
        });
    },
    getCategoryStatList() {
      axios
        .post("/system/examRoomMonitor/queryCategoryPercent", {
          examCode: this.query.examCode,
        })
        .then((response) => {
          let data = response.data.data;
          if (data) {
            let bkCategoryData = data.map((el) => {
              return {
                name: el.category,
                value: Math.round(el.percent * 100),
              };
            });
            // 防止比例总和溢出100%
            const lastTotal = bkCategoryData
              .slice(0, -1)
              .map((el) => el.value)
              .reduce(function (a, b) {
                return a + b;
              });
            bkCategoryData[bkCategoryData.length - 1].value = 100 - lastTotal;
            this.bkCategoryStat = bkCategoryData;
            // 渲染报考类型统计饼状图
            this.renderCategoryChart();
          }
        });
    },
    getPlaceStatList() {
      axios
        .post("/system/examRoomMonitor/queryPlacePercent", {
          examCode: this.query.examCode,
        })
        .then((response) => {
          let data = response.data.data;
          if (data) {
            this.placeStat = data.map((item) => {
              return {
                name: item.placeName,
                login: item.percentDl,
                wait: item.percentYk,
                error: item.percentYc,
              };
            });

            // 渲染全国考点情况统计柱状图
            this.sortPlace(this.placeLegend[1]);
          }
        });
    },
    renderCategoryChart() {
      let categoryChart = init(document.getElementById("category_chart"));
      const categoryChartOption = this.getCategoryChartOption(
        this.bkCategoryStat
      );
      categoryChart.setOption(categoryChartOption);
      window.addEventListener("resize", function () {
        categoryChart.resize();
      });
    },
    renderPlaceChart() {
      let placeChart = init(document.getElementById("place_chart"));

      const placeChartOption = this.getPlaceLineChartOption(this.placeStat);
      placeChart.setOption(placeChartOption);
      placeChart.off("click");
      placeChart.on("click", this.placeChartClickHandle);
      window.addEventListener("resize", function () {
        placeChart.resize();
      });
    },
    examChange(exam) {
      this.query.examCode = exam.examCode;
      this.query.province = "";
      this.query.city = "";
      this.query.placeCode = "";
      this.query.roomCode = "";
      this.provinces = [];
      this.cities = [];
      this.places = [];
      this.examRooms = [];
      this.toPage(1);
      this.getProvinceList();
      this.getPlaceList();
      // stat data
      this.getCategoryStatList();
    },
    provChange() {
      this.query.city = "";
      this.query.placeCode = "";
      this.query.roomCode = "";
      this.cities = [];
      this.places = [];
      this.examRooms = [];
      this.getCityList();
      this.getPlaceList();
    },
    cityChange() {
      this.query.placeCode = "";
      this.query.roomCode = "";
      this.places = [];
      this.examRooms = [];
      this.getPlaceList();
    },
    placeChange() {
      this.query.roomCode = "";
      this.examRooms = [];
      this.getExamRoomList();
    },
    getList() {
      const datas = {
        ...this.query,
        curPage: this.pageNumber,
        pageSize: 10,
      };
      // console.log(datas);

      axios
        .post("/system/examRoomMonitor/pageQuery", datas)
        .then((response) => {
          let data = response.data.data;
          if (data) {
            this.placeInfoList = data.content.map((item) => {
              return {
                id: item.value,
                examName: item.examPlan.name,
                placeCode: item.placeCode,
                placeName: item.placeName,
                roomCode: item.roomCode,
                roomName: item.roomName,
                courseCode: item.courseCode,
                courseName: item.courseName,
                ykCount: item.ykCount,
                loginCount: item.loginCount,
                contactErrorCount: item.contactErrorCount,
              };
            });
            this.total = data.totalElements;
          }
        });
    },
    toPage(page) {
      this.pageNumber = page;
      this.getList();
      this.getBkStatList();
      this.getPlaceStatList();
    },
    sortPlace(item) {
      item.hasSort = true;
      this.placeLegend.map((el) => {
        if (el.name === item.name) {
          item.isSort = !item.isSort;
        } else {
          el.hasSort = false;
          el.isSort = false;
        }
      });
      const type = item.type;

      this.placeStat.sort((a, b) => {
        return item.isSort ? b[type] - a[type] : a[type] - b[type];
      });
      this.renderPlaceChart();
    },
    placeChartClickHandle(params) {
      if (["xAxis", "series"].indexOf(params.componentType) !== -1) {
        const name =
          params.componentType === "xAxis" ? params.value : params.name;
        if (this.query.placeName === name) return;
        this.query.placeName = name;
        this.query.province = "";
        this.query.city = "";
        this.query.placeCode = "";
        this.query.roomCode = "";
        this.toPage(1);
      }
    },
  },
};
</script>

<style lang="less" src="./center.less"></style>
