<template>
  <div id="index" ref="appRef">
    <div
      class="bg"
      :class="
        store.state.screenNotic == 1
          ? pushFlag
            ? bottomTextRef?.urgentList.length > 0
              ? 'bg-red'
              : ''
            : ''
          : ''
      "
    >
      <dv-loading v-if="loading">Loading...</dv-loading>

      <div v-else class="host-body">
        <div class="d-flex jc-center">
          <div class="react-left">
            <span class="text fw-b">
              {{ timeInfo.dateYear }} {{ timeInfo.dateWeek }}
              {{ timeInfo.dateDay }}</span
            >
          </div>

          <dv-decoration-10 class="dv-dec-10" :color="color[1]" />
          <div class="d-flex jc-center">
            <dv-decoration-8 class="dv-dec-8" :color="color[2]" />
            <div class="title">
              <span class="title-text">{{ title }}</span>
            </div>
            <dv-decoration-8
              class="dv-dec-8"
              :reverse="true"
              :color="color[2]"
            />
          </div>
          <dv-decoration-10 class="dv-dec-10-s" :color="color[1]" />
        </div>

        <div class="d-flex secondLine">
          <div class="react-right mr-1">
            <span class="text fw-b" style="display: flex">
              <datePicker
                ref="datePickerRef"
                @timeChangeInfo="timeChangeInfo"
              />
            </span>
          </div>

          <el-dropdown placement="bottom">
            <el-icon :size="22" :color="color[1][0]" class="mt-0.5 mt5">
              <Menu />
            </el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <!-- <el-dropdown-item @click="handleClick('1')"
                  >已发送短信查询</el-dropdown-item
                >

                <el-dropdown-item @click="handleClick('2')"
                  >模拟短信发送</el-dropdown-item
                > -->
                <el-dropdown-item @click="handleClick('3')"
                  >系统配置</el-dropdown-item
                >
                <el-dropdown-item @click="handleClick('4')"
                  >报表导出</el-dropdown-item
                >
                <el-dropdown-item @click="handleClick('5')"
                  >台账导出</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div class="body-box">
          <!-- 第三行数据 -->
          <div class="content-box">
            <dv-border-box-13 :color="color[0]">
              <eventStatistics ref="eventStatisticsRef" />
            </dv-border-box-13>

            <dv-border-box-10 :color="color[0]">
              <Map ref="mapRef" />
              <!-- <center-left /> -->
            </dv-border-box-10>

            <dv-border-box-13 :color="color[0]">
              <alarm ref="alarmRef" />
              <!-- 紧急告警 -->

              <div
                class="icon"
                v-if="!(bottomTextRef?.urgentList.length == 0)"
                :color="color[0][1]"
                :class="
                  bottomTextRef?.urgentList.length > 0
                    ? 'animate-flash-red'
                    : ''
                "
                @click="drawerClick"
              >
                <!-- <WarnTriangleFilled /> -->
                <span
                  class="iconfont icon-gaojing"
                  :style="{
                    color:
                      bottomTextRef?.urgentList.length > 0
                        ? '#ff0000'
                        : color[0][1],
                  }"
                ></span>
                <span
                  class="count"
                  v-if="bottomTextRef?.urgentList.length > 0"
                  >{{
                    bottomTextRef?.urgentList.length > 99
                      ? "99+"
                      : bottomTextRef?.urgentList.length
                  }}</span
                >
              </div>
            </dv-border-box-13>
          </div>

          <!-- 第四行数据 -->
          <div class="bototm-box">
            <dv-border-box-13 :color="color[0]">
              <endpointStatistics ref="endpointStatisticsRef" />

              <!-- <bottom-left /> -->
            </dv-border-box-13>
            <dv-border-box-13 :color="color[0]">
              <informationTable
                ref="informationTableRef"
                @handleCurrentChange="handleCurrentChange"
              />
            </dv-border-box-13>
            <dv-border-box-13 :color="color[0]">
              <sendTrends ref="sendTrendsRef" />
            </dv-border-box-13>
          </div>
          <!-- 底部 -->
        </div>
      </div>
    </div>
    <bottomText
      ref="bottomTextRef"
      @handleCurrentChange="handleCurrentChange"
    />

    <!-- 已发短信查询 -->
    <smsQueries
      ref="smsQueriesRef"
      v-if="smsQueriesFlag"
      @close="smsQueriesFlag = false"
    />

    <!-- 系统配置 -->
    <Config ref="ConfigRef" @flushed="inquire" />

    <!-- 报表导出 -->
    <ReportForms ref="reportForms" />
  </div>
</template>

<!--index.vue-->
<script lang="ts" setup>
import {
  defineComponent,
  ref,
  reactive,
  onMounted,
  onUnmounted,
  onBeforeUnmount,
  watch,
} from "vue";

