<template>
  <section class="mainbox">
    <!-- topBox start -->
    <div class="topBox">
      <div class="column statisSec">
        <statis-top
          :falarmCount="alarmCount"
          :fpersonalCount="personalCount"
          :fsiteCount="siteCount"
          :fepLoad="epLoad"
        ></statis-top>
        <statis-bottom :fhtAnalogData="htAnalogData"></statis-bottom>
      </div>
      <div class="column mapBox" style="position: relative">
        <!-- <map-static-top :fsiteCount="siteCount"></map-static-top>
        <div id="pickerBox">
          <input
            id="pickerInput"
            placeholder="输入关键字选取站点"
            v-model="name"
            @keyup.enter="siteList_api({ name: this.name })"
          />
          <i
            class="el-icon-search"
            @click="siteList_api({ name: this.name })"
          ></i>
          <div id="poiInfo"></div>
        </div>
        <div class="panel-footer"></div> -->
        <!-- <div
          class="map panel"
          id="mapF"
          style="height: 100%; z-index: 1; width: 100%"
        ></div> -->
      </div>
      <div class="column">
        <div class="panel deviceSum">
          <h2>设备运行状态</h2>
          <div class="filterSec" style="top: 0.7rem">
            <el-date-picker
              v-model="dDefaultTime"
              type="datetimerange"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="deviceTypeCount_api()"
            >
            </el-date-picker>
          </div>
          <pie-chart
            :fdeviceTypeCount="deviceTypeCount"
            v-if="this.deviceTypeCount"
          ></pie-chart>
          <div class="panel-footer"></div>
        </div>
        <div class="panel line1 operStatus">
          <h2>负载率</h2>
          <triangle-chart
            :frtAnalogData="rtAnalogData"
            v-if="this.rtAnalogData.heavyLoad"
          ></triangle-chart>
          <div class="panel-footer"></div>
        </div>
      </div>
    </div>
    <!-- topBox end -->

    <!-- bottomBox start -->
    <div class="bottomBox">
      <div class="column">
        <div class="panel currentUsage" style="height: 100%">
          <h2>总能耗</h2>
          <div class="filterSec">
            <select name="" id="" v-model="dayType">
              <option value="0">当日用量趋势</option>
              <option value="1">当月用量趋势</option>
            </select>
            <!-- <img src="../../assets/images/markIcon.png" alt=""> -->
          </div>
          <bar-chart
            :feptrendIco="eptrendIco"
            v-if="this.eptrendIco[0]"
          ></bar-chart>
          <div class="panel-footer"></div>
        </div>
      </div>
      <div class="column">
        <div class="panel currentUsage" style="height: 100%">
          <h2>运维管理</h2>
          <div class="filterSec">
            <el-date-picker
              v-model="fDefaultTime"
              type="datetimerange"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="trendIcoCount_api()"
            >
            </el-date-picker>
          </div>
          <line-chart
            :ftrendIcoCount="trendIcoCount"
            v-if="this.trendIcoCount[0]"
          ></line-chart>
          <div class="panel-footer"></div>
        </div>
      </div>
    </div>
    <!-- bottomBox end -->

    <div
          class="map panel"
          id="mapF"
          style="height: 100%; z-index: -1; width: 100%;position:fixed;top:0;"
        ></div>

  </section>
</template>

<script>
import statisTop from "./components/statisTop";
import statisBottom from "./components/statisBottom";
import pieChart from "./components/pieChart";
import barChart from "./components/barChart";
import lineChart from "./components/lineChart";
import mapStaticTop from "./components/mapStaticTop";
import triangleChart from "./components/triangleChart";

import markIconPath from "../../assets/images/markIcon.png";
import mapData from "../../assets/js/map-data.js";
mapData;

// 地图
import AMap from "AMap";

// import AMapUI from "AMapUI";

import api from "@/api/home/home.js";

