<template>
  <div id="fence">
    <el-row>
      <el-col :span="24" class="main">
        <el-col :span="3" style="margin-bottom: 10px">
          <slot name="back"></slot>
        </el-col>
        <template v-if="type === 'draw'">
          <el-col :span="6">
            <el-button size="small" @click="drawPolygon" v-if="!isDraw()">绘制多边形</el-button>
            <el-button size="small" @click="drawRectangle" v-if="!isDraw()">绘制矩形</el-button>
            <el-button size="small" @click="clearDraw" v-if="isDraw()">重新绘制</el-button>
            <el-button size="small" @click="returnToDraw" v-if="isDraw()">重新选择绘制图形</el-button>
            <el-button size="small" type="primary" @click="toSave" v-if="isDraw()">保存</el-button>
          </el-col>
          <el-col :span="8">
            <span style="color: red" v-if="isDraw() === 'polygon'">您处于绘制多边形状态.双击最后的位置结束绘制</span>
            <span style="color: red" v-if="isDraw() === 'rectangle'">您处于绘制矩形状态.点击后进行拖拽,松开结束绘制</span>
          </el-col>
        </template>
        <template v-if="type === 'edit'">
          <el-col :span="6">
            <el-button size="small" type="primary" @click="toStart" v-if="!editing">编辑</el-button>
            <el-button size="small" type="primary" @click="toEnd" v-if="editing">保存</el-button>
            <el-button size="small" type="primary" @click="reDraw">重新绘制</el-button>
          </el-col>
        </template>
        <el-col :span="6">
          <el-input v-model="keyword" size="small" id="input" placeholder="请输入要查询的地点">
            <template #append>
              <el-button type="primary" @click="mapSearch">查询</el-button>
            </template>
          </el-input>
        </el-col>

        <el-col :span="24" class="one">
          <div id="container"></div>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import drawTools from '@/util/draw';
