<template>
  <pannel class="fence-location-container">
    <template v-slot:icon>
      <svg-icon icon-class="bd_fence"/>
    </template>
    <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>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="室外围栏" :name="Tabs.outside.id">
        </el-tab-pane>
        <el-tab-pane label="室内围栏" :name="Tabs.inside.id">
          <room-layer v-if="activeName === Tabs.inside.id"/>
        </el-tab-pane>
      </el-tabs>
      <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: 80%;cursor: pointer;" @click="()=>fenceClick(fence)">
              {{ fence.name }}
            </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 '@/components/map/maphandle';
import Pannel from '@/views/bd/pannel/index.vue';
import {FenceType} from "@/utils/BDConst";
import RoomLayer from "@/views/bd/rooms/index.vue";

const Tabs = {
  outside: {
    id: 'outside',
    param: {
      fenceType: FenceType.OUTSIDE.value,
    },
  },
  inside: {
    id: 'inside',
    param: {
      fenceType: FenceType.INSIDE.value,
    },
  },
}

export default {
  name: 'fence',
  components: {RoomLayer, Pannel},
  mixins: [maphandle],
  data() {
    return {
      Tabs,
      activeName: Tabs.outside.id,
      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: {
    fenceClick(fence) {
      const {polygon} = fence;
      map.setPitch(0);
      map.fitExtent(polygon.getExtent(), 0);
    },
    async getFenceList(params) {
      const {rows} = await listFenceInfo({
        pageNum: 1,
        pageSize: 10,
        fenceType: 1,
        ...params
      });
      if (!rows || rows.length < 1) {
        return;
      }
      const result = [];
      this.clearLayer();
      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(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: '围栏保存成功',
            });
          } else {
            await updateFenceInfo(this.formatParams(this.form))
            this.$message({
              type: 'success',
              message: '围栏编辑成功',
            });
            this.polyLayer.removeGeometry(this.form.polygonId);
          }
          this.dialogVisible = false;
          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();
    },
    handleClick(tab) {
      this.activeName = tab.name;
      this.getFenceList(Tabs[tab.name].param);
    },
    /**
     *
     * @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: '删除围栏',
            distinguishCancelAndClose: true,
            type: 'warning',
          }).then(() => {
            // 开始编辑围栏
            this.editState = true;
            this.editingDrawGeom.startEdit();
          }).catch(() => {
            this.editingDrawGeom.remove();
            this.editState = false;
            this.editingDrawGeom = null;
          });
          // 点击地图 图形取消编辑状态
          window.map.map.once('click', () => {
            this.editingDrawGeom.endEdit();
            this.dialogVisible = true;
          });
        },
      })
    },
    delFence(fence) {
      // polygon.geom.startEdit();
      fence.polygon.geom.remove();
    },
    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();
      // 点击地图 图形取消编辑状态
      window.map.map.once('click', () => {
        this.editingDrawGeom.endEdit();
        this.dialogVisible = true;
      });
    },
  },
};
</script>
<style lang="scss" src="./index.scss"/>
