<template>
  <div id="main">
    <div class="box-top">
      <manage-btn v-model="selectIndex" @select="manageSelect" :list="routeList" v-if="showMenu" />
      <div class="tunnel-title"></div>
      <!--      <manage-length class="tunnel-length"></manage-length>-->
      <div class="top-length">
        <!--        <span>隧道总长度: {{ tunnelLength }}米</span>-->
        <span>当前施工长度: {{ constructionLength }}米</span>
      </div>
      <div class="top-right">
        <div class="current-site">
          当前站点：<span>{{ currentSite }}</span>
          <el-dropdown trigger="click" @command="handleChangeSite">
            <div class="toggle"></div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="item in siteList" :key="item.value" :command="item">{{
                  item.label
                }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="current-user">
          你好！<span>{{ currentUser }}</span>
          <span>今天是：{{ currentDate }}</span>
          <div class="logout" @click="handleLogout"></div>
        </div>
      </div>
    </div>
    <!-- <tunnel-scene id="tunnel-box" :isedit="false" /> -->
    <!-- 一进去的话应该是预览模式，所以引入这个组件1 -->

    <preview-scene id="tunnel-box" :isedit="false" :tunnelId="tunnelId" :key="tunnelId" :tunnelLen="tunnelLen"
      :tunnelName="tunnelName"></preview-scene>
    <div class="left">
      <el-drawer v-model="drawerLeft" direction="ltr" modal-class="modal-box" :modal="false" :show-close="false"
        :close-on-click-modal="false" :close-on-press-escape="false">
        <fan-info v-if="showFan" :list="socketData.leftData" :fan-data="largeScreenData"
          :transducer-data="largeScreenData" :loading="showFanLoading" :tunnel-id="tunnelId" />
        <used-ele v-if="showFan" :list="socketData.leftData" :ele-data="largeScreenData" />
      </el-drawer>
      <div v-if="drawerLeft" class="left-arrow" @click="closeLeft"></div>
      <div v-else class="shrink-left" @click="closeLeft"></div>
    </div>
    <div class="right">
      <el-drawer v-model="drawerRight" direction="rtl" modal-class="modal-box" :modal="false" :show-close="false"
        :close-on-click-modal="false" :close-on-press-escape="false">
        <wind-pressure-list v-if="showFan" :list="socketData.windPressure" :win-data="largeScreenData"
          :loading="showWindLoading" />
        <air-info v-if="showFan" :list="socketData.sensor" :air-data="largeScreenData" />
        <bad-gas-info v-if="showFan" :list="socketData.sensor" :bad-gas-data="largeScreenData" :tunnelId="tunnelId"
          :loading="showBadLoading" />
      </el-drawer>
      <div v-if="drawerRight" class="right-arrow" @click="closeRight"></div>
      <div v-else class="shrink-right" @click="closeRight"></div>
    </div>
    <div class="switch-btn">
      <div class="arrow" @click="previousBtn"></div>
      <el-carousel height="150px" type="card" ref="tunnelBtn" :autoplay="false" :initial-index="initialIndex"
        @change="changeTunnel">
        <div class="btn">
          <el-carousel-item v-for="item in tunnelList" :key="item.value">
            {{ item.label }}
          </el-carousel-item>
        </div>
      </el-carousel>
      <div class="arrow right" @click="nextBtn"></div>
    </div>
  </div>
</template>

<script setup>
import PreviewScene from "@/components/content/tunnelScene/PreviewScene.vue"
import FanInfo from "@/components/content/fanInfo/FanInfo.vue";
import UsedEle from "@/components/content/usedEle/UsedEle.vue";
import WindPressureList from "@/components/content/windPressure/WindPressureList.vue";
import AirInfo from "@/components/content/airInfo/AirInfo.vue";
import BadGasInfo from "@/components/content/badGasInfo/BadGasInfo.vue";
import ManageBtn from "@/components/manageBtn/index.vue";
import { dateFormat } from "@/utils/date.js";
import { getToken } from "@/utils/auth";
import { useAuthStore } from "@/store/userstore.js";
import { getLargeScreen, getLargeScreenInfo, getTunnelBySiteId } from "@/api/largeScreen";
import { ElMessage, ElMessageBox } from "element-plus";
import { getUserInfo } from "@/api/login";
import { initSceneData } from "@/api/tunnelScene";
const authStore = useAuthStore();
const router = useRouter();
const previewId = reactive(router.currentRoute.value.params.tunnelId)
const selectIndex = ref(-1);
const showFan = ref(false);
const drawerLeft = ref(true);
const initialIndex = ref(0)
const showFanLoading = ref(0)
const showWindLoading = ref(0)
const showBadLoading = ref(0)
const drawerRight = ref(true);
const showMenu = ref(false);
const currentSiteId = ref(0);
const currentSite = ref("");
const siteList = ref([])
const currentUser = ref("");
const currentUserId = ref(0);
const currentDate = ref(dateFormat());
const tunnelBtn = ref();
const tunnelList = ref([]);
const tunnelId = ref(0);
const tunnelLength = ref(0);
const constructionLength = ref(0);
const routeList = ref([]);
let socket = reactive("");
let tunnelName = reactive("")

const btnList = ref([
  {
    route: '/site',
    icon: 'sp_icon_zdgl.png',
    name: '站点管理'
  },
  {
    route: '/tunnel',
    icon: 'sp_icon_sdgl.png',
    name: '隧道管理'
  },
  {
    route: '/user',
    icon: 'sp_icon_yhgl.png',
    name: '用户管理'
  },
  // {
  //   route: '/system',
  //   icon: 'sp_icon_xtgl.png',
  //   name: '系统管理'
  // },
  // {
  //   icon: 'sp_icon_mngl.png',
  //   name: '模拟仿真'
  // },
])
const serialNumber = ref("");
let token = getToken();
let send = {
  type: "ping",
};
const largeScreenData = ref(null);
const socketData = reactive({
  leftData: [],
  windPressure: [],
  sensor: [],
});
let tunnelLen = computed(() => tunnelLength);

onMounted(() => {
  if (previewId) {
    getScreenInfo(previewId)
  }
  getUser()
  getOtherInfo()
  nextTick(() => {
    showFan.value = true;
  });
});

const getUser = () => {
  getUserInfo().then(res => {
    currentUser.value = res.data.user.userName
    currentUserId.value = res.data.user.userId
    localStorage.setItem('roleKey', res.data.user.roles[0].roleKey)
    localStorage.setItem('userId', currentUserId.value)
  })
}

const getOtherInfo = () => {
  getLargeScreenInfo().then((res) => {
    if (res?.code === 1000) {
      let routeArr = [];
      res.data.routeList.forEach((item, index) => {
        for (let btn of btnList.value) {
          if (item === btn.route) {
            routeArr.push(btn)
          }
        }
      })
      routeList.value = routeArr
      showMenu.value = true
      siteList.value = res.data.siteOption
      currentSiteId.value = res.data.siteOption[0].value
      currentSite.value = res.data.siteOption[0].label
      localStorage.setItem('site', currentSite.value)
      if(res.data.tunnelOption.length === 0){
        getTunnel(res.data.siteOption[0].value)
      }else {
        tunnelList.value = res.data.tunnelOption
      }
      if (previewId) {
        tunnelList.value.forEach((item, index) => {
          if (item.value == previewId) {
            initialIndex.value = index
          }
        })
      } else {
        getTunnel(res.data.siteOption[0].value)
      }
    }
  });
};
const getScreenInfo = (id) => {
  if (id) {
    tunnelId.value = id
    getLargeScreen(id).then((res) => {
      if (res?.code === 1000) {
        if (res.data.frequencyChangerList.length !== 0) {
          showFanLoading.value = 0
        } else {
          showFanLoading.value = 1
        }
        if (res.data.windPressureSensorList.length !== 0) {
          showWindLoading.value = 0
        } else {
          showWindLoading.value = 1
        }
        if (res.data.sensorList.length !== 0) {
          res.data.sensorList.forEach((item, index) => {
            if (
              item.equipmentType === "carbonDioxide" ||
              item.equipmentType === "carbonMonoxide" ||
              item.equipmentType === "hydrogenSulfide" ||
              item.equipmentType === "sulfurDioxide" ||
              item.equipmentType === "sulfurMonoxide" ||
              item.equipmentType === "nitrogenDioxide"
            ) {
              showBadLoading.value = 0
            } else {
              showBadLoading.value = 1
            }
          })
        } else {
          showBadLoading.value = 1
        }
        largeScreenData.value = res.data;
      } else {
        ElMessage.warning(res.msg)
      }
    });
    initSceneData(id).then((res) => {
      tunnelLength.value = res.data.tunnelLength
      constructionLength.value = res.data.constructionLength
      serialNumber.value = res.data.serialNumber
      initWebSocket();
    })
  }
};
//根据站点id获取隧道信息
const getTunnel = (id) => {
  getTunnelBySiteId(id).then((res) => {
    if (res?.code === 1000) {
      getScreenInfo(res.data[0]?.value)
      tunnelName = res.data[0].label
      tunnelList.value = res.data
    }
  });
}
const changeTunnel = (e) => {
  let newObj = {}
  tunnelList.value.forEach((item, index) => {
    if (index === e) {
      newObj = item
    }
  })
  showBadLoading.value = 0
  showWindLoading.value = 0
  showFanLoading.value = 0
  getScreenInfo(newObj.value)
  nextTick(() => {
    showFan.value = true;
  });
}
const manageSelect = (index) => {
  console.log("首页点击-", index);
  if (index == '站点管理') {
    if (currentUserId.value) {
      router.push("/site/" + currentUserId.value);
    }
  } else if (index == '隧道管理') {
    if (currentSiteId.value && currentUserId.value) {
      router.push("/tunnel/" + currentSiteId.value + '/byHome/' + currentUserId.value);
    }
  } else if (index == '用户管理') {
    if (currentSiteId.value) {
      router.push("/user/" + currentSiteId.value);
    }
  }
};
const handleChangeSite = (item) => {
  currentSite.value = item.label
  currentSiteId.value = item.value
  getTunnel(item.value)
  showFan.value = false
  nextTick(() => {
    showFan.value = true;
  });
}
const closeLeft = () => {
  drawerLeft.value = !drawerLeft.value;
};
const closeRight = () => {
  drawerRight.value = !drawerRight.value;
};
const handleLogout = () => {
  ElMessageBox.confirm(`确认退出登录吗`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    authStore.userLogout();
    router.push("/login");
  })
};
const previousBtn = () => {
  tunnelBtn.value.prev();
};
const nextBtn = () => {
  tunnelBtn.value.next();
};

