<template>
  <el-collapse-transition>
    <div class="style_container menu" v-if="menuIsShow && list.length > 0">
      <div class="container">
        <el-tree
          ref="tree"
          :data="list"
          :props="defaultProps"
          :expand-on-click-node="true"
          :filter-node-method="filterNode"
        >
          <div class="custom-tree-node" slot-scope="{ node, data }">
            <div v-if="data.models == undefined" class="minimum">
              <span
                :class="['title', { tongji_active: data.chartIsShow }]"
                :title="node.label"
                @click="openStatisticalChart(node, data)"
              >{{ node.label }}</span>
              <span style="float: right">
                <el-button
                  :class="[
                    'singlepoint',
                    {
                      active:
                        data.singlepoint == undefined ||
                          data.singlepoint == false
                          ? false
                          : true,
                    },
                  ]"
                  type="text"
                  size="mini"
                  circle
                  @click="() => searchData(data, 'singlepoint', node)"
                ></el-button>
                <el-button
                  :class="[
                    'aggregation',
                    {
                      active:
                        data.aggregation == undefined ||
                          data.aggregation == false
                          ? false
                          : true,
                    },
                  ]"
                  type="text"
                  size="mini"
                  circle
                  @click="() => searchData(data, 'aggregation', node)"
                ></el-button>
                <el-button
                  :class="[
                    'heatmap',
                    {
                      active:
                        data.heatmap == undefined || data.heatmap == false
                          ? false
                          : true,
                    },
                  ]"
                  type="text"
                  size="mini"
                  circle
                  @click="() => searchData(data, 'heatmap', node)"
                ></el-button>
              </span>
            </div>
            <div v-else>
              <span class="title">{{ node.label }}</span>
            </div>
          </div>
        </el-tree>
      </div>
      <!-- <el-dialog
        :class="'video'"
        :visible.sync="isVideoShow"
        width="680px"
        top="7%"
        :close-on-click-modal="false"
        :before-close="closeVideo"
      >
        <video controls="controls" autoplay="autoplay" loop="loop">
          <source src="../../public/static/gcvideo.mp4" type="video/mp4" />
        </video>
      </el-dialog>-->
    </div>
  </el-collapse-transition>
</template>

<script>
import api from "@/api/menu";
import { getLayerData } from "@/utils/getLayerDataAndCreateFeatures";
import { createLayer } from "@/utils/openlayer_plugins/layer_control";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import { Fill, Stroke, Style } from "ol/style";
import * as echarts from "echarts";
import GeoJSON from "ol/format/GeoJSON";
import { transformExtent } from "ol/proj";

