<template>
  <el-dialog
      title="围栏设置"
      :visible.sync="centerDialogVisible"
      width="70vw"
      @closed="onDialogClose"
  >
    <div v-if="!destroyed" class="trail-dialog-content" style="width: 100%;height: 70vh;">
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="围栏名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
      </el-form>
      <bd-map :loaded="loaded" map-id="room-map"/>

    </div>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="!form.id" type="primary" :disabled="drawState" @click="startDraw">
        {{ drawState ? "双击退出绘制" : "绘制围栏" }}
      </el-button>
      <el-button type="primary" @click="saveEdit">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>

import BdMap from '@/components/map/index.vue';
import maphandle from '@/components/map/maphandle';
import dayjs from 'dayjs';
import {addFenceInfo, updateFenceInfo} from "@/api/bd/fenceInfo";
// import {uuid} from "@/utils";

export default {
  name: 'draw-fence-dialog',
  mixins: [maphandle],
  components: {
    BdMap
  },
  data() {
    return {
      centerDialogVisible: false,
      locationMarkers: {},
      mapIns: null,
      fencePolyLayer: null,
      fence: {},
      destroyed: true,
      playLine: null,
      editingDrawGeom: null,
      drawState: false,
      drawtool: null,
      form: {
        name: '',
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入围栏名称',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  // 组件卸载前清空图层信息
  beforeDestroy() {
    this.markLayer && this.mapIns.removeLayersById('markerLayer');
    this.fencePolyLayer && this.fencePolyLayer.cust.clearLayer()
  },
  created() {

  },
  mounted() {
  },
  methods: {
    dayjs,
    onDialogClose() {
      this.drawtool?.disable();
      this.destroyed = true;
    },
    loaded(map) {
      this.markLayer = new BDLayers.Lib.Layer.CBVectorLayer('markerLayer', true);
      map.addCustomLayers(this.markLayer, 99);
      this.mapIns = map;
      map.setPitch(0);
      map.setCenter([118.86895, 32.01326]);
      this.fencePolyLayer = this.createLayer(map);
      this.addFence()
      this.initDrawTool(map);
    },
    initDrawTool(mapIns) {
      // 地图绘制工具
      this.drawtool = new BDLayers.Lib.Tools.CBDrawTool('myTool', mapIns, 'Polygon', true);
      // 监听图形编辑
      this.drawtool.on('selectDraw', geom => {
        this.editingDrawGeom = geom.target.geometry ? geom.target.geometry : geom.target.geom
            ? geom.target.geom
            : geom.target;
        if (this.editingDrawGeom.isEditing && this.editingDrawGeom.isEditing()) {
          // 点击地图 图形取消编辑状态
          mapIns.map.once('click', () => {
            this.editingDrawGeom.endEdit();
          });
        } else {
          mapIns.map.once('click', () => {
            this.editingDrawGeom = null;
          });
        }
      });
      this.drawtool.on('drawend', (geom) => {
        this.editingDrawGeom = geom.target.geometry ? geom.target.geometry : geom.target.geom
            ? geom.target.geom
            : geom.target;
        this.drawState = false;
      });
    },
    addFence() {
      if (!this.fence) {
        return;
      }
      const {
        id,
        defenceName,
        poly,
      } = this.fence;
      const polygon = this.custDrawPoly({
        name: defenceName,
        coordinates: this.polygonToCoordinates(poly),
        symbol: {
          lineColor: 'rgba(241,0,23,0.49)',
          lineWidth: 2,
          polygonFill: 'rgba(241,0,23,0.49)',
          polygonOpacity: 0.4,
        },
        bizAttr: {
          id,
          name: defenceName
        },
      });
      this.fence = {
        id,
        name: defenceName,
        polygon,
      }
      this.editFence(this.fence)
    },
    /**
     *
     * @param coordinates
     *  [
     *           [
     *             [118.86318437, 31.52265586],
     *             [118.86620514, 31.52541921],
     *             [118.86520697, 31.52406319],
     *             [118.86318437, 31.52265586],
     *           ],
     *         ]
     * @param symbol
     * @param bizAttr
     * @param labelSymbol
     * @returns {BDLayers.Lib.Overlays.Polygon}
     */
    custDrawPoly({
                   name = '多边形',
                   coordinates,
                   symbol = {},
                   bizAttr = {},
                   labelSymbol = {},
                 }) {
      return this.drawPoly({
        name,
        coordinates,
        symbol,
        bizAttr,
        labelSymbol
      }, this.fencePolyLayer)
    },
    cancelEdit() {
      this.drawtool.clear();
    },
    cancel() {
      this.centerDialogVisible = false;
    },
    saveEdit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const resultCoor = [];
          const coordinates = [];
          this.editingDrawGeom._coordinates.forEach(coor => {
            const {
              x,
              y,
            } = coor;
            resultCoor.push(`${x} ${y}`);
            coordinates.push([x, y]);
          });
          resultCoor.push(resultCoor[0]);
          this.form.poly = `POLYGON((${resultCoor.join(',')}))`;
          if (!this.form.id) {
            await addFenceInfo(this.formatParams(this.form))
            this.$message({
              type: 'success',
              message: '围栏保存成功',
            });
            this.$emit('onSuccess');
          } else {
            await updateFenceInfo(this.formatParams(this.form))
            this.$message({
              type: 'success',
              message: '围栏编辑成功',
            });
            this.$emit('onSuccess');
          }
          this.drawtool.clear();
          this.drawPoly({
            coordinates: coordinates,
            symbol: {
              lineColor: 'rgba(241,0,23,0.49)',
              lineWidth: 2,
              polygonFill: 'rgba(241,0,23,0.49)',
              polygonOpacity: 0.4,
            },
            labelSymbol: {
              labelText: this.form.name,
            },
            bizAttr: this.form,
          });
          this.editingDrawGeom = null;
          this.editState = false;
          this.$refs.form.resetFields();
        } else {
          return false;
        }
      });
    },
    formatParams(form) {
      return {
        ...form,
        defenceName: this.form.name,
        poly: this.form.poly,
      };
    },
    startDraw() {
      this.editingDrawGeom = null;
      this.drawState = true;
      this.drawtool.enable();
    },
    editFence(fence) {
      this.editingDrawGeom = fence.polygon.geom;
      this.form.name = fence.polygon.options.bizAttr.name;
      this.form.id = fence.polygon.options.bizAttr.id;
      this.form.polygonId = fence.polygon.options.bizAttr.polygonId;
      this.editState = true;
      this.editingDrawGeom.startEdit();
      // 点击地图 图形取消编辑状态
      this.mapIns.map.once('click', () => {
        this.editingDrawGeom.endEdit();
        this.dialogVisible = true;
      });
    },
    show(data) {
      this.fence = data;
      if (data) {
        this.form = {
          id: data.id,
          name: data.defenceName
        };
      }
      this.destroyed = false;
      this.centerDialogVisible = true;
    },
  },
};
</script>
<style scoped lang="scss">
.trail-dialog-content {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-direction: column;

  .map-ctrl {
    display: flex;
    height: 100%;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    margin-left: 20px;

    .el-button {
      margin-left: 0;
      margin-top: 10px;
    }
  }
}
</style>
