<template>
  <div id="mapDiv">
    <Map @mapView="getMap"></Map>
    <transition
      v-on:before-enter="beforeEnter"
      v-on:enter="enter"
      v-on:before-leave="beforeLeave"
      v-on:leave="leave"
    >
      <div v-show="collapsed" id="leftPanel">
        <!--展开折叠开关-->
        <div @click.prevent="collapse" id="toLeft">
          <i
            v-if="collapsed"
            class="el-icon-arrow-left"
            title="收起"
            style="margin-top: 13px; color: #264672"
          ></i>
          <i
            v-else
            class="el-icon-arrow-right"
            title="展开"
            style="margin-top: 13px; color: #264672"
          ></i>
        </div>
        <div id="leftPanelScroll">
            <el-tabs v-model="activeName">
              <el-tab-pane label="统计分析" name="second">
                <div>
                  <el-select
                    v-model="stattask"
                    size="small"
                    style="width: 45%; margin-bottom: 15px"
                    placeholder="请选择任务"
                    @focus="getTasks1()"
                    @change="changeTask1()"
                  >
                    <el-option
                      v-for="item in stattaskoptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                  <el-select
                    id="statTable"
                    v-model="stattable"
                    size="small"
                    style="width: 45%; margin-bottom: 15px"
                    placeholder="请选择表"
                    @focus="getTables1()"
                    @change="changeTable1()"
                  >
                    <el-option
                      v-for="item in stattableoptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>

                  <el-select
                    v-model="group"
                    size="small"
                    id="sGroup"
                    style="width: 45%; margin-bottom: 15px"
                    placeholder="请选择分组字段"
                    @focus="getGroups1()"
                  >
                    <el-option
                      v-for="item in groupoptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                  <el-select
                    v-model="statfield"
                    size="small"
                    id="statField"
                    style="width: 45%; margin-bottom: 15px"
                    placeholder="请选择统计字段"
                    @focus="getStats1()"
                  >
                    <el-option
                      v-for="item in statfieldoptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                  <el-button
                    size="small"
                    icon="el-icon-search"
                    class="dateBtn"
                    @click="getEchart1()"
                    >确定</el-button
                  >
                  <div
                    id="myChart"
                    style="width: 97%; height: 650px; margin-bottom: 15px"
                  ></div>
                </div>
              </el-tab-pane>
            </el-tabs>
        </div>
      </div>
    </transition>
    <el-dialog
      v-dialogDrag
      class="infoDialog2"
      title="数据信息"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
    >
      <p>
        请选择查看数据：
        <el-select
          v-model="currentFeatureId"
          style="width: 55%"
          placeholder="请选择数据id"
        >
          <el-option
            v-for="item in FeaturesId"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </p>
      <featureInfo :data="Info" style="margin: 0 auto" />
    </el-dialog>
  </div>
</template>

<script>
const Map = () => import("../Mapview/Map");
const featureInfo = () => import("../DataManagement/featureInfo");

import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import GeoJSON from "ol/format/GeoJSON";
import { ajax as request } from "@/request.js";
import "ol/ol.css";
import { Circle as CircleStyle, Fill, Stroke, Style, Text } from "ol/style";
import Select from "ol/interaction/Select";
let echarts = require("echarts/lib/echarts");
require("echarts/lib/chart/bar");
require("echarts/lib/component/title");
require("echarts/lib/component/tooltip");
require("echarts/lib/component/dataZoom");
require("echarts/lib/component/legend");

