<template>
  <div :class="classObj" class="app-wrapper">
    <!-- <div v-if="device==='mobile'&&sidebar.opened" class="drawer-bg" @click="handleClickOutside" /> -->

    <div :class="{ 'fixed-header': fixedHeader }">
      <navbar />
      <breadcrumb v-if="isHome == false" class="breadcrumb-container" />
    </div>
    <sidebar v-if="!$store.state.app.videoListMagnify" class="sidebar-container" />
    <div class="main-container">
      <app-main />
    </div>
    <!-- <el-dialog width="30%" v-for="(item, index) in warningSocketList" :visible.sync="item.show"
      :top="100 + index * 40 + 'px'" class="0" title="报警信息提示" :show-close="false" :close-on-click-modal="false">
      <div class="warning-view">
        <img style="width: 200px; margin-right: 15px" :src="item.data.imageUrls && item.data.imageUrls[0]" />
        <div class="warning-content">
          <div class="text-base text-1">
            报警线路：{{ item.data.railwayName }}
          </div>
          <div class="text-base">
            <span>{{
              item.data.alarmType == 1
              ? "泥石流"
              : item.data.alarmType == 2
                ? "异物侵限"
                : "断轨监测"
            }},</span>
            <span>{{ item.data.lineDirStr }},</span>
            <span>里程位置{{ item.data.alarmMile }}</span>
          </div>
          <div class="text-base">{{ item.data.alarmTime }}</div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer" style="display: flex; align-items: center; justify-content: center">
        <div style="margin-right: 15px" class="sp-button-submit" @click="warningSocketButton(1, index, item.data)">
          立即处理
        </div>
        <div class="sp-button-reset" @click="warningSocketButton(2, index, item.data)">
          我知道了
        </div>
      </span>
    </el-dialog> -->

    <div
    id="close"
      class="warnDialog"
    >
      <div>
        <div class="closeBtn" @click="toClose">
          <i class="el-icon-close"></i>
        </div>
        <div class="warnTitle">
          <img
            width="16"
            height="16"
            src="@/assets/warnTitleIcon.png/"
            alt=""
          >
          未解除报警个数：<span class="warnNum" id="warnNum">{{ this.warnNum }}</span>
        </div>
        <div style="margin-top:10px;color:#fff">
          最新报警时间：<span id="warnTime">{{ this.getNewerTime }}</span>
        </div>
        <el-button
          type="primary"
          size="small"
          style="margin-top: 10px; float: right; pointer-events: all"
          @click="showWarn"
        >查看详细信息</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { Navbar, Sidebar, AppMain } from "./components";
import Breadcrumb from "@/components/Breadcrumb";
import ResizeMixin from "./mixin/ResizeHandler";
import Socket from "@/socket/socket";
import { msgAlarmRead,msgAlarmWebAlarm,msgAlarmList } from "@/api/alarmList";
import { sdkGetMessage } from "@/api/sdk";
import store from "@/store";
import router from '@/router'

