<template>
  <div id="allomap">
    <Map @mapView="getMap"></Map>
    <div id="popup" class="ol-popup" style="display: none">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content" style="text-align: left">
        <span style="display: inline-block; font-size: 15px"
          >修改巡查人员：</span
        >
        <el-select
          v-model="taskCurWorker"
          placeholder="请选择"
          style="width: 50%"
          clearable
        >
          <el-option
            v-for="item in taskCheckWorkerList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-button
          id="buttonS"
          size="small"
          style="font-size: 15px"
          @click="allocateCell"
          >确定</el-button
        >
      </div>
    </div>
    <div id="allomapTool">
      <span class="allomapText">任务：{{ taskName }}</span>
      <span class="allomapText">
        <el-checkbox
          v-model="isGridLayerVisiable"
          style="width: 30px"
        ></el-checkbox
        >查看格网
      </span>
      <span class="allomapText">
        <el-checkbox
          v-model="isCellLayerVisiable"
          style="width: 30px"
          v-show="ctaskValue.length"
          @change="changeDataVis"
        ></el-checkbox
        >查看数据
        <el-select
          v-model="ctaskValue"
          placeholder="请选择数据"
          clearable
          @change="ctaskChange"
          style="padding-left: 10px"
        >
          <el-option
            v-for="item in taskValue.tableNames"
            :key="item.tableKey"
            :label="item.tableName"
            :value="item.tableKey"
          ></el-option>
        </el-select>
      </span>
      <el-button id="buttonS" @click="manageTeam" class="allomapBtn"
        >管理任务人员</el-button
      >
      <el-button id="buttonS" @click="backAllocate" class="allomapBtn"
        >返回上页</el-button
      >
    </div>
    <el-dialog
      v-dialogDrag
      class="workerTeamDialog"
      title="管理任务队伍"
      :append-to-body="true"
      :visible.sync="workerTeamVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-table
        :data="workTeamTbDt"
        :height="400"
        stripe
        highlight-current-row
        class="tb-edit"
        style="width: 100%"
      >
        <el-table-column type="index" min-width="40"></el-table-column>
        <el-table-column prop="username" label="工作人员" min-width="80">
          <template slot-scope="scope">
            <span v-if="!scope.row.isEdit">{{ scope.row.username }}</span>
            <el-select
              v-model="scope.row.username"
              placeholder="请选择"
              v-else
              @change="selectTeamWorker(scope.row)"
            >
              <el-option
                v-for="item in allWorkers"
                :key="item.id"
                :label="item.username"
                :value="item.username"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="工作角色" min-width="80">
          <template slot-scope="scope">
            <span v-if="!scope.row.isEdit">{{
              scope.row.role == 0 ? "采集人员" : "巡查人员"
            }}</span>
            <el-select v-model="scope.row.role" placeholder="请选择" v-else>
              <el-option
                v-for="item in roleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column min-width="80">
          <template slot="header">
            <el-button @click="addWorker()" id="buttonS" class="allomapBtn"
              >添加人员</el-button
            >
          </template>
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteWorker(scope.$index)"
              size="medium"
              type="text"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-button id="buttonS" @click="appendTeamWorker" class="workerBtn"
        >保存</el-button
      >
      <el-button id="buttonS" @click="cancelDialog" class="workerBtn"
        >取消</el-button
      >
    </el-dialog>

    <el-dialog
      v-dialogDrag
      class="workerTeamDialog"
      title="管理网格工作人员"
      :append-to-body="true"
      :visible.sync="gridDiaVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-table
        :data="gridTeamTbDt"
        :height="400"
        stripe
        highlight-current-row
        class="tb-edit"
        style="width: 100%"
      >
        <el-table-column type="index" min-width="40"></el-table-column>
        <el-table-column prop="username" label="工作人员" min-width="80">
          <template slot-scope="scope">
            <span v-if="!scope.row.isEdit">{{ scope.row.username }}</span>
            <el-select
              v-model="scope.row.username"
              placeholder="请选择"
              v-else
              @change="selectWorker(scope.row)"
            >
              <el-option
                v-for="item in taskWorkerList"
                :key="item.id"
                :label="item.username"
                :value="item.username"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="工作角色" min-width="80">
          <template slot-scope="scope">
            <span v-if="!scope.row.isEdit">{{
              scope.row.role == 0
                ? "采集人员"
                : scope.row.role == "采集人员"
                ? "采集人员"
                : "巡查人员"
            }}</span>
            <el-select
              v-model="scope.row.role"
              placeholder="请选择"
              v-else
              @change="selectRole(scope.row)"
            >
              <el-option
                v-for="item in gridRoleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column min-width="80">
          <template slot="header">
            <el-button @click="addGridWorker()" id="buttonS" class="allomapBtn"
              >添加人员</el-button
            >
          </template>
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteGridWorker(scope.$index)"
              size="medium"
              type="text"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-button id="buttonS" @click="appendGridWorker" class="workerBtn"
        >保存</el-button
      >
      <el-button id="buttonS" @click="cancelDialog" class="workerBtn"
        >取消</el-button
      >
    </el-dialog>
  </div>
