<template>
  <div class="safe">
    <!-- <div class="topCard card">
      <el-scrollbar
        style="width: 100%"
        wrap-style="width:100%"
        view-class="scrollbarC"
      >
        <div
          v-for="item in warnList"
          :key="item"
          class="card item"
          @dblclick="stationList(item)"
          :style="{ backgroundColor: item.isOpened == 0 ? '#f59f9f' : '' }"
        >
          <div class="title">
            {{
              item.category1 == "SYZ"
                ? item.stationName
                : item.shortStationName + item.windturbineCode
            }}
          </div>
          <div class="warn_content">{{ item.alertText }}</div>
          <div class="warn_btn">
            {{ item.lastUpdateTime }}
            <el-button
              style="width: 44px"
              size="mini"
              @click="closeWarnlist(item)"
              >确认</el-button
            >
          </div>
        </div>
      </el-scrollbar>
    </div> -->
    <div class="bottomCard">
      <div class="cardLine">
        <div class="lineItem card">
          <Safecom
            title="风机报警"
            deviceType="windturbine"
            alarmType="windturbine"
          />
        </div>
        <div class="lineItem card">
          <Safecom
            title="风机预警"
            deviceType="windturbine"
            alarmType="custom"
          />
        </div>
      </div>
      <div class="cardLine">
        <div class="lineItem card">
          <Safecom
            title="光伏报警"
            deviceType="inverter"
            alarmType="inverter"
          />
        </div>

        <div class="lineItem card">
          <Safecom title="光伏预警" deviceType="inverter" alarmType="custom" />
        </div>
        <!-- <div class="lineItem card">
          <Safecom
            title="升压站事件"
            deviceType="booststation"
            alarmType="custom"
          />
        </div> -->
      </div>
      <div class="cardLine">
        <div class="lineItem card" style="height: 100%">
          <Safecom
            title="升压站报警"
            deviceType="booststation"
            alarmType="booststation"
          />
        </div>
        <!-- <div class="lineItem card">
          <Safecom
            title="升压站事件"
            deviceType="booststation"
            alarmType="custom"
          />
        </div> -->
      </div>
    </div>
    <!-- <div v-dialogdrag>
      <el-dialog
        v-model="centerDialogVisible"
        :title="doubleClickVal?.windturbineName || doubleClickVal?.stationName"
        width="60%"
        center
      >
        <el-table
          :data="tableData"
          height="500px"
          style="width: 100%; margin-top: 10px"
        >
          <el-table-column prop="alertTime" label="时间" width="150px" />
          <el-table-column prop="stationName" label="场站" width="150px" />
          <el-table-column prop="alertText" label="报警信息" />
          <el-table-column prop="rank" label="级别" width="100px">
            <template #default="scope">
              {{ tableFilter(scope.row.rank) }}
            </template>
          </el-table-column>
          <el-table-column prop="messageType" label="类型" width="100px">
            <template #default="scope">
              {{ messageTypeFilter(scope.row.messageType) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            layout="total, prev, pager, next"
            hide-on-single-page
            :current-page="query.page"
            :page-size="query.limit"
            :total="query.pageTotal"
            @current-change="handlePageChange"
          ></el-pagination>
        </div>
      </el-dialog>
    </div> -->
  </div>
</template>
<script setup>
import {
  ref,
  onBeforeMount,
  onMounted,
  reactive,
  nextTick,
  watch,
  computed,
  h,
  warn,
} from "vue";
import {
  alarm_fault_recent,
  alarm_fault_top,
  get_fault_confirm,
  alarm_history,
} from "/@/api/api.js";
import dayjs from "dayjs";
import Safecom from "./safecomponent.vue";
import { ElNotification, ElButton } from "element-plus";
import { common } from "/@/composables/common";
import { useStore } from "vuex";
import { dataAdapterInit } from "@/websocket/index.js";
const store = useStore();

let Notifica = null;
const warnTime = computed(() => store.state.warnTime);
const warnList = computed(() => store.state.warningList);
const windowSetInterval = computed(() => store.state.warnInterval);
const isStation = computed(() => store.getters.isStation);
const synth = window.speechSynthesis;
const msg = new SpeechSynthesisUtterance();
const { username, system, getenableWarn } = common();
onMounted(async () => {
  //   dataAdapterInit();
  await getenableWarn();
  if (!windowSetInterval.value) {
    await init();
  }
});

const init = async () => {
  await fearch(formatTime(new Date(new Date() - 12 * 60 * 60 * 1000)));
  let Interval = window.setInterval(async () => {
    await fearch(formatTime(new Date(new Date() - 12 * 60 * 60 * 1000)));
  }, 10000);
  store.dispatch("actionsWarnInterval", Interval);
};

const centerDialogVisible = ref(false);
const tableData = ref([]);
const doubleClickVal = ref(null);
const Notification = (item) => {
  Notifica = ElNotification({
    type: "warning",
    title: item.windturbineName,
    // dangerouslyUseHTMLString: true,
    message: item.alertText,
    position: "bottom-right",
    duration: warnTime.value * 1000,
  });
};
const fearch = async (dateTime) => {
  //   const data = await alarm_fault_recent({ faulttime: dateTime });
  //   const warnListKeyArr = [];
  //   for (const k of warnList.value) {
  //     warnListKeyArr.push(k.id);
  //   }
  //   const { enableWarn, enableSpeak } = system.value;
  //   for (const e of data) {
  //     if (!warnListKeyArr.includes(e.id)) {
  //       enableWarn && (await Notification(e));
  //       enableSpeak &&
  //         (await handleSpeak(
  //           `${e.windturbineName || e.stationName}${e.alertText}`
  //         ));
  //       setTimeout(() => {
  //         store.dispatch("actionsWarning", e);
  //       }, 0);
  //     }
  //   }
};
// 双击弹出风机报警table
const query = reactive({
  page: 1,
  limit: 10,
  pageTotal: null,
});
const stationList = async (Val) => {
  centerDialogVisible.value = true;
  doubleClickVal.value = Val;
  await getAlarmHistoryt();
};
// 获取历史记录表
const getAlarmHistoryt = async () => {
  const endtime = doubleClickVal.value.lastUpdateTime;
  const params = {
    pagenum: query.page,
    pagesize: query.limit,
    stationid: doubleClickVal.value.stationId,
    windturbineid: doubleClickVal.value.windturbineId,
    category1: "",
    category2: "",
    rank: "",
    starttime: formatTime(
      new Date(new Date(endtime) - 1 * 24 * 60 * 60 * 1000)
    ),
    endtime: endtime,
  };
  const { data } = await alarm_history(params);
  query.pageTotal = data?.total;
  tableData.value = data?.records;
};
const close = () => {
  Notifica.close();
};
//点击消失
const closeWarnlist = (item) => {
  warnList.value.forEach((e, i) => {
    if (e.id == item.id) {
      warnList.value.splice(i, 1);
    }
  });
  const res = get_fault_confirm({
    faultHistoryId: item.id,
    confirmType: 3,
    userName: username,
    snapId: item.snapID,
  });
};
// 播放声音
/**
 *  text – 要合成的文字内容，字符串
 * lang – 使用的语言，字符串， 例如：“zh-cn”
 * voiceURI – 指定希望使用的声音和服务，字符串
 * volume – 声音的音量，区间范围是0到1，默认是1
 * rate – 语速，数值，默认值是1，范围是0.1到10，表示语速的倍数，例如2表示正常语速的两倍。
 * pitch – 表示说话的音高，数值，范围从0（最小）到2（最大）。默认值为1
 */
const handleSpeak = (text) => {
  msg.text = text;
  msg.lang = "zh-CN";
  msg.volume = "1";
  msg.rate = 0.85;
  msg.pitch = 0.5;
  synth.speak(msg);
};
// 语音停止
const handleStop = (e) => {
  msg.text = e;
  msg.lang = "zh-CN";
  synth.cancel(msg);
};
// 分页导航
const handlePageChange = (val) => {
  query.page = val;
  getAlarmHistoryt();
};
// 时间格式化
const formatTime = (val) => {
  return dayjs(val).format("YYYY-MM-DD HH:mm:ss");
};
// // 格式化
// const obj = {
//   1: "低级",
//   2: "中低级",
//   3: "中级",
//   4: "中高级",
//   5: "高级",
// };
// const messageTypeObj = {
//   true: "触发",
//   false: "解除",
// };
// const rankFilter = (val) => {
//   return obj[val];
// };
// const stateFilter = (val) => {
//   return messageTypeObj[val];
// };
// const messageTypeFilter = (val) => {
//   return messageTypeObj[val];
// };
</script>

<style lang="scss" scoped>
.safe {
  width: 100%;
  height: 100%;
  .topCard {
    height: 24vh;
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-content: flex-start;

    .item {
      width: 194px;
      height: 90px;
      padding: 6px 10px;
      margin: 5px;
      display: flex;
      background-color: #f55d5d;
      flex-direction: column;
      -moz-user-select: none;
      -webkit-user-select: none;
      user-select: none;
      cursor: pointer;

      .title {
        color: #fff;
        font-size: 14px;
      }

      .warn_content {
        flex: 1;
        font-size: 12px;
        color: rgb(133, 133, 133);
        line-height: 1.3;
        color: #fff;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .warn_btn {
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        color: #fff;

        .el-button--mini {
          min-height: 20px;
          padding: 0px;
        }
      }
    }
  }

  .bottomCard {
    display: flex;
    align-items: center;
    width: 100%;
    height: 100%;
    justify-content: space-around;
    .cardLine {
      width: calc(100% / 3 - 30px);
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      .lineItem {
        width: 100%;
        height: calc(100% / 2 - 26px);
      }
    }
  }
}

.card {
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  overflow: hidden;
  color: #303133;
  -webkit-transition: 0.3s;
  transition: 0.3s;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
</style>
<style lang="scss">
.notificatBox {
  width: 100%;

  .notificatP {
    color: rgb(7, 7, 7);
  }

  .btn {
    display: flex;
    justify-content: flex-end;
  }
}

.scrollbarC {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: flex-start;
}

.bottomCard {
  .el-table th {
    background-color: #ffffff !important;
  }
}
</style>