import MapLoader from '@/plugins/amap';
export default {
  name: 'fence',
  props: {
    form: { type: Object, default: () => {} },
    drawList: { type: Array },
  },
  model: {
    prop: 'form',
    event: 'change',
  },
  components: {},
  data: function () {
    return {
      map: undefined,
      center: [125.324667, 43.883476],
      mapStyle: 'amap://styles/387f96e0666b7d5aec6e11cffa97c91a',
      // 绘制
      mouseTool: undefined,
      drawForm: {},
      dialog: false,
      levelList: drawTools.levelList,
      editor: undefined,
      editing: false,
      type: 'draw', // 类型模式:draw--画;edit--改
      keyword: undefined,
      searchPlugins: undefined,
    };
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    async toSave() {
      const fence = _.cloneDeep(this.drawForm);
      this.$emit('save', fence);
    },
    async init() {
      if (!_.get(window, 'AMap')) await MapLoader();
      if (this.map) this.map.destroy();
      let that = this;
      let map = new AMap.Map('container', {
        zoom: '11.5',
        resizeEnable: true,
        viewMode: '2D',
        center: this.center,
        // mapStyle: this.mapStyle,
      });
      await this.initMapSearch();
      await drawTools.initSearchAutoComplete('input');
      // 无围栏信息,画
      AMap.plugin(['AMap.MouseTool'], function () {
        that.mouseTool = new AMap.MouseTool(map);
      });
      map.on('complete', () => {
        this.map = map;
        this.mouseTool.on('draw', this.drawFinish);
        if (_.get(this.form, 'fence.type')) {
          // 有围栏信息,复现,改
          this.initGraphic();
          this.type = 'edit';
        }
        this.drawInMap(this.drawList);
      });
    },
    drawInMap(list = []) {
      if (!_.isArray(list)) return;
      for (const i of list) {
        const { type } = i;
        let obj;
        if (type === 'polygon') obj = drawTools.initPolygon(i);
        else obj = drawTools.initRectangle(i);
        this.map.add(obj);
      }
    },
    async initMapSearch() {
      this.searchPlugins = await drawTools.initSearch({ city: '长春' });
    },
    mapSearch() {
      // 根据关键字进行搜索
      this.searchPlugins.search(this.keyword, (status, result) => {
        // 先做简单的.只拿第一个,然后将中心点定过去
        if (result.info !== 'OK') return;
        const list = _.get(result, 'poiList.pois');
        const poi = _.head(list);
        const point = [_.get(poi, 'location.lng'), _.get(poi, 'location.lat')];
        this.map.setCenter(point, true, 0);
        const mark = drawTools.initMark({ position: point });
        this.map.add(mark);
      });
    },
    // 改
    async initGraphic() {
      const data = _.get(this.form, 'fence');
      if (!data) return;
      const { type } = data;
      let obj;
      // 生成画过的图形
      if (type === 'polygon') obj = drawTools.initPolygon(data);
      else obj = drawTools.initRectangle(data);
      // 加入地图
      this.map.add(obj);
      // 加载插件
      let editor;
      if (type === 'polygon') {
        this.drawForm.type = 'polygon';
        editor = new AMap.PolyEditor(this.map, obj);
        editor.on('end', (e) => {
          this.editDrawFinish(e);
          this.toSave();
        });
      } else {
        this.drawForm.type = 'rectangle';
        editor = new AMap.RectangleEditor(this.map, obj);
        editor.on('end', (e) => {
          this.editDrawFinish(e);
          this.toSave();
        });
      }
      this.editor = editor;
    },
    toStart() {
      this.editor.open();
      this.editing = true;
    },
    toEnd() {
      this.editor.close();
      this.editing = false;
    },

    // 画
    // 结束绘制事件触发
    clearDraw() {
      this.mouseTool.close(true);
      const type = _.get(this.drawForm, 'type');
      if (type === 'polygon') this.drawPolygon();
      else this.drawRectangle();
    },
    returnToDraw() {
      this.mouseTool.close(true);
      this.$set(this, 'drawForm', {});
    },
    // 结束绘制数据处理部分
    drawFinish(e) {
      let path;
      if (_.get(this.drawForm, 'type') === 'polygon') {
        path = _.get(e, 'obj._opts.path');
        if (!path) {
          this.$message.error('未获取到绘制图形的坐标');
          return false;
        }
      } else if (_.get(this.drawForm, 'type') === 'rectangle') {
        path = _.chunk(_.flattenDeep(_.get(e, 'obj.aE')), 2);
      }
      this.drawForm.range = path;
    },
    // 结束绘制数据处理部分
    editDrawFinish(e) {
      let path;
      if (_.get(this.drawForm, 'type') === 'polygon') {
        path = _.get(e, 'target._opts.path');
        if (!path) {
          this.$message.error('未获取到绘制图形的坐标');
          return false;
        }
      } else if (_.get(this.drawForm, 'type') === 'rectangle') {
        path = _.chunk(_.flattenDeep(_.get(e, 'target.aE')), 2);
        if (!path) {
          this.$message.error('未获取到绘制图形的坐标');
          return false;
        }
      }
      this.drawForm.range = path;
    },
    // 画多边形
    drawPolygon() {
      drawTools.drawPolygon(this.mouseTool);
      this.$set(this.drawForm, 'type', 'polygon');
    },
    // 画矩形
    drawRectangle() {
      drawTools.drawRectangle(this.mouseTool);
      this.$set(this.drawForm, 'type', 'rectangle');
    },
    isDraw() {
      const r = _.get(this.drawForm, 'type');
      return r;
    },
    // 重新绘制
    reDraw() {
      this.type = 'draw';
      this.map.clearMap();
      this.drawForm = {};
      this.form.fencen = {};
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  beforeDestroy() {
    this.map.destroy();
  },
};
</script>

<style lang="less" scoped>
#container {
  width: 100%;
  height: 750px;
  overflow: hidden;
}
</style>