import { formatTime, getDateRange, stopSpeak } from "@/utils/index"; //引入封装好的
import useDraw from "@/utils/useDraw"; // 引入封装好的屏幕适配方法
import { WEEK, title, subtitle, moduleInfo, color } from "@/constant/index"; //引入封装的标题日期
import datePicker from "@/components/datePicker/index.vue";
import { Menu, BellFilled, WarnTriangleFilled } from "@element-plus/icons-vue";
//页面组件
import eventStatistics from "./components/eventStatistics.vue"; //统计事件
import endpointStatistics from "./components/endpointStatistics.vue"; //终端在线统计
import sendTrends from "./components/sendTrends.vue"; //终端在线统计
import informationTable from "./components/informationTable.vue"; //实时暂态信息
import alarm from "./components/alarm.vue"; //实时暂态信息
import Map from "./components/bdMap.vue"; //地图
import smsQueries from "./components/smsQueries.vue"; // //短信查询
import bottomText from "./components/bottomText.vue"; //边框组件
import socketClient from "@/utils/webSocketClient";
import { useStore } from "vuex";
import Config from "./components/config.vue";
import ReportForms from "./components/reportForms.vue";
import { exportLineData } from "@/api/statistics/index";
const store = useStore();
const smsQueriesRef = ref(); // 短信查询组件引用
const endpointStatisticsRef = ref(); // 终端在线统计组件引用
const informationTableRef = ref(); // 实时暂态信息组件引用
const sendTrendsRef = ref();
const ConfigRef = ref();
const eventStatisticsRef = ref();
const alarmRef = ref();
const mapRef = ref();
//开始创建webSocket客户端
const dataSocket = reactive({
  socketServe: socketClient.Instance,
});
const smsQueriesFlag = ref(false);
const pushFlag = ref(true);
const bottomTextRef = ref(); // 底部滚动组件引用
// * 加载标识
const loading = ref<boolean>(true);
// * 时间内容
const timeInfo: any = reactive({
  setInterval: 0,
  dateDay: "",
  dateYear: "",
  dateWeek: "",
});
const timeType = ref(3);
const reportForms = ref();
// 适配处理
const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw();
// 连接webSocket客户端
const init = () => {
  if (!dataSocket.socketServe) {
    console.error("WebSocket 客户端实例不存在");
    return;
  }
  dataSocket.socketServe.connect(new Date().getTime());
  dataSocket.socketServe.registerCallBack("message", (res: any) => {
    pushFlag.value = true;
    inquire();
    bottomTextRef.value?.updateData(res);
  });
};
// 打开重要告警弹框
const drawerClick = () => {
  bottomTextRef.value?.openDrawer();
};

// 生命周期
onMounted(() => {
  stopSpeak();

  cancelLoading();

  handleTime();
  // todo 屏幕适应
  windowDraw();
  calcRate();
  setTimeout(() => {
    store.dispatch("setConfig");
  }, 500);
  init();
});
const handleCurrentChange = (val: string) => {
  mapRef.value?.setIcon(val);
};
onUnmounted(() => {
  unWindowDraw();
  clearInterval(timeInfo.setInterval);
});
onBeforeUnmount(() => {
  dataSocket.socketServe?.closeWs();
});

// methods
// todo 处理 loading 展示
const cancelLoading = () => {
  setTimeout(() => {
    loading.value = false;
  }, 500);
};

// todo 处理时间监听
const handleTime = () => {
  timeInfo.setInterval = setInterval(() => {
    const date = new Date();
    timeInfo.dateDay = formatTime(date, "HH: mm: ss");
    timeInfo.dateYear = formatTime(date, "yyyy-MM-dd");
    timeInfo.dateWeek = WEEK[date.getDay()];
  }, 1000);
};
// todo 处理菜单点击事件
const handleClick = (type: string) => {
  smsQueriesFlag.value = true;

  setTimeout(() => {
    if (type === "3") {
      ConfigRef.value.open("系统配置");
    }
    if (type === "4") {
      reportForms.value.open("报表导出");
    }
    if (type === "5") {
      exportLineData().then((res: any) => {
        let blob = new Blob([res], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a"); // 创建a标签
        link.href = url;
        link.download = "台账.xlsx"; // 设置下载的文件名
        document.body.appendChild(link);
        link.click(); //执行下载
        document.body.removeChild(link);
      });
    }
  }, 100);
};

// 切换时间
const timeChangeInfo = async () => {
  inquire();
};
const inquireTimer: any = ref(null);
const inquire = async () => {
  // 清除上一次的定时器
  if (inquireTimer.value) {
    clearTimeout(inquireTimer.value);
  }

  // 设置新的定时器，延迟300毫秒执行
  inquireTimer.value = setTimeout(async () => {
    eventStatisticsRef.value.init(); //电能质量监测终端运行状态
    endpointStatisticsRef.value.init(); //各区域终端运行状态
    mapRef.value.init(); //地图
    informationTableRef.value.init(true); //暂降事件列表
    sendTrendsRef.value.init();

    alarmRef.value.init();

    // 执行完毕后重置定时器变量
    inquireTimer.value = null;
  }, 500);
};

watch(
  store.state,
  (val) => {
    timeChangeInfo();
  },
  {
    deep: true,
  }
);
</script>

<style lang="scss" scoped>
@use "@/assets/scss/index.scss";

.react-right {
  width: 460px !important;
}

.count {
  position: absolute;
  top: -8px;
  left: 23px;
  background-color: #ff2501;
  color: #fff;
  height: 15px;
  line-height: 15px;
  padding: 0 3px;
  border-radius: 40%;
  font-size: 10px;
  text-align: center;
}

.icon {
  position: absolute;
  top: 8px;
  right: 25px;
}

.significant {
  position: absolute;
  top: 12px;
  left: 15px;

  .count {
    top: -3px;
    left: 13px;
    height: 13px;
  }
}

.react-left {
  position: absolute;
  left: 140px;
  top: 30px;
  font-size: 18px;
  line-height: 35px;
}

.titles {
  margin-right: 10px;

  .react-right {
    width: 50px !important;
    line-height: 20px !important;
    font-size: 14px !important;
  }
}

.iconfont {
  font-size: 35px !important;
}
</style>