const initWebSocket = () => {
  // let wsUrl = `ws://192.168.31.175:9000/websocket/equipment/${token}/${serialNumber.value}`
  let wsUrl = `ws://web-tunnel.feashow.com/api/wstunnel/websocket/equipment/${token}/${serialNumber.value}`;
  socket = new WebSocket(wsUrl);
  //连接发生错误的回调方法
  socket.onerror = function () {
    console.log("ws连接发生错误");
  };
  //连接成功建立的回调方法
  socket.onopen = function () {
    console.log("ws连接成功");
  };
  //接收到消息的回调方法
  socket.onmessage = function (event) {
    // console.log("服务器返回的信息: ", JSON.parse(event.data));
    const type = JSON.parse(event.data).type;
    const data = JSON.parse(event.data).data;
    if (type === "equipment") {
      data.forEach((item) => {
        if (item.typeKey === "frequency") {
          socketData.leftData = data;
        } else if (item.typeKey === "windPressure") {
          socketData.windPressure = data;
        } else if (item.typeKey === "sensor") {
          socketData.sensor = data;
        }
      });
    }

  };
  //连接关闭的回调方法
  socket.onclose = function () {
    console.log("ws连接关闭");
    // initWebSocket()
  };
  setInterval(() => {
    socket.send(JSON.stringify(send));
  }, 30000);
};
</script>
<style lang="scss">
.el-drawer__header {
  display: none;
}

.el-drawer__body {
  padding: 180px 68px 0 68px;
  overflow: hidden;
}

.el-dropdown__popper.el-popper {
  background: transparent;
  //border: none;
  border: 1px solid #0E7DAA;
  border-radius: 10px;
}

.is-light {
  background: rgba(7, 35, 72, 0.9);
}

.el-popper {
  padding: 20px;
  margin-left: 50px;
  width: 150px;
  background: rgba(7, 35, 72, 0.9);

  .el-scrollbar__wrap {
    .el-dropdown__list {
      .el-dropdown-menu {
        background-color: rgba(7, 35, 72, 0.9);
        border-radius: 10px;
        padding: 5px;

        .el-dropdown-menu__item {
          color: #FFFFFF;
          //border:none;
          padding: 5px;

          border-bottom: 1px solid #05FEFF;

          &:last-child {
            border-bottom: none;
          }
        }

        .el-dropdown-menu__item.hover,
        .el-dropdown-menu__item:hover {
          background-color: transparent !important;
          color: #F7B500;
        }
      }
    }
  }
}
</style>
<style lang="scss" scoped>
#main {
  height: 100%;
  width: 100%;
  background-color: #072348;

  #tunnel-box {
    height: 100%;
  }
}
</style>
