<template>
  <div id="unloading-platform">
    <div class="side-area">
      <Title text="设备列表"></Title>
      <ShadowContainer class="short-container">
        <div id="platform-description">
          <div
            :class="['platforms', activePlatform == index ? 'active' : '']"
            v-for="(platform, index) in platformList"
            :key="index"
            @click="showDeviceInfo(platform)"
          >
            <div class="platform-title">
              <i class="iconfont icon-xieliaopingtai"></i>
              {{ platform.device_no }}
              <span
                :style="{ color: platform.is_online == 1 ? '#66cab9' : '' }"
                >{{ platform.is_online_text }}</span
              >
            </div>
          </div>
        </div>
      </ShadowContainer>
      <Title text="各平台运行分析"></Title>
      <ShadowContainer class="long-2-container">
        <div class="filters">
          <div
            :class="['filter', activeType == '0' ? 'active' : '']"
            @click="changeType('0')"
          >
            过去24小时
          </div>
          <div
            :class="['filter', activeType == '1' ? 'active' : '']"
            @click="changeType('1')"
          >
            过去7天
          </div>
        </div>
        <div id="battery-chart" ref="batteryChart"></div>
        <div class="separate-chart-line"></div>
        <div id="weight-chart" ref="weightChart"></div>
      </ShadowContainer>
    </div>
    <div class="mid-area">
      <div class="cover-area"></div>
      <div class="buildingwindow" v-if="platformWindowVisible">
        <div class="building-description">
          <img src="@/assets/unloadingplatform/platform.png" alt="" />
          {{ windowData.device_no }}
        </div>
        <div class="building-info">
          <div class="building-info-text">载重：{{ windowData.weight }}t</div>
          <div class="building-info-text">
            电量：{{ windowData.battery_quantity }}%
          </div>
          <div class="building-info-text">偏置：{{ windowData.bias }}%</div>
        </div>
        <div class="recent-open">
          最后更新:{{ windowData.latest_record_time }}
        </div>
      </div>
      <div class="swagger-container">
        <img class="lt" src="@/assets/lt.png" alt="" />
        <img class="rt" src="@/assets/rt.png" alt="" />
        <img class="rb" src="@/assets/rb.png" alt="" />
        <img class="lb" src="@/assets/lb.png" alt="" />
        <div id="amap-container"></div>
      </div>
    </div>
    <div class="side-area">
      <Title text="报警信息"></Title>
      <ShadowContainer class="long-container">
        <div id="warning-info">
          <div>
            <div class="warning-info-text">今日报警</div>
            <div class="warning-info-num">
              {{ platformWarningStatus.today_num }}
            </div>
            <div class="warning-info-img">
              <img src="@/assets/fallprotection/today.png" alt="" />
            </div>
          </div>
          <div>
            <div class="warning-info-text">累计未处理报警</div>
            <div class="warning-info-num" style="color: #ffc74c">
              {{ platformWarningStatus.un_handle_num }}
            </div>
            <div class="warning-info-img">
              <img src="@/assets/fallprotection/total-no.png" alt="" />
            </div>
          </div>
          <div>
            <div class="warning-info-text">累计履责率</div>
            <div class="warning-info-num" style="color: #22c3ed">
              {{ platformWarningStatus.handle_rate
              }}<span style="font-size: 14px; margin-left: 12px">%</span>
            </div>
            <div class="warning-info-img">
              <img src="@/assets/fallprotection/percent.png" alt="" />
            </div>
          </div>
        </div>
        <div class="warning-table">
          <div class="warning-table-header">
            <div class="warning-table-run-time">运行时间</div>
            <div class="warning-table-device">设备</div>
            <div class="warning-table-info">告警信息</div>
            <div class="warning-table-status">处理状态</div>
          </div>
          <div
            class="warning-table-list"
            v-infinite-scroll="load"
            :infinite-scroll-distance="1"
            id="table-scroll"
            @mouseenter="clearScroll"
            @mouseleave="reScroll"
          >
            <div
              class="warning-table-column"
              v-for="(column, index) in platformWarningList"
              :key="index"
            >
              <div class="warning-table-run-time">{{ column.log_time }}</div>
              <el-tooltip
                class="item"
                effect="dark"
                :content="column.device_no"
                placement="top"
              >
                <div class="warning-table-device">{{ column.device_no }}</div>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                :content="column.alarm_content"
                placement="top"
              >
                <div class="warning-table-info">
                  {{ column.alarm_content }}
                </div>
              </el-tooltip>
              <div
                class="warning-table-status"
                :style="{ color: column.status == 1 ? '#FFC74C' : '#22C3ED' }"
              >
                {{ column.status_text }}
              </div>
            </div>
          </div>
        </div>
      </ShadowContainer>
    </div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import {
  getBaseInfo,
  getUnloadingPlatformList,
  getPlatformCurrentStatus,
  getPlatformRunningAnalysis,
  getPlatformWarningStatus,
  getPlatformWarningList,
} from "@/api/index";
import platformIcon from "@/assets/unloadingplatform/icon-platform.png";
export default {
  name: "UnloadingPlatform",
  data() {
    return {
      platformList: [],
      AMap: null,
      map: null,
      mapCenter: [],
      buildingList: [],
      platformRunningData: [],
      platformWarningList: [],
      platformWarningStatus: {
        today_num: 0,
        un_handle_num: 0,
        handle_rate: 0,
      },
      platformWindowVisible: false,
      windowData: {},
      activePlatform: 0,
      activeType: "0",
      batteryChart: null,
      weightChart: null,
      page: 1,
      interval1: null,
    };
  },
  methods: {
    initMap() {
      AMapLoader.load({
        key: "a7387204aeee9f238b217bad35460ba9",
        version: "1.4.15",
        plugins: ["AMap.MarkerClusterer", "AMap.DistrictSearch"],
      })
        .then((AMap) => {
          // 初始化地图
          this.AMap = AMap;
          this.map = new AMap.Map("amap-container", {
            viewMode: "2D",
            zoom: 20,
            center: this.mapCenter,
            resizeEnable: true,
            mapStyle: "amap://styles/1dda787b3ac1ce28f171d2f153726eb7",
          });

          this.$nextTick(() => {
            var scale = window.screen.height / 1080;
            document.getElementById("amap-container").style.zoom = 1 / scale;
          });
          this.map.on("click", () => {
            this.platformWindowVisible = false;
          });
          this.getUnloadingPlatformList();
        })
        .catch((e) => {
          console.log(e);
        });
    },
    setMarker() {
      this.platformList.map((device) => {
        if (device.latitude && device.longitude) {
          const mapMarkers = new this.AMap.Marker({
            icon: platformIcon,
            position: [device.longitude, device.latitude],
            offset: new this.AMap.Pixel(-25, -25),
            extData: {
              markerData: device,
            },
          });
          mapMarkers.setMap(this.map);
          mapMarkers.on("click", (e) => {
            const markData = e.target.getExtData().markerData;
            this.map.setCenter([markData.longitude, markData.latitude]);
            this.$nextTick(() => {
              this.showDeviceInfo(markData);
            });
          });
        }
      });
    },
    getUnloadingPlatformList() {
      getUnloadingPlatformList().then((res) => {
        this.platformList = res.data;
        this.setMarker();
      });
    },
    showDeviceStatus(item) {
      if (item.showDevice) {
        item.showDevice = false;
      } else {
        item.showDevice = true;
      }
      this.$forceUpdate();
    },
    showDeviceInfo(device) {
      this.platformWindowVisible = false;
      this.map.setCenter([device.longitude, device.latitude]);
      getPlatformCurrentStatus({ device_id: device.id }).then((res) => {
        this.windowData = { ...device, ...res.data };
        console.log(this.windowData);
        this.$nextTick(() => {
          this.platformWindowVisible = true;
        });
      });
    },
    renderBatteryChart() {
      const xAxisData = this.platformRunningData[0].data.map((item) => {
        return item.time;
      });
      const series = this.platformRunningData.map((item) => {
        return {
          name: item.name,
          data: item.data.map((platformData) => {
            return platformData.battery_quantity;
          }),
          type: "line",
          smooth: true,
        };
      });
      this.batteryChart = this.$echarts.init(this.$refs.batteryChart);
      const option = {
        grid: {
          top: 30,
          bottom: 30,
          left: 30,
          right: 30,
        },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          data: xAxisData,
          axisTick: { show: false },
          axisLabel: {
            fontSize: "12",
            color: "#c6def9",
          },
        },
        yAxis: {
          name: "电量/%",
          nameTextStyle: {
            color: "#C6DEF9",
            nameLocation: "start",
          },
          type: "value",
          axisLabel: {
            fontSize: "12",
            color: "#c6def9",
          },
          splitNumber: 4,
          splitLine: {
            lineStyle: {
              color: "rgba(95, 120, 144, 0.4)",
            },
          },
          minInterval: 1,
        },
        series: series,
        legend: {
          orient: "horizontal",
          textStyle: {
            fontSize: 12,
            color: "rgba(225, 239, 255, 0.7)",
          },
          itemGap: 12,
        },
      };
      this.batteryChart.setOption(option);
      this.$nextTick(() => {
        // 解决echarts图表放大溢出父容器
        const resizeOb = new ResizeObserver((entries) => {
          for (const entry of entries) {
            this.$echarts.getInstanceByDom(entry.target).resize();
          }
        });
        resizeOb.observe(document.getElementById("battery-chart"));
      });
    },
    renderWeightChart() {
      const xAxisData = this.platformRunningData[0].data.map((item) => {
        return item.time;
      });
      const series = this.platformRunningData.map((item) => {
        return {
          name: item.name,
          data: item.data.map((platformData) => {
            return platformData.weight;
          }),
          type: "line",
          smooth: true,
        };
      });
      this.weightChart = this.$echarts.init(this.$refs.weightChart);
      const option = {
        grid: {
          top: 30,
          bottom: 30,
          left: 30,
          right: 30,
        },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          data: xAxisData,
          axisTick: { show: false },
          axisLabel: {
            fontSize: "12",
            color: "#c6def9",
          },
        },
        yAxis: {
          name: "载重/t",
          nameTextStyle: {
            color: "#C6DEF9",
            nameLocation: "start",
          },
          type: "value",
          axisLabel: {
            fontSize: "12",
            color: "#c6def9",
          },
          splitNumber: 4,
          splitLine: {
            lineStyle: {
              color: "rgba(95, 120, 144, 0.4)",
            },
          },
        },
        legend: {
          orient: "horizontal",
          textStyle: {
            fontSize: 12,
            color: "rgba(225, 239, 255, 0.7)",
          },
          itemGap: 12,
        },
        series: series,
      };
      this.weightChart.setOption(option);
      this.$nextTick(() => {
        // 解决echarts图表放大溢出父容器
        const resizeOb = new ResizeObserver((entries) => {
          for (const entry of entries) {
            this.$echarts.getInstanceByDom(entry.target).resize();
          }
        });
        resizeOb.observe(document.getElementById("weight-chart"));
      });
    },
    changeType(type) {
      this.activeType = type;
      this.batteryChart.dispose();
      this.weightChart.dispose();
      getPlatformRunningAnalysis({ date_type: type }).then((res) => {
        this.platformRunningData = res.data;
        this.$nextTick(() => {
          this.renderBatteryChart();
          this.renderWeightChart();
        });
      });
    },
    load() {
      if (this.platformWarningList.length == this.page * 20) {
        getPlatformWarningList({ page: this.page + 1, limit: 20 }).then(
          (res) => {
            this.page += 1;
            this.platformWarningList = [
              ...this.platformWarningList,
              ...res.data.data,
            ];
          }
        );
      } else if (this.platformWarningList.length == 0) {
        getPlatformWarningList({ page: 1, limit: 20 }).then((res) => {
          this.page = 1;
          this.platformWarningList = res.data.data;
          this.$nextTick(() => {
            const element = document.getElementById("table-scroll");
            this.autoScroll(1, 50, 1500, element);
          });
        });
      }
    },
    autoScroll(stepLength, speed, delay, element) {
      var that = this;
      function start() {
        that.interval1 = setInterval(scrolling, speed);
        element.scrollTop += stepLength;
      }
      function scrolling() {
        var sTop = element.scrollTop;
        element.scrollTop += stepLength;
        if (
          sTop === element.scrollTop ||
          sTop == 0 ||
          element.scrollTop === element.scrollHeight - element.offsetHeight
        ) {
          element.scrollTop = 0;
          clearInterval(that.interval1);
          that.timeout1 = setTimeout(start, delay);
        }
      }
      if (element.offsetHeight !== element.scrollHeight) {
        // 元素内容没有溢出时，不触发
        that.timeout1 = setTimeout(start, delay);
      }
    },
    clearScroll() {
      clearInterval(this.interval1);
      clearTimeout(this.timeout1);
    },
    reScroll() {
      this.$nextTick(() => {
        const element = document.getElementById("table-scroll");
        this.autoScroll(1, 50, 1500, element);
      });
    },
  },

  mounted() {
    getBaseInfo().then((res) => {
      this.mapCenter = [res.data.longitude, res.data.latitude];
      this.$nextTick(() => {
        this.initMap();
      });
    });

    getPlatformRunningAnalysis({ date_type: 0 }).then((res) => {
      this.platformRunningData = res.data;
      this.$nextTick(() => {
        this.renderBatteryChart();
        this.renderWeightChart();
      });
    });
    getPlatformWarningStatus().then((res) => {
      this.platformWarningStatus = res.data;
    });
  },
};
</script>
<style lang="less" scoped>
#unloading-platform {
  padding: 12px 20px;
  display: flex;
  justify-content: space-between;
  padding-bottom: 0;
  height: calc(100% - 24px);
}
.side-area {
  width: 25%;
  min-width: 400px;
}
.mid-area {
  width: 50%;
  margin: 0 12px;
  position: relative;
  height: 100%;
}
.swagger-container {
  position: relative;
  height: 100%;
  .container-img {
    width: 100%;
    height: 520px;
    vertical-align: top;
  }
  .lt,
  .lb,
  .rb,
  .rt {
    position: absolute;
    width: 20px;
    height: 20px;
  }
  .lt {
    top: -2px;
    left: -2px;
  }
  .lb {
    left: -2px;
    bottom: -2px;
  }
  .rb {
    right: -2px;
    bottom: -2px;
  }
  .rt {
    right: -2px;
    top: -2px;
  }
}
#amap-container {
  width: 100%;
  height: 100%;
}
#platform-description {
  height: 100%;
  overflow-y: scroll;
  .platforms {
    margin-bottom: 12px;
    &:last-child {
      margin-bottom: 0;
    }
    .platform-title {
      line-height: 22px;
      img {
        width: 22px;
        vertical-align: top;
      }
      background: rgba(44, 96, 162, 0.2);
      font-size: 14px;
      color: #c6def9;
      padding: 10px 12px;
      cursor: pointer;
      span {
        float: right;
      }
      &:hover {
        background: rgba(44, 96, 162, 0.5);
        color: #16c0ff;
      }
      &.active {
        background: rgba(44, 96, 162, 0.5);
      }
    }
    .platform-info {
      line-height: 22px;

      img {
        width: 22px;
        vertical-align: top;
      }
      background: rgba(44, 96, 162, 0.1);
      font-size: 14px;
      color: #c6def9;
      padding: 10px 12px;
      border-top: 1px solid rgba(122, 143, 173, 0.2);
      cursor: pointer;
      span {
        float: right;
      }
    }
  }
}
#battery-chart,
#weight-chart {
  height: calc(50% - 42px);
}
.warning-count {
  display: inline-block;
  vertical-align: top;
  width: 49%;
  position: relative;
  margin-right: 2%;
  &:nth-child(2n) {
    margin-right: 0;
  }
  img {
    vertical-align: top;
    width: 100%;
  }
  .warning-info {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translateX(-50%) translateY(-50%);
    text-align: center;
    .warning-num {
      font-size: 24px;
      color: #ff6151;
    }
    .warning-text {
      font-size: 14px;
      color: #27acfb;
    }
  }
}
#warning-info {
  display: flex;
  justify-content: space-between;
  text-align: center;
  & > div {
    width: 33%;
  }
  .warning-info-text {
    white-space: nowrap;
    padding-top: 10px;
    font-size: 16px;
    color: #ffffff;
    line-height: 24px;
    text-shadow: 0 0 5px rgba(99, 226, 253, 0.6),
      0 0 5px rgba(99, 226, 253, 0.6), 0 0 6px rgba(99, 226, 253, 0.6),
      0 0 40px rgba(99, 226, 253, 0.6);
  }
  .warning-info-num {
    font-size: 24px;
    color: #ff6151;
  }
  .warning-info-img {
    position: relative;
    transform: translateY(-60px);
    margin-bottom: -60px;
    img {
      width: 80%;
      margin: 0 auto;
    }
  }
}
.warning-table {
  font-size: 14px;
  text-align: center;
  color: #c6def9;
  height: calc(100% - 132px);
  .warning-table-list {
    height: calc(100% - 50px);
    overflow-y: auto;
  }
  .warning-table-header {
    background: rgba(44, 96, 162, 0.2);
    display: flex;
    padding: 12px 0;
  }
  .warning-table-column {
    padding: 12px 0;
    background: rgba(44, 96, 162, 0.05);
    display: flex;
    &:nth-child(2n) {
      background: rgba(44, 96, 162, 0.1);
    }
  }
  .warning-table-run-time {
    width: 30%;
    white-space: pre-wrap;
  }
  .warning-table-device,
  .warning-table-info {
    width: 25%;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
  .warning-table-status {
    width: 20%;
  }
}
.warning-scroll {
  height: 370px;
  overflow-y: auto;
}

.buildingwindow {
  width: 460px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-120%);
  background: url("@/assets/safecap/cap-window-bg.png") no-repeat;
  background-size: 100% 100%;
  padding: 20px;
  z-index: 1000;
}
.recent-open,
.building-info-text {
  font-size: 14px;
  color: #c6def9;
  line-height: 24px;
}
.building-info {
  display: flex;
  flex-wrap: wrap;
}
.building-info-text {
  width: 50%;
}
.building-description {
  line-height: 32px;
  font-size: 18px;
  color: #c6def9;
  padding-bottom: 16px;
  margin-bottom: 20px;
  border-bottom: 1px solid #7a8fad;
  img {
    width: 32px;
    vertical-align: top;
  }
  .name {
    float: right;
  }
  .online-status.online {
    color: rgba(62, 236, 111, 1);
  }
}
::v-deep .amap-icon {
  img {
    width: 50px;
    height: 50px;
  }
}

