<template>
  <div id="fall-protection">
    <div class="side-area">
      <Title text="工地区域"></Title>
      <ShadowContainer class="short-container">
        <div id="level-description">
          <div
            class="levels"
            v-for="(building, index) in buildingList"
            :key="index"
          >
            <div class="level-title" @click="showDeviceStatus(building)">
              <i class="iconfont icon-linbianfanghu-liebiao-1"></i>
              {{ building.area_name }}
              <span>{{ building.total }}</span>
            </div>
            <div v-show="building.showDevice">
              <div
                class="level-info"
                v-for="(device, i) in building.device_list"
                :key="i"
                @click="showDeviceInfo(device)"
              >
                <i class="iconfont icon-linbianfanghu-liebiao-2"></i>
                {{ device.device_no }}
                <span
                  :style="{ color: device.is_online == 1 ? '#26D591' : '' }"
                  >{{ device.is_online_text }}</span
                >
              </div>
            </div>
          </div>
        </div>
      </ShadowContainer>
      <Title text="近24小时报警分析"></Title>
      <ShadowContainer class="long-container">
        <div id="today-warning-chart" ref="today24hourWarningChart"></div>
      </ShadowContainer>
    </div>
    <div
      class="mid-area"
      v-loading="mapLoading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <div class="cover-area"></div>
      <div class="buildingwindow" v-if="buildingWindowVisible">
        <div class="building-description">
          <img src="@/assets/fallprotection/building.png" alt="" />
          {{ windowData.device_no }}
        </div>
        <div class="building-info">
          <div
            class="building-info-text"
            v-for="(info, index) in windowData.alarm_list"
            :key="index"
          >
            {{ info.alarm_name }}：{{ info.describe }}
          </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="short-container">
        <div class="warning-scroll">
          <div
            class="warning-count"
            v-for="(warn, index) in fallWarningList"
            :key="index"
          >
            <div class="warning-info">
              <div class="warning-num">{{ warn.num }}</div>
              <div class="warning-text">{{ warn.alarm_type_text }}</div>
            </div>
          </div>
        </div>
      </ShadowContainer>
      <Title text="报警信息"></Title>
      <ShadowContainer class="long-container">
        <div id="warning-info">
          <div>
            <div class="warning-info-text">今日报警</div>
            <div class="warning-info-num">
              {{ fallwarningStatus.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">
              {{ fallwarningStatus.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">
              {{ fallwarningStatus.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-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 fallwarningTableData"
              :key="index"
              @click="showWarning(column._id)"
            >
              <div class="warning-title">
                <div class="warning-name">
                  <div
                    class="warning-dot"
                    :style="{
                      backgroundColor:
                        column.alarm_level == 1 ? '#FFC74C' : '#FF4C4C',
                    }"
                  ></div>
                  <span class="warning-device">{{ column.device_no }}</span> /
                  <span
                    :style="{
                      color: column.alarm_level == 1 ? '#FFC74C' : '#FF4C4C',
                    }"
                    >{{ column.alarm_level_text }}</span
                  >
                </div>
                <div
                  class="warning-status"
                  :style="{ color: column.status == 1 ? '#FFC74C' : '#22C3ED' }"
                >
                  {{ column.status_text }}
                </div>
              </div>
              <div class="warning-content">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="column.alarm_content"
                  placement="top"
                >
                  <div class="warning-message">
                    预警信息：{{ column.alarm_content }}
                  </div>
                </el-tooltip>
                <div class="warning-time">{{ column.log_time }}</div>
              </div>
            </div>
          </div>
        </div>
      </ShadowContainer>
      <warning-dialog
        :data="warningData"
        :visible="warningDialogVisible"
        @changeVisible="(val) => (warningDialogVisible = val)"
      ></warning-dialog>
    </div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import WarningDialog from "@/components/earlywarning/WarningDialog";
import {
  getBaseInfo,
  getBuildingList,
  get24hourWarningData,
  getFallWarningList,
  getFallWarningStatus,
  getFallWarningTableList,
  getDeviceCurrentStatus,
  getWarningLogDetail,
} from "@/api/index";
import buildingIcon from "@/assets/fallprotection/building-marker.png";
export default {
  name: "FallProtection",
  components: { WarningDialog },
  data() {
    return {
      levelList: [],
      AMap: null,
      map: null,
      mapCenter: [],
      buildingList: [],
      warning24hourData: [],
      fallWarningList: [],
      fallwarningStatus: {
        today_num: 0,
        un_handle_num: 0,
        handle_rate: 0,
      },
      fallwarningTableData: [],
      buildingWindowVisible: false,
      windowData: {},
      page: 1,
      interval1: null,
      mapLoading: false,
      warningDialogVisible: false,
      warningData: {},
    };
  },
  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.innerHeight / 1080;
            document.getElementById("amap-container").style.zoom = 1 / scale;
          });
          this.map.on("click", () => {
            this.buildingWindowVisible = false;
          });
          this.getBuildingList();
        })
        .catch((e) => {
          console.log(e);
        });
    },
    setMarker() {
      this.buildingList.map((building) => {
        building.device_list.map((device) => {
          const mapMarkers = new this.AMap.Marker({
            icon: buildingIcon,
            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);
            });
          });
        });
      });
    },
    getBuildingList() {
      getBuildingList().then((res) => {
        this.buildingList = res.data;
        this.setMarker();
      });
    },
    showDeviceStatus(item) {
      if (item.showDevice) {
        item.showDevice = false;
      } else {
        item.showDevice = true;
      }
      this.$forceUpdate();
    },
    showDeviceInfo(device) {
      this.mapLoading = true;
      this.buildingWindowVisible = false;
      this.map.setCenter([device.longitude, device.latitude]);
      getDeviceCurrentStatus({ device_id: device.id }).then((res) => {
        this.mapLoading = false;
        this.windowData = { ...device, ...res.data };
        console.log(this.windowData);
        this.$nextTick(() => {
          this.buildingWindowVisible = true;
        });
      });
    },
    render24hourWarningChart() {
      const xAxisData = this.warning24hourData.map((item) => {
        return item.hour;
      });
      const yAxisData = this.warning24hourData.map((item) => {
        return item.num;
      });
      const chart = this.$echarts.init(this.$refs.today24hourWarningChart);
      const option = {
        color: ["#ff4544"],
        grid: {
          top: 30,
          bottom: 30,
          left: 30,
          right: 30,
        },
        tooltip: {
          appendToBody: true,
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          data: xAxisData,
          axisTick: { show: false },
          axisLabel: {
            fontSize: "12",
            color: "#c6def9",
          },
        },
        yAxis: {
          type: "value",
          axisLabel: {
            fontSize: "12",
            color: "#c6def9",
          },
          splitNumber: 4,
          splitLine: {
            lineStyle: {
              color: "rgba(95, 120, 144, 0.4)",
            },
          },
          minInterval: 1,
        },
        series: [
          {
            data: yAxisData,
            type: "line",
            smooth: true,
            areaStyle: {
              color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "#ff4544",
                },
                {
                  offset: 1,
                  color: "rgba(0,0,0,0)",
                },
              ]),
            },
          },
        ],
      };
      chart.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("today-warning-chart"));
      });
    },
    load() {
      if (this.fallwarningTableData.length == this.page * 10) {
        getFallWarningTableList({ page: this.page + 1 }).then((res) => {
          this.page += 1;
          this.fallwarningTableData = [
            ...this.fallwarningTableData,
            ...res.data.data,
          ];
        });
      } else if (this.fallwarningTableData.length == 0) {
        getFallWarningTableList({ page: 1 }).then((res) => {
          this.page = 1;
          this.fallwarningTableData = 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;
      //let step = 1

      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);
      });
    },
    showWarning(id) {
      getWarningLogDetail(id).then((res) => {
        this.warningData = res.data;
        this.warningDialogVisible = true;
      });
    },
  },
  mounted() {
    getBaseInfo().then((res) => {
      this.mapCenter = [res.data.longitude, res.data.latitude];
      this.$nextTick(() => {
        this.initMap();
      });
    });
    get24hourWarningData().then((res) => {
      this.warning24hourData = res.data;
      this.$nextTick(() => {
        this.render24hourWarningChart();
      });
    });
    getFallWarningList().then((res) => {
      this.fallWarningList = res.data;
    });
    getFallWarningStatus().then((res) => {
      this.fallwarningStatus = res.data;
    });
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/common/element.less";
#fall-protection {
  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;
}
.swagger-container {
  position: relative;
  .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%;
}
.swagger-container {
  width: 100%;
  height: 100%;
}
#level-description {
  height: 100%;
  overflow-y: scroll;
  .levels {
    margin-bottom: 12px;
    &:last-child {
      margin-bottom: 0;
    }
    .level-title {
      line-height: 22px;
      &:hover {
        color: #27acfb;
        background: rgba(44, 96, 162, 0.5);
      }
      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;
      }
    }
    .level-info {
      line-height: 22px;
      &:hover {
        color: #27acfb;
        background: rgba(44, 96, 162, 0.5);
      }
      img {
        width: 22px;
        vertical-align: top;
      }
      background: rgba(44, 96, 162, 0.1);
      font-size: 14px;
      color: #c6def9;
      padding: 10px 30px;
      border-top: 1px solid rgba(122, 143, 173, 0.2);
      cursor: pointer;
      span {
        float: right;
      }
    }
  }
}
#today-warning-chart {
  height: 100%;
}
.warning-count {
  display: inline-block;
  vertical-align: top;
  padding: 20px 0;
  width: 32%;
  margin-right: 2%;
  margin-bottom: 16px;
  background: url("@/assets/fallprotection/rect.png") no-repeat;
  background-size: 100% 100%;
  cursor: pointer;
  &:nth-child(3n) {
    margin-right: 0;
  }
  &:hover {
    font-weight: bold;
  }
  img {
    vertical-align: top;
    width: 100%;
  }
  .warning-info {
    text-align: center;
    .warning-num {
      font-size: 24px;
      color: #ff6151;
    }
    .warning-text {
      font-size: 14px;
      color: #27acfb;
      white-space: nowrap;
    }
  }
}
#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(31, 129, 239, 0.6),
      0 0 5px rgba(31, 129, 239, 0.6), 0 0 6px rgba(31, 129, 239, 0.6),
      0 0 40px rgba(31, 129, 239, 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: 100%;
    overflow-y: auto;
  }

  .warning-table-column {
    margin-bottom: 10px;
    cursor: pointer;
    .warning-title,
    .warning-content {
      display: flex;
      justify-content: space-between;
      line-height: 40px;
      padding: 0 20px;
    }
    .warning-title {
      background: rgba(44, 96, 162, 0.3);
      border-bottom: 1px solid rgba(122, 143, 173, 0.4);
    }
    .warning-content {
      background: rgba(44, 96, 162, 0.1);
    }
    .warning-message {
      text-align: left;
      white-space: nowrap;
      text-overflow: ellipsis;
      width: 50%;
      overflow: hidden;
    }
    .warning-dot {
      border-style: double;
      border-width: 4px;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      background: #fff;
      display: inline-block;
      vertical-align: middle;
      margin-right: 12px;
      border-color: #153a68;
    }
  }
}
.warning-scroll {
  height: 100%;
  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 {
  margin-bottom: 14px;
  line-height: 32px;
  font-size: 18px;
  color: #c6def9;
  padding-bottom: 16px;
  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;
  }
}
.short-container {
  height: calc(42.5% - 108px);
}
.long-container {
  height: calc(58% - 108px);
}
.cover-area {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 999;
  box-shadow: rgba(99, 226, 253, 0.6) 0px 0px 16px inset;
  pointer-events: none;
}
</style>