export default {
  props: {
    menuIsShow: {
      type: Boolean,
      default: false,
    },
    keyword: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      list: [],
      defaultProps: {
        children: "models",
        label: "title",
      },
      layerInfos: {},
      chartSource: null,
      chartLayer: null,
      isVideoShow: false,
      cityJson: null,
      countryJson: null,
    };
  },
  created() {
    $.getJSON("/static/data/shi.geojson", function (result) {
      window.cityJson = result;
    });
    $.getJSON("/static/data/xian.geojson", function (result) {
      window.countryJson = result;
    });
  },
  mounted() { },
  methods: {
    openVideo() {
      this.isVideoShow = true;
    },
    closeVideo() {
      this.isVideoShow = false;
    },
    getMenu() {
      let that = this;
      // if (this.list.length != 0) return;
      return new Promise((resolve, reject) => {
        api
          .getMenu()
          .then((result) => {
            if (result.code == 200) {
              let arr = result.content.map(function (item, index) {
                item.title = item.name;
                item.models.map(function (item_, index) {
                  item_.chartIsShow = false;
                });
                return item;
              });
              that.list = arr;
              resolve();
            } else {
              that.$message({
                type: "warning",
                message: result.message,
              });
              reject();
            }
          })
          .catch((err) => {
            that.$message({
              type: "warning",
              message: err,
            });
            reject();
          });
      });
    },

    // 清空chartSource
    clearChartSource() {
      let that = this;
      this.chartSource.getFeatures().map(function (item) {
        that.chartSource.removeFeature(item);
      });
    },
    // 清空menu统计图高亮效果
    clearChartHighLight() {
      this.list.forEach(function (item, index) {
        item.models.map(function (item_, index) {
          item_.chartIsShow = false;
        });
        return item;
      });
    },
    // 展开统计接口
    openStatisticalChart(node) {
      let that = this;
      if (node.data.chartIsShow) return;
      this.clearChartHighLight();
      let label = node.label;
      let data = node.data;
      const loading = this.$loading({
        customClass: "allPageLoading",
        lock: true,
        text: "统计数据分析获取中，请稍后！",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.searchStatisticalData(data.id, 2)
        .then((result) => {
          loading.close();
          data.chartIsShow = true;
          that.setChart(result, label);
        })
        .catch((err) => {
          loading.close();
          that.$message({
            type: "warning",
            message: "该图层不支持统计功能",
          });
        });
    },
    // 查询统计数据
    searchStatisticalData(id, level, cityCode) {
      return new Promise((resolve, reject) => {
        api
          .getStatisticalData({
            modelId: id,
            level: level,
          })
          .then((result) => {
            if (result.code == 200) {
              let arr = result.content.map(function (item) {
                item.modelId = id;
                item.value = item.total;
                item.name = item.areaName;
                item.level = level;
                return item;
              });
              if (cityCode) {
                arr = arr.filter(function (item) {
                  return item.cityCode == cityCode;
                });
              }
              resolve(arr);
            } else {
              reject(result.message);
            }
          })
          .catch((err) => {
            reject("数据获取失败");
          });
      });
    },
    // 设置Echart
    setChart(result, label) {
      let that = this;
      this.$store.commit("setChartIsShow", true);
      this.$nextTick(function () {
        let chartDom = document.querySelector("#pie");
        let myChart = echarts.init(chartDom);
        let option = {
          title: {
            text: label,
            x: "center",
            y: "top",
            top: "20px",
            textStyle: {
              fontSize: 16,
            },
          },

          tooltip: {
            trigger: "item",
          },
          legend: {
            orient: "horizontal",
            bottom: "10px",
            textStyle: {
              fontSize: 12,
            },
          },
          series: [
            {
              type: "pie",
              radius: [50, 100],
              center: ["50%", "50%"],
              data: result,
              label: {
                normal: {
                  textStyle: {
                    fontSize: 12,
                  },
                },
              },
            },
          ],
        };
        myChart.setOption(option);
        myChart.on("mouseover", function (params) {
          if (params.componentType == "series") {
            let features = cityJson.features;
            if (params.data.level == 3) {
              features = countryJson.features;
            }
            let feature = features.filter(function (item) {
              if (item.properties.code) {
                return item.properties.code.indexOf(params.data.areaCode) > -1;
              } else {
                return false;
              }
            })[0];
            that.clearChartSource();
            that.chartSource.addFeatures(
              new GeoJSON().readFeatures(
                {
                  type: "FeatureCollection",
                  features: [feature],
                },
                {
                  dataProjection: "EPSG:4326",
                  featureProjection: "EPSG:3857",
                }
              )
            );
          }
          // console.log(params);
        });
        myChart.on("click", function (params) {
          if (params.componentType == "series") {
            let features = cityJson.features;
            if (params.data.level == 3) {
              features = countryJson.features;
            }
            let feature = features.filter(function (item) {
              if (item.properties.code) {
                return item.properties.code.indexOf(params.data.areaCode) > -1;
              } else {
                return false;
              }
            })[0];
            globalVariable.map
              .getView()
              .fit(
                transformExtent(turf.bbox(feature), "EPSG:4326", "EPSG:3857")
              );
            if (params.data.level == 2) {
              that.clearChartSource();
              that
                .searchStatisticalData(
                  params.data.modelId,
                  3,
                  params.data.areaCode
                )
                .then((result) => {
                  that.setChart(result, label);
                })
                .catch((err) => {
                  that.$message({
                    type: "warning",
                    message: err,
                  });
                });
            }
          }
        });
      });
    },

    // 点位数据
    searchData(item, layerType, node) {
      item.classify = node.parent.label + "/" + node.label;
      let that = this;
      if (!this.layerInfos[item.id]) {
        this.layerInfos[item.id] = {};
      }
      if (
        this.layerInfos[item.id].source == undefined ||
        this.layerInfos[item.id].source == null
      ) {
        // 上传loading
        const loading = this.$loading({
          customClass: "allPageLoading",
          lock: true,
          text: "数据获取中，请稍后！",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        getLayerData(item, this.extendFunc, loading)
          .then((result) => {
            that.layerInfos[item.id].source = new VectorSource();
            that.layerInfos[item.id].source.addFeatures(result);
            that.layerControl(item, layerType, that.layerInfos[item.id].source);
          })
          .catch((err) => {
            that.$message({
              type: "warning",
              message: err,
            });
          });
      } else {
        // 直接使用已有source
        this.layerControl(item, layerType, this.layerInfos[item.id].source);
      }
      return;
    },

    // 弹窗回调
    extendFunc(properties, position) {
      this.$root.popup_content.html(
        `<div>名称：${properties.title}</div>
         <div>类别：${properties.classify}</div>
         <div>详情：${properties.content}</div>
        `
      );
      this.getMoreDetail(properties, position);
    },

    // 展开更多详情
    getMoreDetail(properties, position) {
      let that = this;
      api
        .getPointDetailByID({
          id: properties.id,
          modelId: properties.modelId,
        })
        .then((result) => {
          if (result.code == 200) {
            if (result.content.jsonStr)
              JSON.parse(result.content.jsonStr).forEach(function (item) {
                $(
                  `<div>${item.name}：${item.value}${item.unit}</div>`
                ).appendTo(that.$root.popup_content);
              });
            // if (properties.modelId == 9) {
            //   $(
            //     `<div><p class='moreInfo'><a onclick="openVideo()">视频监控</a>&nbsp;&nbsp;&nbsp;&nbsp;<a>更多信息</a></p></div>`
            //   ).appendTo(that.$root.popup_content);
            // } else {
            $(`<div><p class='moreInfo'><a>更多信息</a></p></div>`).appendTo(
              that.$root.popup_content
            );
            // }

            // that.$root.popup_setPositionAndRelocation(position);
          } else {
            that.$message({
              type: "error",
              message: result.message,
            });
          }
          that.$root.popup_setPositionAndRelocation(position);
        })
        .catch((err) => {
          that.$message({
            type: "error",
            message: "获取详情失败，请稍后重试。",
          });
        });
    },

    // 图层控制
    layerControl(item, layerType, source) {
      let that = this;
      if (item[layerType] == undefined || item[layerType] == false) {
        this.$set(item, layerType, true);
        this.addDifferentLayer(item, layerType, source);
      } else {
        this.$set(item, layerType, false);
        this.removeDifferentLayer(item, layerType, source);
      }
      this.$forceUpdate();
    },

    // 地图 加载 不同图层
    addDifferentLayer(item, layerType, source) {
      let str = "";
      let layer = createLayer(item, layerType, source, this.$store.state.token);
      switch (layerType) {
        case "aggregation":
          str = "聚合图";
          break;
        case "heatmap":
          str = "热力图";
          break;
        default:
          break;
      }
      globalVariable.map.addLayer(layer);
      globalVariable.map.getView().fit(source.getExtent());
      let obj = {
        title: item.title + " " + str,
        id: item.id,
        layerId: this.buildGuid("menulayer"),
        layer: layer,
        layerType: layerType,
        opacity: 1,
        show: true,
        item: item,
        removeLayer: this.removeDifferentLayer,
      };
      this.$store.dispatch("addLayerControl", obj);
      this.layerInfos[item.id][layerType] = obj;
    },

    // 地图 移除 不同图层
    removeDifferentLayer(item, layerType) {
      let type = layerType || item.layerType;
      if (item.item) {
        item.item[type] = false;
      }
      this.$store.dispatch(
        "removeLayerControl",
        this.layerInfos[item.id][type]
      );
      globalVariable.map.removeLayer(this.layerInfos[item.id][type].layer);
      this.layerInfos[item.id][type] = null;
    },

    // 搜索筛选
    filterText() {
      this.$refs.tree.filter(this.keyword);
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },

    // 清空筛选
    clearFilter() {
      if (this.$refs.tree) this.$refs.tree.filter("");
    },

    // 随机生成生成字符串
    buildGuid(options) {
      var text = "";
      var mar = options || "default";
      var possible =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      for (var i = 0; i < 18; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));
      return mar + "_" + new Date().getTime().toString() + text;
    },
  },
  computed: {
    // tokenStr() {
    //   return this.$store.state.token;
    // },
    isShowChart() {
      return this.$store.state.isShowChart;
    },
  },
  watch: {
    // tokenStr(newVal) {
    //   if (newVal != "") {
    //     this.getMenu();
    //   }
    // },
    menuIsShow(newVal) {
      let that = this;
      if (newVal) {
        this.getMenu()
          .then(() => {
            that.list = that.list.map(function (item) {
              item.show = true;
              item.open = false;
              item.chartIsShow = false;
              return item;
            });
            that.activeNames = [];
            that.nowKeyword = "";
            that.$root.popup.setPosition(undefined);
            that.clearFilter();
            if (!that.chartSource) {
              that.chartSource = new VectorSource();
              that.chartLayer = new VectorLayer({
                source: that.chartSource,
                zIndex: 3,
                style: new Style({
                  stroke: new Stroke({
                    color: "#ff9900",
                    width: 3,
                  }),
                  fill: new Fill({
                    color: "rgb(255 153 0 / 60%)",
                  }),
                }),
              });
              globalVariable.map.addLayer(that.chartLayer);
            }
          })
          .catch((err) => { });
      } else {
      }
    },
    isShowChart(newVal, oldVal) {
      if (!newVal) {
        this.clearChartSource();
        this.clearChartHighLight();
      }
    },
  },
};
</script>

<style lang="less" scoped>
@FontSize: 18px;
.menu {
  position: absolute;
  top: 55px;
  left: -5px;
}
.menu .container {
  width: 500px;
  max-height: 300px;
  overflow: hidden;
  overflow-y: auto;
  border-radius: 4px;
  padding: 5px 5px;
  box-sizing: border-box;
  -moz-box-shadow: inset 0px 0px 2px 1px #888888;
  box-shadow: inset 0px 0px 2px 1px #888888;
  .el-tree {
    background: transparent;
    color: #1c4a6f;
    /deep/ .el-tree-node__expand-icon {
      font-size: 24px;
      color: #124572;
      &.is-leaf {
        color: transparent;
      }
    }
    /deep/ .el-tree-node:hover > .el-tree-node__content {
      background: transparent;
    }
    /deep/ .el-tree-node:focus > .el-tree-node__content {
      background: transparent;
    }
    /deep/ .el-tree-node__content {
      height: 39px;
      line-height: 40px;
      font-size: @FontSize;
      border-bottom: 1px solid #eaeaea;
    }
    .custom-tree-node {
      width: 100%;
      padding-right: 15px;
      height: 100%;
      .minimum {
        width: 100%;
        font-size: 16px;
        > span {
          display: inline-block;
          vertical-align: top;
        }
        .title {
          width: 300px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          &.tongji_active {
            color: #008dff;
          }
        }
      }
    }
    .singlepoint,
    .aggregation,
    .heatmap {
      width: 28px;
      height: 28px;
    }

    .singlepoint {
      background: url(../assets/images/menu/singlepoint1.png) center center
        no-repeat;
    }
    .aggregation {
      background: url(../assets/images/menu/aggregation1.png) center center
        no-repeat;
    }
    .heatmap {
      background: url(../assets/images/menu/heatmap1.png) center center
        no-repeat;
    }
    .singlepoint.active {
      background: url(../assets/images/menu/singlepoint_active1.png) center
        center no-repeat;
    }
    .aggregation.active {
      background: url(../assets/images/menu/aggregation_active1.png) center
        center no-repeat;
    }
    .heatmap.active {
      background: url(../assets/images/menu/heatmap_active1.png) center center
        no-repeat;
    }
  }
}
</style>