<template>
  <pannel class="fence-location-container">
    <template v-slot:title>
      围栏闯禁
    </template>
    <template v-slot:action>
      <el-button
          size="mini"
          type="text"
          icon="el-icon-plus"
          round
          @click="startDraw"
          style="margin-left: auto"
          :disabled="drawState"
      >
        {{ drawState ? '绘制中...' : '绘制围栏' }}
      </el-button>
    </template>
    <template v-slot:content>
      <div class="location-list">
        <template v-for="fence in fenceList">
          <div :key="`fence_${fence.id}`" class="list-item">
          <span class="over-flow-hidden" style="width: 40%">
            {{ fence.name }}
          </span>
            <span class="over-flow-hidden" style="width: 40%">
           {{ fence.updateTime }}
          </span>
            <span class="over-flow-hidden" style="width: 20%">
              <el-popconfirm
                  confirm-button-text='好的'
                  cancel-button-text='不用了'
                  icon="el-icon-info"
                  icon-color="red"
                  :title="`是否删除围栏【${fence.name}】？`"
                  @confirm="()=>delFence(fence)"
              >
               <i
                   slot="reference"
                   class="el-icon-delete"
                   title="删除围栏"
               ></i>
              </el-popconfirm>
            <i
                class="el-icon-edit"
                title="编辑围栏"
                @click="()=>editFence(fence)"
            />
          </span>
          </div>
        </template>
      </div>
      <el-dialog
          width="20%"
          title="提示"
          :visible="dialogVisible"
          append-to-body>
        <div>
          <div style="margin-bottom: 14px">
            检测到未保存的内容，是否保存修改?
          </div>
          <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>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelEdit">放弃修改</el-button>
          <el-button type="primary" @click="saveEdit">保存</el-button>
        </div>
      </el-dialog>
    </template>
  </pannel>
</template>

<script>

import { addFenceInfo, listFenceInfo, updateFenceInfo } from '@/api/bd/fenceInfo';
import maphandle from '@/views/bd/map/maphandle';
import Pannel from '@/views/bd/pannel/index.vue';
// this.drawtool = new BDLayers.Lib.Tools.CBDrawTool('mytool', this.mapView, 'Rectangle', true); // 绘制矩形，参数1：id，参数2：地图，参数3：绘制类型，参数4：是否可拖拽编辑
// this.drawtool.enable(); // 开始绘制
// this.drawtool.disable(); // 结束绘制
// this.drawtool.clear(); // 清除绘制内容
// this.drawtool.setDrawMode(type); // 设置绘制类型
// this.drawtool.on('drawend', (geom) => {}) // 绘制结束事件
// this.drawtool.on('selectDraw', geom => {}) // 绘制完毕后选择绘制图形
export default {
  name: 'fence',
  components: { Pannel },
  mixins: [maphandle],
  data() {
    return {
      playItem: {},
      editState: false,
      editPolyInfo: {},
      dialogVisible: false,
      editingDrawGeom: null,
      drawState: false,
      drawtool: null,
      form: {
        name: '',
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入围栏名称',
            trigger: 'blur',
          },
        ],
      },
      fenceList: [],
    };
  },
  // 组件卸载前清空图层信息
  beforeDestroy() {
    window.map.removeLayersById('drawLayer');
    window.map.removeLayersById('distanceLayer');
    this.drawtool?.disable();
  },
  created() {
    // 地图绘制工具
    this.drawtool = new BDLayers.Lib.Tools.CBDrawTool('myTool', window.map, '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()) {
        // 点击地图 图形取消编辑状态
        window.map.map.once('click', () => {
          this.editingDrawGeom.endEdit();
          this.dialogVisible = true;
        });
      } else {
        window.map.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.dialogVisible = true;
      this.drawState = false;
    });
  },
  mounted() {
    this.getFenceList();
  },
  methods: {
    async getFenceList() {
      const { rows } = await listFenceInfo({
        pageNum: 1,
        pageSize: 10,
      });
      if (!rows || rows.length < 1) {
        return;
      }
      const result = [];
      rows.forEach(item => {
        const {
          id,
          defenceName,
          poly,
        } = item;
        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,
          },
        });
        result.push({
          id,
          name: defenceName,
          polygon,
        });
      });
      this.editingDrawGeom = null;
      this.fenceList = result;
      // window.map.flyToPoint([118.86318437, 31.52265586], {
      //   zoom: 13,
      //   pitch: 0,
      //   bearing: 20,
      //   duration: 5000,
      // });
    },
    cancelEdit() {
      this.drawtool.clear();
      this.dialogVisible = false;
    },
    saveEdit() {
      this.$refs.form.validate((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) {
            addFenceInfo(this.formatParams(this.form)).then(response => {
              this.$message({
                type: 'success',
                message: '围栏保存成功',
              });
            });
          } else {
            updateFenceInfo(this.formatParams(this.form)).then(response => {
              this.$message({
                type: 'success',
                message: '围栏编辑成功',
              });
            });
          }
          this.dialogVisible = false;
          this.drawtool.clear();
          const polygon = 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.polyLayer.addGeometry(polygon);
          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();
    },
    /**
     *
     * @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,
        polyOnClick: (data) => {
        console.log(data.target.options);
        if (this.editState) {
          return;
        }
        this.form.name = data.target.options.bizAttr.name;
        this.editingDrawGeom = data.target.geometry ? data.target.geometry : data.target.geom
            ? data.target.geom
            : data.target;
        this.$confirm('检测到选中了围栏，请选择操作类型?', '提示', {
          confirmButtonText: '编辑围栏',
          cancelButtonText: '删除围栏',
          type: 'warning',
        }).then(() => {
          // 开始编辑围栏
          this.editState = true;
          this.editingDrawGeom.startEdit();
        }).catch(() => {
          this.editingDrawGeom.remove();
          this.editState = false;
          this.editingDrawGeom = null;
          this.$message({
            type: 'info',
            message: '删除围栏',
          });
        });
        // 点击地图 图形取消编辑状态
        window.map.map.once('click', () => {
          this.editingDrawGeom.endEdit();
          this.dialogVisible = true;
        });
        },
      })
    },
    delFence(fence) {
      // polygon.geom.startEdit();
      fence.polygon.geom.remove();
    },
    editFence(fence) {

    },
  },
};
</script>
<style lang="scss" src="./index.scss" />