export default {
  name: "index",
  components: {
    statisTop,
    statisBottom,
    pieChart,
    barChart,
    lineChart,
    mapStaticTop,
    triangleChart,
  },
  data() {
    return {
      dDefaultTime: this.$store.state.se_defaultTime,
      // fDefaultTime: [
      //   new Date("2021-6-23 00:00:00"),
      //   new Date("2021-7-12 00:00:00"),
      // ],
      fDefaultTime: this.$store.state.th_defaultTime,

      map: null,
      alarmCount: {},
      personalCount: {},
      siteCount: {},
      deviceTypeCount: {},
      trendIcoCount: [],
      rtAnalogData: {},

      htAnalogData: {},
      dayType: 1,
      eptrendIco: {},
      eptrendIcoMonth: {},
      epLoad: "",
      siteOne: {},

      name: "",

      mapPolList: [],
      colorList: [
        ["#99e", "#F33"],
        ["#ee6", "#c38"],
        ["#c38", "#F33"],
        ["#6E7", "#F33"],
        ["#6A7", "#F33"],
        ["#EF7", "#F33"],
        ["#AF7", "#F33"],
        ["#BAC", "#F33"],
        ["#BEF", "#F33"],
        ["#BBB", "#F33"],
        ["#EFA", "#F33"],
        ["#FE6", "#F33"],
        ["#7F6", "#F33"],
        ["#7dc", "#F33"],
      ],
      colorIndList: [-1, 7, 21, 26, 31, 37, 46, 52, 57, 66, 68, 71, 74, 100],

      district: null,
      polygons: [],
    };
  },
  watch: {
    dayType(val) {
      if (val == 0) {
        this.eptrendIco_api();
      } else {
        this.eptrendIcoMonth_api();
      }
    },
  },
  created() {},
  mounted() {
    this.alarmCount_api();
    this.personalCount_api();
    this.epLoad_api();
    this.siteCount_api();
    this.deviceTypeCount_api();
    this.trendIcoCount_api();
    this.rtAnalogData_api();
    this.siteList_api();
    this.htAnalogData_api();
    // this.eptrendIco_api();
    this.eptrendIcoMonth_api();

    
  },
  methods: {
    // searchSite(){
    //     this.siteList_api({"name":this.name});
    // },

    //告警总数数据对接
    alarmCount_api() {
      api.alarmCount_api().then((requset) => {
        this.alarmCount = requset.data;
      });
    },
    //运维人员
    personalCount_api() {
      api.personalCount_api().then((requset) => {
        this.personalCount = requset.data;
      });
    },
    //总实时负荷
    epLoad_api() {
      api.epLoad_api().then((requset) => {
        this.epLoad = requset.data;
      });
    },
    //站点总数
    siteCount_api() {
      api.siteCount_api().then((requset) => {
        this.siteCount = requset.data;
      });
    },

    //设备数量echarts饼图
    deviceTypeCount_api() {
      var _this = this;
      _this.$store.commit("TimeAll_function", this.dDefaultTime);
      var time = _this.$store.state.Time_Data;

      api
        .deviceTypeCount_api({
          startTime: time[0],
          endTime: time[1],
        })
        .then((requset) => {
          this.deviceTypeCount = requset.data;
        });
    },
    //故障抢修echarts折线图
    trendIcoCount_api() {
      var _this = this;
      _this.$store.commit("TimeAll_function", this.fDefaultTime);
      var time = _this.$store.state.Time_Data;

      api
        .trendIco_api({
          startTime: time[0],
          endTime: time[1],
        })
        .then((requset) => {
          this.$store.state.trendIcoCount = requset.data;
          this.trendIcoCount = requset.data;
        });
    },
    //重载运行echarts锥形图
    rtAnalogData_api() {
      api.rtAnalogData_api().then((requset) => {
        this.rtAnalogData = requset.data;
      });
    },
    //地图撒点
    siteList_api(query = {}) {
      api.siteList_api(query).then((requset) => {
        this.siteList = requset.data;
        this.initMap();
      });
    },
    //地图撒点

    // 日月年用电量
    htAnalogData_api() {
      api.htAnalogData_api().then((requset) => {
        this.htAnalogData = requset.data;
      });
    },

    // 今日昨日用电量趋势
    eptrendIco_api() {
      api.eptrendIco_api().then((requset) => {
        this.eptrendIco = requset.data;
        // console.log("this.eptrendIco");
        // console.log(this.eptrendIco[0].name);
      });
    },

    // 今日昨日用电量趋势
    eptrendIcoMonth_api() {
      api.eptrendIcoMonth_api().then((requset) => {
        this.eptrendIco = requset.data;
        // console.log("this.eptrendIco");
        // console.log(this.eptrendIco);
      });
    },

    Overview() {
      // this.$router.push({ path: "/Overview" }); //, query: { title: title }
    },

    async initMap() {
      this.map = await new AMap.Map("mapF", {
        mapStyle: "amap://styles/blue", //设置地图的显示样式
        resizeEnable: true,
        zoom: 13,
        zooms: [3, 16],
        // features: [] //清空背景道路等
      });

      var con = `<div class="siteModelBox" >
                  <h2>
                    {siteName}
                  </h2>
                  <div >
                   <div class="siteDetailInfo" >
                    <div class="infoLine">
                      <span>站点状态：</span>
                      <p>{status}</p>
                    </div>
                    <div class="infoLine">
                      <span>设备总数：</span>
                      <p>{deviceCount}</p >
                    </div>
                    <div class="infoLine">
                      <span>告警数：</span>
                      <p>{alarmPowerCount}</p >
                    </div>
                    <div class="infoLine">
                      <span>监控类型：</span>
                      <p>{deviceType}</p >
                    </div>
                    <div class="infoLine">
                      <span>电话：</span>
                      <p>{phone}</p >
                    </div>
                    <div class="infoLine">
                      <span>地址：</span>
                      <p>{siteAddress}</p >
                    </div>
                  </div>
                  </div>
                </div>`;
      var dataList = this.siteList;

      dataList.forEach(function (item) {
        let conNew = con;
        // console.log(item.siteAddress);
        conNew = conNew.replace(/{siteAddress}/g, item.siteAddress);
        conNew = conNew.replace(/{phone}/g, item.phone);
        conNew = conNew.replace(/{siteName}/g, item.siteName);
        item.content = conNew;
      });

      this.addMarker(dataList, "water");

      this.drawBounds();
    },

    addMarker(lnglats) {
      // 创建标点和点击事件
      let markers = lnglats.map((val, ind) => {
        let marker = new AMap.Marker({
          position: new AMap.LngLat(val.longitude, val.latitude),
          icon: markIconPath,

          //   icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png',
          zIndex: 9,
          extData: {
            id: ind + 1,
          },
        });
        marker.on("mouseover", async () => {
          // console.log([val.latitude, val.longitude], null, val);
          await api.siteOne_api({ siteId: val.id }).then((requset) => {
            this.siteOne = requset.data;
          });

          if (this.siteOne) {
            val.content = val.content.replace(
              /{alarmPowerCount}/g,
              this.siteOne.alarmPowerCount ? this.siteOne.alarmPowerCount : "0"
            );
            val.content = val.content.replace(
              /{status}/g,
              this.siteOne.status ? this.siteOne.status : "-"
            );
            val.content = val.content.replace(
              /{deviceCount}/g,
              this.siteOne.deviceCount ? this.siteOne.deviceCount : "0"
            );
            val.content = val.content.replace(
              /{deviceType}/g,
              this.siteOne.deviceType ? this.siteOne.deviceType : "-"
            );
          }

          await this.addMarkerInfo(
            [val.longitude, val.latitude],
            val.content,
            val
          );
        });

        marker.on("mouseout", async () => {
          this.map.clearInfoWindow();
        });
        marker.on("click", async () => {
          // localStorage.clear();
          localStorage.removeItem("Overview");
          this.$router.push({ path: "/Overview" });
          this.$store.commit("increment", val.id);
          localStorage.setItem("Overview", [val.id, val.siteName]);
        });
        return marker;
      });
      this.map.add(new AMap.OverlayGroup(markers));
      this.map.setFitView(); // 根据所有点自适应

      this.mapPolList = mapData.map((val, ind) => {
        // console.log(val)
        let color =
          this.colorList[
            this.colorIndList.findIndex(
              (value, index) =>
                value <= ind && ind < this.colorIndList[index + 1]
            )
          ];
        return [
          new AMap.Polygon({
            map: this.map,
            fillOpacity: 0.5,
            path: val[3],
            fillColor: color[0],
            strokeColor: color[1],
          }),
          new AMap.Polygon({
            map: this.map,
            fillOpacity: 0.5,
            path: val[3],
            fillColor: color[1],
            strokeColor: color[0],
          }),
        ];
      });
      this.map.on("mousemove", (e) => {
        var point = [e.lnglat.getLng(), e.lnglat.getLat()];
        var pointList = mapData.map((val) => {
          return AMap.GeometryUtil.isPointInRing(point, val[3]);
        });
        this.mapPolList.forEach((element, ind) => {
          if (pointList[ind]) {
            this.map.remove(element[0]);
            this.map.add(element[1]);
          } else {
            this.map.remove(element[1]);
            this.map.add(element[0]);
          }
        });
      });
    },
    // 添加标点
    addMarkerInfo(position, content, value = "") {
      value;
      // console.log("value");
      // console.log(value);
      this.map.clearInfoWindow();
      var infoWindow = new AMap.InfoWindow({
        isCustom: true, //使用自定义窗体
        closeWhenClickMap: true,
        content: content,
        offset: new AMap.Pixel(16, -30),
      });
      infoWindow.open(this.map, position);
    },

    // 嘉定区边界高亮 start
    drawBounds() {
      //加载行政区划插件
      if (!this.district) {
        //实例化DistrictSearch
        var that=this
        AMap.plugin("AMap.DistrictSearch", function () {
          that.district = new AMap.DistrictSearch({
            subdistrict: 0, //获取边界不需要返回下级行政区
            extensions: "all", //返回行政区边界坐标组等具体信息
            level: "district", //查询行政级别为 市
          });

          //行政区查询
          that.district.search("嘉定区", function (status, result) {
            that.map.remove(that.polygons); //清除上次结果
            that.polygons = [];
            var bounds = result.districtList[0].boundaries;
            if (bounds) {
              for (var i = 0, l = bounds.length; i < l; i++) {
                //生成行政区划polygon
                var polygon = new AMap.Polygon({
                  strokeWeight: 1,
                  path: bounds[i],  
                  fillOpacity:.2,
                  fillColor: "pink",
                  strokeColor: "pink",
                });
                that.polygons.push(polygon);
              }
            }
            that.map.add(that.polygons);
            that.map.setFitView(that.polygons); //视口自适应
          });
        });
      }
    },

    // 嘉定区边界高亮 end
  },
};
</script>






<style lang="scss">
#pickerBox {
  position: absolute;
  z-index: 9;
  top: 0.15rem;
  right: 0.15rem;
  width: 3rem;
  height: 0.425rem;
  font-size: 0.15rem;
}
.el-icon-search {
  position: absolute;
  right: 0.1375rem;
  top: 0.1rem;
  font-size: 0.2125rem;
  color: #00f4fd;
  cursor: pointer;
}

#pickerInput {
  width: 3rem;
  line-height: 0.425rem;
  padding: 0 0.125rem;
  outline: none;
  border: 1px solid #00f4fd;
  border-radius: 18px;
  background: rgba(0, 0, 0, 0);
  color: #fff;
}

#poiInfo {
  background: #fff;
}
// 自定义图标调整大小
.amap-icon img {
  width: 25px;
}
</style>