export default {
  name: "Layout",
  components: {
    Navbar,
    Sidebar,
    Breadcrumb,
    AppMain,
  },
  mixins: [ResizeMixin],
  watch: {
    "$route.path"(newValue) {
      if (newValue != "/dashboard") {
        this.$store.dispatch("app/openSideBar", { withoutAnimation: false });
      }
    },
  },
  data(){
    return{
      warnVisible: false,
      warnNum: 0,
      getNewerTime:'',
      warningSocketList: null,
      dialogShow:false,
    }
  },
  computed: {
    isHome() {
      return this.$route.path == "/dashboard";
    },
    sidebar() {
      return this.$store.state.app.sidebar;
    },
    device() {
      return this.$store.state.app.device;
    },
    fixedHeader() {
      return this.$store.state.settings.fixedHeader;
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened && this.isHome == true,
        openSidebar: this.sidebar.opened,
        ishome: this.isHome == true,
        withoutAnimation: this.sidebar.withoutAnimation,
        // mobile: this.device === 'mobile'  // 不再有移动端
      };
    },
  },
  data() {
    return {
      warningSocketList: [],
    };
  },
  created(){
    this.$eventBus.$on('customEvent', () => {
        // 执行需要触发的方法
        this.getWtsAlarm()
    });
  },
  mounted() {
      this.getWtsAlarm()
    this.startWebSocket();
    const close = document.getElementById('close');
      close.style.display='none'
  },
  methods: {
   getWtsAlarm(){
      const params = {
      pageNum: 1,
      pageSize: 100000000,
      isRelease: '2'
    }
    msgAlarmList(params).then((res) => {
      const timeArray = res.data.records.map(item =>
        item.alarmTime
      )
      // 获取当前时间
      const currentTime = new Date()

      // 初始化最近时间为数组中的第一个时间
      let closestTime = new Date(timeArray[0])
      let timeDiff = Math.abs(currentTime - closestTime)

      // 遍历数组中的时间，找到离当前时间最近的时间
      timeArray.forEach(timeStr => {
        const time = new Date(timeStr.replace(/-/g, '/').replace(' ', 'T'))
        const diff = Math.abs(currentTime - time)
        if (diff < timeDiff) {
          closestTime = time
          timeDiff = diff
        }
      })
      if (res.data.records.length > 0) {
        this.warnNum = res.data.records.length
        if(this.warnNum>0){
        const close = document.getElementById('close');
      close.style.display='block'
       }
      this.getNewerTime= this.getTime(closestTime)
      const closeBox = document.getElementById('close');
        closeBox.style.display='block'
        document.getElementById('warnNum').textContent=this.warnNum
        document.getElementById('warnTime').textContent=this.getNewerTime
        if (document.querySelector('#audio')) {
          const audio = document.querySelector('#audio')
          audio.muted = false
          audio.play()
        } else {
          var audio = document.createElement('audio')
          audio.setAttribute('id', 'audio')
          audio.src = './video.mp3'
          document.body.append(audio)
          audio.play()

          setTimeout(() => {
            document.body.removeChild(audio)
          }, 3000)
        }
      }
    })
    },
    getTime(data){
      const date = new Date(data);

// 获取年、月、日、时、分、秒
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    handleClickOutside() {
      this.$store.dispatch("app/closeSideBar", { withoutAnimation: false });
    },
    // 开始连接webSocket
    startWebSocket() {
      return new Promise((resolve, reject) => {
        console.log("Socket建立链接");
        this.socket = new Socket({
          "socket-open": (socket) => {
            console.log("Socket开启连接");
            socket.sendLogin();

            sdkGetMessage();

            resolve();
          },
          "socket-message": async(res) => {
            console.log("Socket接受信息", res);
            if (res.code == 110) {
              // this.warningSocket.show = true
              // this.warningSocket.data = res.data
              // console.log(this.warningSocket.data)
              this.getWtsAlarm()
              // this.warnVisible = true
              const closeBox = document.getElementById('close');
        closeBox.style.display='block'
        document.getElementById('warnNum').textContent=this.warnNum
        document.getElementById('warnTime').textContent=this.getNewerTime
              this.warningSocketList.push({
                show: true,
                data: res.data,
              });

              
              this.$store.state.app.warningSocket.list.push(res.data);
              this.$store.state.app.warningSocket.list = JSON.parse(
                JSON.stringify(this.$store.state.app.warningSocket.list)
              );
            }
          },
          "socket-close": () => {
            // this.$message.error("连接系统中断");
            this.startWebSocket();
          },
          "socket-error": () => {
            this.$message.error("连接系统失败,请刷新重试或联系客服");
          },
        });
        this.socket.setVm(this);
        this.socket.onInit();
      });
    },
    warningSocketButton(type, index, data) {
      console.log(data, '99999')
      for (
        var i = 0;
        i < this.$store.state.app.warningSocket.list.length;
        i++
      ) {
        if (data.id === this.$store.state.app.warningSocket.list[i].id) {
          this.$store.state.app.warningSocket.list.splice(i, 1);
        }
      }
      if (type === 1) {
        msgAlarmRead({ pushId: data.pushId });
        sessionStorage.row = JSON.stringify(data)
        this.$router.push({
          path: "/alarmDetail",
          query: {
            id: data.id,
            cameraCode: data.cameraCode || 200,
            alarmId: data.alarmId,
          },
        });
      } else if (type === 2) {
        // this.$store.commit('app/warningSocketAdd', this.warningSocket.data)
        console.log("已读消息", data);
        msgAlarmRead({ pushId: data.pushId });

        this.$store.commit("app/homeWarningChange");
      }

      this.warningSocketList[index].show = false;
      this.warningSocketList.splice(index, 1);
    },
    showWarn() {
      if (this.$route.path === '/list') {
        window.refreshList()
      } else router.push({ path: '/list', query: { zhangtai: '2' }})
    },
    toClose(){
      const close = document.getElementById('close');
      close.style.display='none'
      // this.warnVisible=false
      // alert(this.warnVisible)
    }
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
@import "~@/styles/variables.scss";

.nav-header {
  width: 100%;
  height: 50px;
}

.sidebar-container {
  top: 50px !important;
  height: calc(100% + 50px);
}

.home-list {
  width: 35%;

  ::v-deep .el-dialog__body {
    padding: 0 20px;
  }
}

.app-wrapper {
  @include clearfix;
  position: relative;
  height: 100%;
  width: 100%;

  &.mobile.openSidebar {
    position: fixed;
    top: 0;
  }
}

.drawer-bg {
  background: #000;
  opacity: 0.3;
  width: 100%;
  top: 0;
  height: 100%;
  position: absolute;
  z-index: 999;
}

.fixed-header {
  position: fixed;
  top: 50px;
  right: 0;
  // background-color: #F5F5F5;
  z-index: 9;
  width: calc(100% - #{$sideBarWidth});
  transition: width 0.28s;
}

.hideSidebar .fixed-header {
  width: 100%;
}

.mobile .fixed-header {
  width: 100%;
}

.warning-view {
  padding: 5px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 15px;

  .status-icon {
    padding: 3px 7px;
    background-color: #d68e15;
    position: absolute;
    right: 5px;
    top: 5px;
    font-size: 12px;
    border-radius: 5px;
    color: #fff;
    line-height: 1em;

    &.status-icon-2 {
      background-color: #70d2ff;
    }
  }

  .warning-image {
    width: 80px;
    height: 80px;
    border: 1px solid #fff;
    margin-right: 10px;
  }

  .warning-content {
    color: #8eacc8;
    font-size: 13px;
    flex: 1;

    .text-base {
      color: #333;
      margin-top: 4px;
    }

    .text-1 {
      margin-bottom: 10px;
      color: #2766dd;
      font-size: 15px;
    }
  }

  .warning-operation {
    display: flex;
    font-size: 12px;
    color: #fff;
    margin-top: 4px;
    justify-content: flex-end;

    .button-1 {
      width: 60px;
      padding: 2px 0px;
      border-radius: 5px;
      border: 1px solid #fff;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .button-2 {
      width: 60px;
      padding: 2px 0px;
      border-radius: 5px;
      margin-left: 5px;
      border: 1px solid #fff;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.warnDialog {
  display: block;
  height: 130px;
  width: 350px;
  position: absolute;
  bottom: 20px;
  right: 20px;
  padding: 20px;
  z-index: 999;
  box-shadow: 0px 2px 12px 1px #0b285b;
        border-radius: 12px;
  background: linear-gradient(
            183deg,
            #2766dd 0%,
            #0d2855 53%,
            #041a3a 100%
        );
  .warnTitle {
      width: 212px;
      height: 32px;
      line-height: 32px;
      padding-left: 8px;
      color: #fff;
      background: url(../assets/warnTitle.png) center / 100%;
  }
  .warnNum {
      padding: 0 6px;
      font-weight: 400;
      font-size: 20px;
      color: #f00404;
      cursor: pointer;
  }
}
.closeBtn{
  position:absolute;
  top:12px;
  right:12px;
  color:#fff;
  cursor: pointer;
  z-index: 999;
}
</style>