.platform {
  img {
    width: 20px;
    vertical-align: middle;
    margin-right: 6px;
  }
  font-size: 14px;
  color: #c6def9;
  .platform-title {
    background: rgba(44, 96, 162, 0.2);
    border-bottom: 1px solid rgba(122, 143, 173, 0.4);
    line-height: 40px;
    padding: 0 12px;
    .status {
      float: right;
    }
  }
  .platform-info {
    background: rgba(44, 96, 162, 0.1);
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    & > div {
      width: calc(50% - 48px);
      padding: 6px 12px;
    }
  }
  &:hover {
    color: #27acfb;
    .platform-title,
    .platform-info {
      background: rgba(44, 96, 162, 0.4);
    }
  }
}

.filters {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
  .filter {
    white-space: nowrap;
    font-size: 14px;
    color: rgba(198, 222, 249, 1);
    width: 120px;
    padding: 6px;
    text-align: center;
    cursor: pointer;
    margin: 0 40px;
    background: linear-gradient(
      90deg,
      rgba(8, 36, 71, 0) 0%,
      rgba(39, 172, 251, 0.19) 49%,
      rgba(9, 37, 71, 0) 100%
    );
    &.active {
      color: #16c0ff;
    }
  }
}
.separate-chart-line {
  background: #114e70;
  height: 4px;
  width: 100%;
  margin: 20px 0;
}
.short-container {
  height: calc(99% / 3 - 98px);
}
.long-2-container {
  height: calc(99% / 3 * 2 - 98px);
}
.long-container {
  height: calc(100% - 98px);
}
.cover-area {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 999;
  box-shadow: #1f81ef 0px 0px 8px inset;
  pointer-events: none;
}
</style>