export default {
  name: "ViewTask",
  data() {
    return {
      FeaturesId: [],
      currentFeatureId: "",
      distribute: false,
      minSize: "",
      maxSize: "",
      clusters: null,
      isClusters: false,
      vectorLayer: null,
      isVectorLayer: false,
      cellLayer: null,
      dialogVisible: false,
      selectclick: null,
      Info: {},
      vectorSource: null,
      feature: null,

      collapsed: true,
      drawer: false,
      activeName: "second",
      total: "",
      myChart1: null,
      myChart2: null,
      data: "",
      ratio: "",
      task: "",
      table: "",
      date: "",
      radio: "day",
      value: "",
      taskoptions: [],
      tableoptions: [],
      myChart: null,
      min: [],
      max: [],
      avg: [],
      count: [],
      sum: [],
      groupField: [],
      stattask: "",
      stattable: "",
      statfield: "",
      group: "",
      statfieldoptions: [],
      groupoptions: [],
      stattaskoptions: [],
      stattableoptions: [],
    };
  },
  components: {
    Map,
    featureInfo,
  },
  created() {
    this.initList();
  },
  methods: {
    getMap(val) {
      this.map = val;
      let that = this;
      this.map.on("moveend", function (e) {
        //移除所有
        if (that.clusters) {
          if (that.isClusters) {
            that.map.removeLayer(that.clusters);
            that.isClusters = false;
          }
          that.clusters = null;
        }
        if (that.vectorLayer) {
          if (that.isVectorLayer) {
            that.map.removeLayer(that.vectorLayer);
            that.map.removeInteraction(that.selectclick);
            that.isVectorLayer = false;
          }
          that.vectorLayer = null;
          that.selectclick = null;
        }
        if (that.distribute && that.cellLayer) {
          that.debounce(that.getClusters(), 500);
        }
      });
    },
    debounce(fn, delay) {
      let timer = null; //借助闭包
      return function () {
        if (timer) {
          clearTimeout(timer);
          timer = setTimeout(fn, delay);
        } else {
          timer = setTimeout(fn, delay);
        }
      };
    },
    // 初始化任务清单
    initList() {},
    // 左侧面板收缩动画
    collapse() {
      this.collapsed = !this.collapsed;
    },
    beforeEnter: function (el) {
      el.style.transform = "translate(410px,0px)";
    },
    enter: function (el, done) {
      el.style.transform = "translate(0px,0px)";
      el.style.transition = "all 0.6s ease";
      done();
    },
    beforeLeave: function (el) {
      el.style.transform = "translate(0px,0px)";
    },
    leave: function (el, done) {
      el.style.transform = "translate(-425px,0px)";
      el.style.transition = "all 0.6s ease";
      // done();
    },
    handleClose(done) {
      done();
    },
    changeTable1() {
      this.statfield = "";
      this.group = "";
      //清空
      //清空
      if (this.clusters) {
        if (this.isClusters) {
          this.map.removeLayer(this.clusters);
          this.isClusters = false;
        }
        this.clusters = null;
      }
      if (this.vectorLayer) {
        if (this.isVectorLayer) {
          this.map.removeLayer(this.vectorLayer);
          this.map.removeInteraction(this.selectclick);
          this.isVectorLayer = false;
        }
        this.vectorLayer = null;
        this.selectclick = null;
      }
      this.cellLayer = null;
      if (this.stattable == "") {
        this.distribute = false;
      } else {
        this.distribute = true;
        this.getRange(0);
      }
    },
    changeTask1() {
      this.stattable = "";
      this.statfield = "";
      this.group = "";
      if (this.clusters) {
        if (this.isClusters) {
          this.map.removeLayer(this.clusters);
          this.isClusters = false;
        }
        this.clusters = null;
      }
      if (this.vectorLayer) {
        if (this.isVectorLayer) {
          this.map.removeLayer(this.vectorLayer);
          this.map.removeInteraction(this.selectclick);
          this.isVectorLayer = false;
        }
        this.vectorLayer = null;
        this.selectclick = null;
      }
      this.cellLayer = null;
    },
    initEchart1() {
      if (this.myChart) {
        this.myChart.clear();
      }
      this.myChart = echarts.init(document.getElementById("myChart"));
      // 绘制图表
      let that = this;
      this.myChart.setOption({
        backgroundColor: "#323a5e",
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
          formatter: function (param) {
            if (param.length > 0) {
              var res = param[0].name;
              for (let i = 0; i < param.length; i++) {
                res =
                  res + "<br/>" + param[i].seriesName + "：" + param[i].value;
              }
              for (let i = 0; i < that.groupField.length; i++) {
                if (that.groupField[i] === param[0].name) {
                  if (that.count[i]) {
                    res = res + "<br/>" + "count:" + that.count[i];
                  }
                }
              }
              return res;
            }
          },
        },
        grid: {
          left: "2%",
          right: "4%",
          bottom: "14%",
          top: "16%",
          containLabel: true,
        },
        legend: {
          data: ["min", "avg", "max", "sum"],
          right: 10,
          top: 12,
          textStyle: {
            color: "#fff",
          },
          itemWidth: 12,
          itemHeight: 10,
        },
        xAxis: {
          type: "category",
          data: this.groupField,
          axisLine: {
            lineStyle: {
              color: "white",
            },
          },
          axisLabel: {
            textStyle: {
              fontFamily: "Microsoft YaHei",
            },
          },
        },
        yAxis: {
          type: "value",
          //                    max:'1200',
          axisLine: {
            show: false,
            lineStyle: {
              color: "white",
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "rgba(255,255,255,0.3)",
            },
          },
          axisLabel: {},
        },
        dataZoom: [
          {
            show: true,
            height: 12,
            xAxisIndex: [0],
            bottom: "8%",
            start: 10,
            end: 90,
            handleIcon:
              "path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z",
            handleSize: "110%",
            handleStyle: {
              color: "#d3dee5",
            },
            textStyle: {
              color: "#fff",
            },
            borderColor: "#90979c",
          },
          {
            type: "inside",
            show: true,
            height: 15,
            start: 1,
            end: 35,
          },
        ],
        series: [
          {
            name: "min",
            type: "bar",
            barWidth: "15%",
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: "#fccb05",
                  },
                  {
                    offset: 1,
                    color: "#f5804d",
                  },
                ]),
                barBorderRadius: 12,
              },
            },
            data: this.min,
          },
          {
            name: "avg",
            type: "bar",
            barWidth: "15%",
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: "#8bd46e",
                  },
                  {
                    offset: 1,
                    color: "#09bcb7",
                  },
                ]),
                barBorderRadius: 11,
              },
            },
            data: this.avg,
          },
          {
            name: "max",
            type: "bar",
            barWidth: "15%",
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: "#248ff7",
                  },
                  {
                    offset: 1,
                    color: "#6851f1",
                  },
                ]),
                barBorderRadius: 11,
              },
            },
            data: this.max,
          },
          {
            name: "sum",
            type: "bar",
            barWidth: "15%",
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: "#33CCFF",
                  },
                  {
                    offset: 1,
                    color: "#0096f3",
                  },
                ]),
                barBorderRadius: 11,
              },
            },
            data: this.sum,
          },
        ],
      });
    },
    getTasks1() {
      this.stattaskoptions = [];
      let that = this;
      // 从 store 获取数据
      const taskData = that.$store.state.taskData.selectTaskHasCreated || [];
      for (var i = 0; i < taskData.length; i++) {
            that.stattaskoptions.push({
          value: taskData[i].id,
          label: taskData[i].taskName,
            });
          }
    },
    getTables1() {
      if (this.stattask === "") {
        this.$alert("请先选择任务！", "提示", {
          confirmButtonText: "确定",
        });
        document.getElementById("statTable").blur();
      } else {
        var taskname = "";
        for (var i = 0; i < this.stattaskoptions.length; i++) {
          if (this.stattask == this.stattaskoptions[i].value) {
            taskname = this.stattaskoptions[i].label;
            break;
          }
        }
        this.stattableoptions = [];
        let that = this;
        request({
          url: "/statistic/getTables",
          method: "post",
          params: {
            tskName: taskname,
          },
        }).then(function (response) {
          // 获取数据存入config
          if (response.data.status == "401") {
            that.$alert(response.data.message);
            that.$router.push({ path: "/login" });
          } else if (response.status === 200) {
            var json = response.data;
            for (var key in json) {
              that.stattableoptions.push({
                value: key,
                label: json[key],
              });
            }
          }
        });
      }
    },
    getStats1() {
      if (this.stattask === "") {
        this.$alert("请先选择任务！", "提示", {
          confirmButtonText: "确定",
        });
        document.getElementById("statField").blur();
      } else if (this.stattable === "") {
        this.$alert("请先选择表！", "提示", {
          confirmButtonText: "确定",
        });
        document.getElementById("statField").blur();
      } else {
        var taskname = "";
        for (var i = 0; i < this.stattaskoptions.length; i++) {
          if (this.stattask == this.stattaskoptions[i].value) {
            taskname = this.stattaskoptions[i].label;
            break;
          }
        }
        this.statfieldoptions = [];
        this.groupoptions = [];
        let that = this;
        request({
          url: "/basicStat/getFields",
          method: "post",
          params: {
            tskName: taskname,
            tblName: that.stattable,
          },
        }).then(function (response) {
          // 获取数据存入config
          var Fields = [];
          if (response.data.status == "401") {
            that.$alert(response.data.message);
            that.$router.push({ path: "/login" });
          } else if (response.status === 200) {
            var json = response.data;
            for (var key in json) {
              Fields.push(json[key]);
            }
          }
          for (var i = 0; i < Fields[0].length; i++) {
            for (let key in Fields[0][i]) {
              that.statfieldoptions.push({
                value: key,
                label: Fields[0][i][key],
              });
            }
          }
          for (let i = 0; i < Fields[1].length; i++) {
            for (let key in Fields[1][i]) {
              that.groupoptions.push({
                value: key,
                label: Fields[1][i][key],
              });
            }
          }
        });
      }
    },
    getGroups1() {
      if (this.stattask === "") {
        this.$alert("请先选择任务！", "提示", {
          confirmButtonText: "确定",
        });
        document.getElementById("sGroup").blur();
      } else if (this.stattable === "") {
        this.$alert("请先选择表！", "提示", {
          confirmButtonText: "确定",
        });
        document.getElementById("sGroup").blur();
      } else {
        this.statfieldoptions = [];
        this.groupoptions = [];
        var taskname = "";
        for (var i = 0; i < this.stattaskoptions.length; i++) {
          if (this.stattask == this.stattaskoptions[i].value) {
            taskname = this.stattaskoptions[i].label;
            break;
          }
        }
        let that = this;
        request({
          url: "/basicStat/getFields",
          method: "post",
          params: {
            tskName: taskname,
            tblName: that.stattable,
          },
        }).then(function (response) {
          // 获取数据存入config
          var Fields = [];
          if (response.data.status == "401") {
            that.$alert(response.data.message);
            that.$router.push({ path: "/login" });
          } else if (response.status === 200) {
            var json = response.data;
            for (var key in json) {
              Fields.push(json[key]);
            }
          }
          for (var i = 0; i < Fields[0].length; i++) {
            for (let key in Fields[0][i]) {
              that.statfieldoptions.push({
                value: key,
                label: Fields[0][i][key],
              });
            }
          }
          for (let i = 0; i < Fields[1].length; i++) {
            for (let key in Fields[1][i]) {
              that.groupoptions.push({
                value: key,
                label: Fields[1][i][key],
              });
            }
          }
        });
      }
    },
    getRange(addToMap) {
      let that = this;
      request({
        url: "/allocation/info/cell/all",
        method: "post",
        params: {
          taskId: that.stattask,
        },
      }).then(function (response) {
        // 获取数据存入config
        if (response.data.status === 200) {
          var result = response.data.data;
          if (result.features.length != 0) {
            that.drawCellLayer(result);
            that.map.getView().fit(that.cellLayer.getSource().getExtent());
            that.getClusters();
          } else {
            that.$message.info("获取任务范围失败，未上传数据！");
          }
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        }
      });
    },
    getClusters() {
      var zoom = 0;
      zoom = this.map.getView().getZoom();
      //获取地图范围
      var coordinates = this.map.getView().calculateExtent(this.map.getSize());
      var geoHashLength = "";
      switch (zoom) {
        case 8:
        case 9:
          geoHashLength = 4;
          break;
        case 10:
        case 11:
        case 12:
          geoHashLength = 5;
          break;
        case 13:
        case 14:
        case 15:
        case 16:
          geoHashLength = 6;
          break;
        case 17:
        case 18:
        case 19:
        case 20:
          geoHashLength = 7;
          break;
        default:
          geoHashLength = 3;
      }
      if (this.distribute) {
        if (zoom < 15) {
          //请求聚类图层
          let that = this;
          that.minSize = 0;
          that.maxSize = 0;
          request({
            url: "/base/getCountByGeoHash",
            method: "post",
            params: {
              taskId: that.stattask,
              tableName: that.stattable,
              accuracy: geoHashLength,
              longitudeMin: coordinates[0],
              latitudeMin: coordinates[1],
              longitudeMax: coordinates[2],
              latitudeMax: coordinates[3],
            },
          }).then(function (response) {
            if (response.data.success) {
              if (response.data.data) {
                var result = response.data.data;
                var geojson = [];
                for (var i = 0; i < result.length; i++) {
                  var count = result[i].count;
                  if (i == 0) {
                    that.minSize = count;
                    that.maxSize = count;
                  } else {
                    if (count < that.minSize) {
                      that.minSize = count;
                    }
                    if (count > that.maxSize) {
                      that.maxSize = count;
                    }
                  }
                  //存入count
                  var geojson1 = result[i].feature;
                  geojson1.properties = {};
                  geojson1.properties.count = count;
                  geojson.push(result[i].feature);
                }
                var geojsonObject = {
                  type: "FeatureCollection",
                  features: geojson,
                  crs: { type: "EPSG", properties: { code: "4326" } },
                };
                that.drawClusterLayer(geojsonObject);
              } else that.$message.info("获取范围内数据为空！");
            } else if (response.data.status == "401") {
              that.$alert(response.data.message);
              that.$router.push({ path: "/login" });
            }
          });
        } else {
          let that = this;
          request({
            url: "/get/getDataByRangeIntersection",
            method: "post",
            params: {
              taskId: that.stattask,
              tableName: that.stattable,
              longitudeMin: coordinates[0],
              latitudeMin: coordinates[1],
              longitudeMax: coordinates[2],
              latitudeMax: coordinates[3],
            },
          }).then(function (response) {
            if (response.data.success) {
              if (response.data.data) {
                var geojson = response.data.data;
                var geojsonObject = {
                  type: "FeatureCollection",
                  features: geojson,
                  crs: { type: "EPSG", properties: { code: "4326" } },
                };
                that.drawVectorLayer(geojsonObject);
              } else {
                that.$message.info("获取范围内数据为空！");
              }
            } else if (response.data.status == "401") {
              that.$alert(response.data.message);
              that.$router.push({ path: "/login" });
            }
          });
        }
      }
    },
    drawCellLayer(geojsonObject) {
      //
      if (this.cellLayer) {
        this.map.removeLayer(this.cellLayer);
      }
      var vectorSource = new VectorSource({
        features: new GeoJSON().readFeatures(geojsonObject),
      });
      this.cellLayer = new VectorLayer({
        source: vectorSource,
      });
      this.cellLayer.setZIndex(5);
    },
    drawClusterLayer(geojsonObject) {
      if (this.clusters) {
        if (this.isClusters) {
          this.map.removeLayer(this.clusters);
          this.isClusters = false;
        }
        this.clusters = null;
      }
      if (this.vectorLayer) {
        if (this.isVectorLayer) {
          this.map.removeLayer(this.vectorLayer);
          this.map.removeInteraction(this.selectclick);
          this.isVectorLayer = false;
        }
        this.vectorLayer = null;
        this.selectclick = null;
      }
      var vectorSource = new VectorSource({
        features: new GeoJSON().readFeatures(geojsonObject),
      });
      let that = this;
      this.clusters = new VectorLayer({
        source: vectorSource,
        style: function (feature) {
          let count = feature.get("count").toString();
          let style = new Style({
            stroke: new Stroke({
              lineDash: [1, 2, 3, 4, 5, 6],
              color: "rgba(70,130,180, 0.9)",
              width: 2,
            }),
            fill: new Fill({
              color: [255, 153, 0, 0.8],
            }),
            text: new Text({
              text: feature.get("count").toString(),
              font: "16px Microsoft YaHei",
              fill: new Fill({
                color: "#fff",
              }),
              stroke: new Stroke({
                color: "rgba(0, 0, 0, 0.6)",
                width: 3,
              }),
            }),
          });
          return [style];
        },
      });
      this.clusters.setZIndex(4);
      this.map.addLayer(this.clusters);
      this.isClusters = true;
    },
    drawVectorLayer(geojsonObject) {
      if (this.clusters) {
        if (this.isClusters) {
          this.map.removeLayer(this.clusters);
          this.isClusters = false;
        }
        this.clusters = null;
      }
      if (this.vectorLayer) {
        if (this.isVectorLayer) {
          this.map.removeLayer(this.vectorLayer);
          this.map.removeInteraction(this.selectclick);
          this.isVectorLayer = false;
        }
        this.vectorLayer = null;
        this.selectclick = null;
      }
      this.vectorSource = new VectorSource({
        features: new GeoJSON().readFeatures(geojsonObject),
      });
      var allfearures = this.vectorSource.getFeatures();
      for (var i = 0; i < allfearures.length; i++) {
        allfearures[i].setId(allfearures[i].get("id"));
      }
      var styles = {
        Point: new Style({
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: "rgba(173,216,230)",
            }),
            stroke: new Stroke({
              lineDash: [1, 2, 3, 4, 5, 6],
              color: "rgba(70,130,180)",
              width: 2,
            }),
          }),
          stroke: new Stroke({
            lineDash: [1, 2, 3, 4, 5, 6],
            color: "rgba(70,130,180)",
            width: 2,
          }),
          fill: new Fill({
            color: "rgba(173,216,230)",
          }),
        }),
        LineString: new Style({
          stroke: new Stroke({
            color: "green",
            width: 3,
          }),
        }),
        Polygon: new Style({
          stroke: new Stroke({
            color: "blue",
            lineDash: [4],
            width: 3,
          }),
          fill: new Fill({
            color: "rgba(0, 0, 255, 0.1)",
          }),
        }),
      };
      var styleFunction = function (feature) {
        return styles[feature.getGeometry().getType()];
      };
      this.vectorLayer = new VectorLayer({
        id: "vectorlayer",
        source: this.vectorSource,
        style: styleFunction,
      });
      this.vectorLayer.setZIndex(4);
      this.map.addLayer(this.vectorLayer);
      this.isVectorLayer = true;
      let this1 = this;
      this.selectclick = new Select({
        layers: [this.vectorLayer],
        style: new Style({
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: "yellow",
            }),
            stroke: new Stroke({
              color: "#37eed0",
              width: 3,
            }),
          }),
          fill: new Fill({
            color: "yellow",
          }),
          stroke: new Stroke({
            color: "#37eed0",
            width: 3,
          }),
        }),
      });
      this.selectclick.on("select", function (e) {
        this1.FeaturesId = [];
        var features = e.selected;
        if (features.length > 0) {
          this1.dialogVisible = true;
          let that = this1;
          var feature = features[0];
          var type = feature.getGeometry().getType();
          var tmp = 1;
          if (type == "LineString" || type == "Point") {
            that.FeaturesId.push({
              value: feature.get("id"),
              label: feature.get("id"),
            });
            that.currentFeatureId = feature.get("id");
            tmp = 0;
          }
          this.getFeatures().clear();
          var coordinate = e.mapBrowserEvent.coordinate;
          var Features = that.vectorSource.getFeaturesAtCoordinate(coordinate);
          for (var i = 0; i < Features.length; i++) {
            that.FeaturesId.push({
              value: Features[i].get("id"),
              label: Features[i].get("id"),
            });
            if (i == 0 && tmp == 1) {
              that.currentFeatureId = Features[i].get("id");
            }
          }
        }
      });
      this.map.addInteraction(this.selectclick);
    },
    getEchart1() {
      if (this.stattask === "") {
        this.$alert("请选择任务！", "提示", {
          confirmButtonText: "确定",
        });
        return;
      }
      if (this.stattable === "") {
        this.$alert("请选择表！", "提示", {
          confirmButtonText: "确定",
        });
        return;
      }
      if (this.statfield === "") {
        this.$alert("请选择统计字段！", "提示", {
          confirmButtonText: "确定",
        });
        return;
      }
      if (this.group === "") {
        this.$alert("请选择分组字段！", "提示", {
          confirmButtonText: "确定",
        });
        return;
      }
      var taskname = "";
      for (var i = 0; i < this.stattaskoptions.length; i++) {
        if (this.stattask == this.stattaskoptions[i].value) {
          taskname = this.stattaskoptions[i].label;
          break;
        }
      }
      this.distribute = true;
      let that = this;
      request({
        url: "/basicStat/stat",
        method: "post",
        params: {
          tskName: taskname,
          tblName: that.stattable,
          statField: that.statfield,
          groupField: that.group,
        },
      }).then(function (response) {
        // 获取数据存入config
        if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        } else if (response.status === 200) {
          if (response.data && response.data.length != 0) {
            that.avg = [];
            that.min = [];
            that.max = [];
            that.sum = [];
            that.count = [];
            that.groupField = [];
            var data = response.data;
            for (var i = 0; i < data.length; i++) {
              for (var key in data[i]) {
                if (key === "avg") {
                  that.avg.push(data[i][key]);
                } else if (key === "min") {
                  that.min.push(data[i][key]);
                } else if (key === "max") {
                  that.max.push(data[i][key]);
                } else if (key === "count") {
                  that.count.push(data[i][key]);
                } else if (key === "sum") {
                  that.sum.push(data[i][key]);
                }
                if (key === that.group) {
                  that.groupField.push(data[i][key]);
                }
              }
            }
            that.initEchart1();
          } else {
            that.$alert("获取数据为空！");
            if (that.myChart) {
              that.myChart.clear();
            }
          }
        } else that.$alert(response.message);
      });
    },
    setCurrentStyle() {
      if (this.currentFeatureId !== "") {
        this.getFeatureData();
        //改变样式
        if (this.feature) {
          this.feature.setStyle(undefined);
        }
        this.feature = this.vectorSource.getFeatureById(this.currentFeatureId);
        var style = new Style({
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: "yellow",
            }),
            stroke: new Stroke({
              color: "#37eed0",
              width: 3,
            }),
          }),
          fill: new Fill({
            color: "yellow",
          }),
          stroke: new Stroke({
            color: "#37eed0",
            width: 3,
          }),
        });
        this.feature.setStyle(style);
      } else {
        if (this.feature) {
          this.feature.setStyle(undefined);
          this.feature = null;
        }
      }
    },
    clearAll() {
      this.currentFeatureId = "";
      this.Info = {};
      this.FeaturesId = [];
    },
    getFeatureData() {
      if (this.currentFeatureId !== "") {
        let that = this;
        //获取数据
        request({
          url: "/get/getDataById",
          method: "post",
          params: {
            taskId: that.stattask,
            tableName: that.stattable,
            polygonId: that.currentFeatureId,
            requestor: "browser",
          },
        }).then(function (response) {
          if (response.data.success == true) {
            var jsondata = response.data.data;
            var imagedata = [];
            var videodata = [];
            for (var i = 0; i < jsondata.mediaFileURLs.length; i++) {
              if (
                jsondata.mediaFileURLs[i].substring(
                  jsondata.mediaFileURLs[i].length - 3
                ) == "jpg"
              ) {
                imagedata.push(jsondata.mediaFileURLs[i]);
              } else if (
                jsondata.mediaFileURLs[i].substring(
                  jsondata.mediaFileURLs[i].length - 3
                ) == "avi"
              ) {
                videodata.push(jsondata.mediaFileURLs[i]);
              }
            }
            jsondata.imagedata = imagedata;
            jsondata.videodata = videodata;
            that.Info = jsondata;
          } else if (response.data.status == "401") {
            that.$alert(response.data.message);
            that.$router.push({ path: "/login" });
          }
        });
      }
    },
  },
  watch: {
    dialogVisible: {
      handler() {
        if (this.dialogVisible == false) {
          this.getClusters();
          this.clearAll();
        }
      },
    },
    currentFeatureId: {
      handler() {
        if (this.vectorLayer && this.currentFeatureId !== "") {
          this.setCurrentStyle();
        }
      },
    },
  },
};
</script>

<style scoped lang='scss'>
.taskChoser {
  margin: 5px 0px 5px 0px;
}
.el-input__inner {
  >>> &::placeholder {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: #c0c4cc;
  }
}
</style>