</template>

<script>
import "ol/ol.css";
import Map from "../../Mapview/Map";
import axios from "axios";
import VectorSource from "ol/source/Vector";
import GeoJSON from "ol/format/GeoJSON";
import VectorLayer from "ol/layer/Vector";
import { Circle as CircleStyle, Fill, Stroke, Style, Text } from "ol/style";
import { ajax as request } from "@/request.js";
import Overlay from "ol/Overlay";
export default {
  name: "ManualAllocate",
  data() {
    return {
      taskId: this.$route.params.id,
      taskName: this.$route.params.name,
      ctaskValue: "",
      taskValue: {},
      taskWorkerList: [],
      taskWorkerListData: [],
      taskWorkerOriList: [],
      taskCurWorker: "",
      curGeohash: "",
      hasValue: "",
      selectedFeature: null,
      map: null,
      cUserWorker: "",
      workerTeamVisible: false,
      //任务队伍
      workTeamTbDt: [],
      roleOptions: [
        {
          value: "0",
          label: "采集人员",
        },
        {
          value: "1",
          label: "巡查人员",
        },
      ],
      gridRoleOptions: [
        {
          value: "0",
          label: "采集人员",
        },
        {
          value: "1",
          label: "巡查人员",
        },
      ],
      gridRole: "",
      gridDiaVisible: false,
      cellDiaVisible: false,
      taskCheckWorkerList: [],
      taskCheckWorkerOriList: [],
      popupCloser: {},
      container: {},
      taskCurReviewer: "",
      allWorkers: [],
      allOriWorkers: [],
      //网格工作人员
      gridTeamTbDt: [],

      highlightLineStyle: {},
      gridLayer: null,
      cellLayer: null,
      isGridLayer: false,
      clusters: null,
      isClusters: false,
      selectedByAttriFeature: null,
      isCurGridCollRole: true,
      isGridLayerVisiable: true,
      isCellLayerVisiable: false,
    };
  },
  mounted() {
    this.initWorker();
  },
  components: {
    Map,
  },
  created() {},
  watch: {
    workTeamTbDt: {
      immediate: true,
      handler() {
        this.filterTeamWorker();
      },
    },
    gridTeamTbDt: {
      immediate: true,
      handler() {
        this.filterGridWorker();
      },
      deep: true,
    },
    isCurGridCollRole: {
      immediate: true,
      handler() {
        this.filterGridWorker();
      },
    },
    isGridLayerVisiable: {
      immediate: true,
      handler() {
        if (this.gridLayer) {
          if (this.isGridLayerVisiable) {
            this.gridLayer.setVisible(true);
          } else {
            this.gridLayer.setVisible(false);
          }
        }
      },
    },
    isCellLayerVisiable: {
      immediate: true,
      handler() {
        if (this.cellLayer) {
          if (this.isCellLayerVisiable) {
            this.cellLayer.setVisible(true);
          } else {
            this.cellLayer.setVisible(false);
          }
        }
        if (this.clusters) {
          if (this.isCellLayerVisiable) {
            this.clusters.setVisible(true);
          } else {
            this.clusters.setVisible(false);
          }
        }
      },
    },
  },
  methods: {
    //根据工作角色 返回网格工作人员列表
    selectRole(row) {
      row.username = "";
      if (row.role == "巡查人员" || row.role == "1") {
        this.taskWorkerList = this.taskWorkerListData.filter(
          (item) => item.role == 1
        );
      } else {
        this.taskWorkerList = this.taskWorkerListData.filter(
          (item) => item.role == 0
        );
      }
    },
    //根据选择人员判断工作角色
    selectWorker(row) {
      let curWorker = this.taskWorkerListData.find(
        (item) => item.username == row.username
      );
      row.role = curWorker.role == 0 ? "采集人员" : "巡查人员";
    },
    selectTeamWorker(row) {
      this.filterTeamWorker();
    },
    filterTeamWorker() {
      this.allWorkers = this.allOriWorkers.filter((item) => {
        let tableID = [...new Set(this.workTeamTbDt.map((v) => v.username))];
        return !tableID.includes(item.username);
      });
    },
    //网格工作人员发生变化调用
    filterGridWorker(row) {
      let isCollector;
      if (row) {
        isCollector = row.role == 0 ? true : false;
      } else {
        isCollector = this.isCurGridCollRole;
      }
      if (isCollector) {
        let hash = {};
        //去掉网格中已经有的人
        this.taskWorkerList = this.taskWorkerOriList.filter((item) => {
          let tableID = [...new Set(this.gridTeamTbDt.map((v) => v.username))];
          return !tableID.includes(item.username);
        });
        this.taskWorkerList = this.taskWorkerList.reduce((targetData, item) => {
          var filterKey = item.username;
          hash[filterKey]
            ? ""
            : (hash[filterKey] = true && targetData.push(item));
          return targetData;
        }, []);
        this.taskWorkerListData = this.taskWorkerList.slice(0);
      } else {
        let hash = {};
        this.taskCheckWorkerList = this.taskCheckWorkerOriList.filter(
          (item) => {
            let tableID = [
              ...new Set(this.gridTeamTbDt.map((v) => v.username)),
            ];
            return !tableID.includes(item.username);
          }
        );
        this.taskCheckWorkerList = this.taskCheckWorkerList.reduce(
          (targetData, item) => {
            var filterKey = item.username;
            hash[filterKey]
              ? ""
              : (hash[filterKey] = true && targetData.push(item));
            return targetData;
          },
          []
        );
        this.taskWorkerList = this.taskCheckWorkerList;
        this.taskWorkerListData = this.taskWorkerList.slice(0);
      }
    },
    getMap(val) {
      this.map = val;
      this.mapClickQuery();
      this.initgrid(true);
      this.map.on("moveend", (e) => {
        //移除所有
        if (this.clusters) {
          if (this.isClusters) {
            this.map.removeLayer(this.clusters);
          }
          this.clusters = null;
        }
        if (this.cellLayer) {
          this.map.removeLayer(this.cellLayer);
          this.container.style.display = "none";
          this.cellLayer = null;
        }
        if (this.ctaskValue !== "" && this.isCellLayerVisiable) {
          setTimeout(this.getClusters(), 500);
        }
      });
    },
    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;
      }
      var tskId = this.taskValue.id;
      var tabName = this.ctaskValue;
      if (this.ctaskValue !== "") {
        if (zoom < 15) {
          //请求聚类图层
          this.minSize = 0;
          this.maxSize = 0;
          request({
            url: "/base/getCountByGeoHash",
            method: "post",
            params: {
              taskId: tskId,
              tableName: tabName,
              accuracy: geoHashLength,
              longitudeMin: coordinates[0],
              latitudeMin: coordinates[1],
              longitudeMax: coordinates[2],
              latitudeMax: coordinates[3],
            },
          }).then((response) => {
            if (response.data.data) {
              var result = response.data.data;
              var geojson = [];
              if (!result) {
                return;
              }
              for (var i = 0; i < result.length; i++) {
                var count = result[i].count;
                if (i == 0) {
                  this.minSize = count;
                  this.maxSize = count;
                } else {
                  if (count < this.minSize) {
                    this.minSize = count;
                  }
                  if (count > this.maxSize) {
                    this.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" } },
              };

              this.drawClusterLayer(geojsonObject);
            } else if (response.data.status == "401") {
              that.$alert(response.data.message);
              that.$router.push({ path: "/login" });
            }
          });
        } else {
          request({
            url: "/get/getDataByRangeIntersection",
            method: "post",
            params: {
              taskId: tskId,
              tableName: tabName,
              longitudeMin: coordinates[0],
              latitudeMin: coordinates[1],
              longitudeMax: coordinates[2],
              latitudeMax: coordinates[3],
            },
          }).then((response) => {
            if (response.data.data) {
              var geojson = response.data.data;
              if (!geojson) {
                return;
              }
              var geojsonObject = {
                type: "FeatureCollection",
                features: geojson,
                crs: { type: "EPSG", properties: { code: "4326" } },
              };
              this.drawCellLayer(geojsonObject);
            } else if (response.data.status == "401") {
              that.$alert(response.data.message);
              that.$router.push({ path: "/login" });
            }
          });
        }
      }
    },
    drawClusterLayer(geojsonObject) {
      if (this.clusters) {
        if (this.isClusters) {
          this.map.removeLayer(this.clusters);
          this.isClusters = false;
        }
        this.clusters = null;
      }
      if (this.cellLayer) {
        this.map.removeLayer(this.cellLayer);
        this.cellLayer = null;
      }
      var vectorSource = new VectorSource({
        features: new GeoJSON().readFeatures(geojsonObject),
      });
      var styleFunction = (feature) => {
        return new Style({
          image: new CircleStyle({
            radius:
              (15 * feature.get("count")) /
                (this.maxSize - this.minSize == 0
                  ? 15
                  : this.maxSize - this.minSize) +
              5,
            fill: new Fill({
              color: [255, 153, 0, 0.8],
            }),
          }),
          text: new Text({
            text: feature.get("count").toString(),
            fill: new Fill({
              color: "#fff",
            }),
            stroke: new Stroke({
              color: "rgba(0, 0, 0, 0.6)",
              width: 3,
            }),
          }),
        });
      };
      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(this.map.getSize());
      this.map.addLayer(this.clusters);
      this.isClusters = true;
    },
    getRange(addToMap) {
      request({
        url: "/allocation/info/cell/all",
        method: "post",
        params: {
          taskId: this.taskId,
        },
      }).then((response) => {
        // 获取数据存入config
        if (response.data.status === 200) {
          var result = response.data.data;
          if (result.features.length == 0) {
            this.$alert("获取任务范围失败，未上传数据！", "提示", {
              confirmButtonText: "确定",
            });
          } else {
            this.map.getView().fit(this.gridLayer.getSource().getExtent());
            //缩放至图层
            if (addToMap == 1) {
              this.map.addLayer(this.gridLayer);
              this.isGridLayer = true;
            }
          }
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        } else {
          this.$alert(response.data.message, "提示", {
            confirmButtonText: "确定",
          });
        }
      });
    },
    //管理队伍人员
    manageTeam() {
      //所有工作人员
      request({
        url: "/user/all_worker",
        method: "get",
      })
        .then((res) => {
          if (res.data.status == "401") {
            that.$alert(response.data.message);
            that.$router.push({ path: "/login" });
          } else {
            this.allOriWorkers = res.data.data;
            this.filterTeamWorker();
            this.workerTeamVisible = true;
          }
        })
        .catch((error) => {
          this.$notify.error({
            title: "提示",
            message: error,
          });
        });
    },
    //跳转上级
    backAllocate() {
      this.$router.push({ path: "/taskmanage" });
    },
    //任务下工作人员
    initWorker() {
      this.workTeamTbDt = [];
      request({
        url: "/allocation/info/worker?taskId=" + this.taskId,
        method: "get",
      })
        .then((res) => {
          if (res.data.status == "401") {
            that.$alert(response.data.message);
            that.$router.push({ path: "/login" });
          } else {
            this.taskWorkerOriList = res.data.data;
            this.taskWorkerList = this.taskWorkerOriList.slice(0);
            this.taskCheckWorkerOriList = this.taskWorkerOriList.filter(
              (item) => {
                return item.role !== 0;
              }
            );
            this.taskCheckWorkerList = this.taskCheckWorkerOriList.slice(0);
            this.workTeamTbDt = this.taskWorkerOriList.map((item) => {
              return {
                username: item.username,
                role: item.role,
                id: item.id,
                isEdit: false,
              };
            });
          }
        })
        .catch((error) => {
          this.$notify.error({
            title: "提示",
            message: error,
          });
        });
    },
    //获取格网数据
    initgrid(flag, isRedraw) {
      request({
        url: "/allocation/info/cell/all?taskId=" + this.taskId,
        method: "get",
      })
        .then((result) => {
          if (result.data.status == "401") {
            this.$alert(response.data.message);
            this.$router.push({ path: "/login" });
          } else {
            let geojsonObject = result.data.data;
            this.drawgridLayer(geojsonObject, flag, isRedraw);
            // 从 store 获取数据
            const taskData = this.$store.state.taskData.selectAllWithTableName || [];
            let current = taskData.find((item) => {
                  return item.id == this.taskId;
                });
            if (current) {
                this.taskValue = {
                  value: current.databaseName,
                  label: current.taskName,
                  id: current.id,
                  tableNames: current.tableNames,
                };
              }
          }
        })
        .catch((error) => {
          this.$notify.error({
            title: "提示",
            message: error,
          });
        });
    },
    //获取格网内数据
    initCell() {
      if (this.ctaskValue !== "") {
        if (this.cellLayer) {
          this.map.removeLayer(this.cellLayer);
          this.cellLayer = null;
        }
        if (this.clusters) {
          if (this.isClusters) {
            this.map.removeLayer(this.clusters);
          }
          this.clusters = null;
        }
        this.map.getView().fit(this.gridLayer.getSource().getExtent());
        this.getClusters();
      } else {
        if (this.isClusters) this.map.removeLayer(this.clusters);
        if (this.cellLayer) this.map.removeLayer(this.cellLayer);
      }
    },
    //绘制格网数据
    drawgridLayer(geojsonObject, flag, isRedraw) {
      if (this.gridLayer) {
        this.map.removeLayer(this.gridLayer);
      }
      var vectorSource = new VectorSource({
        features: new GeoJSON().readFeatures(geojsonObject),
      });
      this.gridLayer = new VectorLayer({
        id: "gridLayer",
        source: vectorSource,
        style: function (feature) {
          let worker = feature.get("users");
          let workerNames = worker
            .map((item) => {
              return "\n" + item.username;
            })
            .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: "rgba(173,216,230, 0.5)",
            }),
            text: new Text({
              text: "工作人员：" + (workerNames || "无"),
              font: "14px Microsoft YaHei",
              fill: new Fill({
                color: "#000",
              }),
            }),
          });
          return [style];
        },
      });
      if (this.map) {
        this.gridLayer.setZIndex(this.map.getSize());
        this.map.addLayer(this.gridLayer);
        //缩放至图层
        if (flag) {
          this.map.getView().fit(vectorSource.getExtent());
        }
        if (isRedraw) {
          this.selectByAttribute(this.gridLayer, "geohash");
        }
      }
    },
    selectByAttribute(layer, property) {
      let features = layer.getSource().getFeatures();
      if (property == "geohash") {
        for (let i = 0; i < features.length; i++) {
          if (features[i].get(property) === this.curGeohash) {
            this.selectedByAttriFeature = features[i];
            break;
          }
        }
      } else {
        for (let i = 0; i < features.length; i++) {
          if (features[i].get(property) === this.dataid) {
            this.selectedByAttriFeature = features[i];
            break;
          }
        }
      }
      if (this.selectedByAttriFeature) {
        this.selectedByAttriFeature.setStyle(
          this.highlightLineStyle(this.selectedByAttriFeature)
        );
      }
    },
    //绘制格网内数据
    drawCellLayer(geojsonObject) {
      if (this.cellLayer) {
        this.map.removeLayer(this.cellLayer);
      }
      let cellSource = new VectorSource({
        features: new GeoJSON().readFeatures(geojsonObject),
      });

      let styleFunction = function (feature) {
        let worker = feature.get("reviewer");
        let 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)",
            }),
            text: new Text({
              text: "巡查人员：" + (worker || "无"),
              font: "14px Microsoft YaHei",
              fill: new Fill({
                color: "red",
              }),
            }),
          }),
          LineString: new Style({
            stroke: new Stroke({
              color: "green",
              width: 3,
            }),
            text: new Text({
              text: "巡查人员：" + (worker || "无"),
              font: "14px Microsoft YaHei",
              fill: new Fill({
                color: "red",
              }),
            }),
          }),
          Polygon: new Style({
            stroke: new Stroke({
              color: "blue",
              lineDash: [4],
              width: 3,
            }),
            fill: new Fill({
              color: "rgba(0, 0, 255, 0.1)",
            }),
            text: new Text({
              text: "巡查人员：" + (worker || "无"),
              font: "14px Microsoft YaHei",
              fill: new Fill({
                color: "red",
              }),
            }),
          }),
        };
        return styles[feature.getGeometry().getType()];
      };
      this.cellLayer = new VectorLayer({
        id: "cellLayer",
        source: cellSource,
        style: styleFunction,
      });
      this.cellLayer.setZIndex(this.map.getSize());
      this.map.addLayer(this.cellLayer);
      this.selectByAttribute(this.cellLayer, "id");
    },
    closeDialog() {
      if (this.selectedFeature !== null) {
        this.selectedFeature.setStyle(undefined);
        this.selectedFeature = null;
      }
      if (this.selectedByAttriFeature !== null) {
        this.selectedByAttriFeature.setStyle(undefined);
        this.selectedByAttriFeature = null;
      }
      this.workTeamTbDt = this.workTeamTbDt.filter((item) => {
        return !item.isEdit;
      });
      this.gridTeamTbDt = this.gridTeamTbDt.filter((item) => {
        return !item.isEdit;
      });
      this.workerTeamVisible = false;
      this.gridDiaVisible = false;
      this.isCurGridCollRole = true;
    },
    cancelDialog() {
      this.closeDialog();
      this.initWorker();
      this.initgrid(false, false);
    },
    //地图点击事件
    mapClickQuery() {
      var that = this;
      this.highlightLineStyle = (feature) => {
        let worker = feature.get("users");
        let reviewer = feature.get("reviewer");
        let workerNames;
        if (worker) {
          workerNames = worker
            .map((item) => {
              return "\n" + item.username;
            })
            .toString();
        }
        if ((workerNames === "" || workerNames === undefined) && reviewer) {
          that.hasValue = "巡查人员：" + (reviewer || "无");
        } else {
          that.hasValue = "工作人员：" + (workerNames || "无");
        }
        let 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,
          }),
          text: new Text({
            text: that.hasValue,
            font: "14px Microsoft YaHei",
            fill: new Fill({
              color: "#FF6347",
            }),
          }),
        });
        return [style];
      };

      this.container = document.getElementById("popup");
      this.popupCloser = document.getElementById("popup-closer");
      this.popupCloser.addEventListener("click", () => {
        this.container.style.display = "none";
        this.selectedFeature.setStyle(undefined);
        this.selectedFeature = null;
        if (this.selectedByAttriFeature) {
          this.selectedByAttriFeature.setStyle(undefined);
          this.selectedByAttriFeature = null;
        }
        this.taskCurWorker = "";
        return false;
      });
      let overlay = new Overlay({
        element: this.container,
      });
      var that = this;
      this.map.on("singleclick", (event) => {
        if (that.selectedFeature !== null) {
          that.selectedFeature.setStyle(undefined);
          that.selectedFeature = null;
          overlay.setPosition(undefined);
          that.taskCurWorker = "";
        }
        this.map.forEachFeatureAtPixel(event.pixel, (f) => {
          that.selectedFeature = f;
          that.curGeohash = f.get("geohash");
          let gridWorkers = f.get("users");
          if (gridWorkers) {
            that.gridTeamTbDt = gridWorkers.map((item) => {
              return {
                username: item.username || "",
                role: item.role || "",
                id: item.userId || "",
                isEdit: false || "",
              };
            });
          }

          if (that.curGeohash) {
            that.gridDiaVisible = true;
          }
          let coodinate = event.coordinate;
          if (that.ctaskValue == "") {
            that.filterGridWorker();
            f.setStyle(that.highlightLineStyle);
          }
          if (that.ctaskValue !== "" && that.cellLayer) {
            f.setStyle(that.highlightLineStyle);
            if (that.ctaskValue !== "" && !that.gridDiaVisible) {
              that.dataid = f.get("id");
              overlay.setPosition(coodinate);
              that.map.addOverlay(overlay);
              that.container.style.display = "block";
            }
          }
          return true;
        });
      });
    },
    //表变更
    ctaskChange() {
      if (this.container) {
        this.container.style.display = "none";
      }
      this.initCell(true);
      if (this.ctaskValue !== "") {
        this.isCellLayerVisiable = true;
      } else {
        this.isCellLayerVisiable = false;
      }
    },
    //往某个任务的外业人员队伍里加人
    appendTeamWorker() {
      var that = this;
      let newTeamWorker = this.workTeamTbDt;
      let isContinue;
      //是否存在没填写
      isContinue = newTeamWorker.some((item) => {
        if (item.username == "") {
          this.$notify.error({
            title: "提示",
            message: "请完整填写内容",
          });
          return true;
        }
      });
      if (isContinue) {
        return;
      }
      let allobj = {};
      //新增工作人员的列表
      let appendObj = {};
      //需要删除工作人员的列表
      let deleteObj = {};
      //新队伍去遍历
      newTeamWorker.map((item) => {
        //是否前后都有来匹配
        let match = that.allOriWorkers.find((ele) => {
          return ele.username === item.username;
        });
        allobj[match.id] = item.role;
        //新的有原来的没有说明要增加
        if (
          !that.taskWorkerList.find((ele) => {
            return ele.username == item.username && ele.role == item.role;
          })
        ) {
          appendObj[match.id] = item.role;
        }
      });
      that.taskWorkerList.map((item) => {
        //原来的有 新的没有说明要删除
        if (
          !newTeamWorker.find((ele) => {
            return ele.username == item.username && ele.role == item.role;
          })
        ) {
          let match = that.allOriWorkers.find((ele) => {
            return ele.username === item.username;
          });
          deleteObj[match.id] = item.role;
        }
      });
      if (allobj) {
        let collectFd = new FormData();
        collectFd.append("taskId", this.taskId);
        collectFd.append("append", JSON.stringify(appendObj));
        collectFd.append("delete", JSON.stringify(deleteObj));
        axios({
          url: "/api/allocation/change/worker",
          method: "post",
          data: collectFd,
        })
          .then((response) => {
            if (response.data.success == true) {
              that.$notify.success({
                title: "提示",
                message: response.data.message,
              });
              if (that.ctaskValue == "") {
                that.initgrid(false, false);
              }
              that.initWorker();
            } else if (response.data.status == "401") {
              that.$alert(response.data.message);
              that.$router.push({ path: "/login" });
            } else {
              that.$notify.error({
                title: "提示",
                message: response.data.message,
              });
            }
          })
          .catch((err) => {
            that.initWorker();
            that.initgrid(false, true);
          });
      }
    },
    addWorker() {
      this.workTeamTbDt.push({
        username: "",
        id: "",
        role: "0",
        isEdit: true,
      });
    },
    deleteWorker(index) {
      if (this.workTeamTbDt[index].isEdit) {
        this.workTeamTbDt.splice(index, 1);
        return;
      }
      let workerrole = this.workTeamTbDt[index].role;
      request({
        url:
          "/allocation/worker_status?taskId=" +
          Number(this.taskId) +
          "&userId=" +
          Number(this.workTeamTbDt[index].id) +
          "&role=" +
          workerrole,
        method: "get",
      })
        .then((response) => {
          if (response.data.success) {
            let messageTip = "确认删除该人员？" + response.data.message;
            messageTip = response.data.data
              ? messageTip + "，将删除与任务的关联关系"
              : messageTip;
            this.$confirm(messageTip, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              this.workTeamTbDt.splice(index, 1);
            });
          } else if (response.data.status == "401") {
            this.$alert(response.data.message);
            this.$router.push({ path: "/login" });
          }
        })
        .catch((error) => {
          this.$notify.error({
            title: "提示",
            message: error,
          });
        });
    },
    appendGridWorker() {
      var that = this;
      let newGridWorker = this.gridTeamTbDt;
      let isContinue;
      isContinue = newGridWorker.some((item) => {
        if (item.username == "") {
          this.$notify.error({
            title: "提示",
            message: "请完整填写内容",
          });
          return true;
        }
      });
      if (isContinue) {
        return;
      }
      let allobj = {};
      newGridWorker.map((item) => {
        let match = that.taskWorkerOriList.find((ele) => {
          return ele.username === item.username;
        });
        allobj[match.id] = match.role;
      });

      if (allobj) {
        let collectFd = new FormData();
        collectFd.append("taskId", this.taskId);
        collectFd.append("geohash", this.curGeohash);
        collectFd.append("change", JSON.stringify(allobj));
        axios({
          url: "/api/allocation/change/cell_worker",
          method: "post",
          data: collectFd,
        })
          .then((response) => {
            if (response.data.success == true) {
              this.$notify.success({
                title: "提示",
                message: response.data.message,
              });
              this.gridTeamTbDt.forEach((item) => {
                item.isEdit = false;
              });
              this.initWorker();
              this.initgrid(false, true);
              this.getClusters();
            } else if (response.data.status == "401") {
              that.$alert(response.data.message);
              that.$router.push({ path: "/login" });
            } else {
              this.$notify.error({
                title: "提示",
                message: response.data.message,
              });
            }
          })
          .catch((err) => {
            this.initgrid(false, true);
          });
      }
    },
    addGridWorker() {
      this.gridTeamTbDt.push({
        username: "",
        id: "",
        role: "",
        isEdit: true,
      });
    },
    deleteGridWorker(index) {
      if (this.gridTeamTbDt[index].isEdit) {
        this.gridTeamTbDt.splice(index, 1);
        return;
      }
      this.$confirm("确认删除该人员？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.gridTeamTbDt.splice(index, 1);
      });
    },
    allocateCell() {
      let obj = {};
      let objIn = {};
      objIn[this.dataid] = Number(this.taskCurWorker);
      obj[this.ctaskValue] = objIn;
      let fd = new FormData();
      fd.append("taskId", this.taskId);
      fd.append("change", JSON.stringify(obj));
      axios({
        url: "/api/allocation/change/data",
        method: "post",
        data: fd,
      }).then((response) => {
        if (response.data.success == true) {
          this.$notify.success({
            title: "提示",
            message: response.data.message,
          });
          this.getClusters();
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        } else {
          this.$notify.error({
            title: "提示",
            message: response.data.message,
          });
        }
      });
    },
    changeDataVis() {
      if (this.isCellLayerVisiable) {
        if (this.isClusters) {
          setTimeout(this.getClusters(), 500);
          this.clusters.setVisible(true);
        }
      } else {
        if (this.isClusters) {
          this.clusters.setVisible(false);
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
#allomap {
  height: 100%;
  width: 100%;
  left: 0px;
  position: absolute;
  top: 0px;
  padding: 0px !important;

  #allomapTool {
    position: absolute;
    z-index: 10;
    right: 10px;
    top: 10px;
    left: 40px;
    background-color: #e9eef3;
    padding: 5px;
  }
  .allomapText {
    display: inline-block;
    padding: 0px 10px;
    font-size: 15px;
  }
  .allomapBtn {
    padding: 8px 10px;
  }
  .el-main {
    padding: 0;
    height: 100% !important;
  }
}
</style>
