<template>
  <div class="container">
    <div style="padding: 12px">
      <el-form :inline="true" ref="form" :model="form" :rules="rules" class="demo-form-inline">
        <el-form-item label="电子围栏名称" prop="electronicFenceName">
          <el-input v-model="form.electronicFenceName" placeholder="请输入电子围栏名称"/>
        </el-form-item>
        <el-form-item label="所属场景" prop="sceneId">
          <el-select v-model="form.sceneId" placeholder="请选择" @input="sceneChange" :disabled="sceneDisabled">
            <el-option
              v-for="(scene, index) in editedScenes"
              :key="index"
              :label="scene.sceneName"
              :value="scene.sceneId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="触发状态" prop="triggerStatus">
          <el-select v-model="form.triggerStatus" placeholder="请选择触发状态">
            <el-option
              v-for="dict in dict.type.hw_fence_trigger_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>


      </el-form>
      <div>
        <el-col :span="12">
          <el-button type="primary" @click="createPolygon">新增多边形</el-button>

          <el-button type="primary" @click="createCircle">新增圆</el-button>
          <el-button type="primary" @click="clear">清空</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </el-col>
      </div>
    </div>
    <div id="map" class="map"></div>
  </div>
</template>

<script>
import {
  listElectronicFence,
  getElectronicFence,
  delElectronicFence,
  addElectronicFence,
  updateElectronicFence,
  getEditedScenes
} from "@/api/business/electronicFence";

let map = null
let polyEditor = null
let CircleEditor = null
let path = [[116.390969, 39.911592], [116.391496, 39.909008], [116.389264, 39.909765], [116.38802, 39.911016]]
let path1 = [[116.391969, 39.912592], [116.392496, 39.910008], [116.390264, 39.910765], [116.38902, 39.912016]]
export default {
  dicts: ['hw_fence_trigger_status'],
  components: {},
  data() {
    return {
      form: {
        data1: '',
        data2: ''
      },
      //编辑页面场景列表
      editedScenes: [],
      // 表单校验
      rules: {
        electronicFenceName: [
          {required: true, message: "电子围栏名称不能为空", trigger: "blur"}
        ],
        sceneId: [
          {required: true, message: "所属场景，关联hw_scene表的scene_id字段不能为空", trigger: "blur"}
        ],
        fenceType: [
          {required: true, message: "规则类型不能为空", trigger: "change"}
        ],
        effectiveTimeFlag: [
          {required: true, message: "生效时间标识不能为空", trigger: "blur"}
        ],
        effectiveTime: [
          {required: true, message: "格式：开始时间_结束时间_状态，多个用|隔开不能为空", trigger: "blur"}
        ],
        triggerStatus: [
          {required: true, message: "触发状态不能为空", trigger: "change"}
        ],
        areaShapeFlag: [
          {required: true, message: "区域形状不能为空", trigger: "blur"}
        ],
        fencePushFlag: [
          {required: true, message: "报警推送标识(1、是，0、否）不能为空", trigger: "blur"}
        ],
      }
    }
  },
  created() {
    getEditedScenes().then(response => {
      this.editedScenes = response.data;
    });

    this.getEditedElectronicFence();
  },
  mounted() {
    map = new AMap.Map('map', {
      zoom: 11,
      center: [113.4, 23.35],
    });
    CircleEditor = new AMap.CircleEditor(map);
    CircleEditor.on('add', function (data) {
      let circle = data.target;
      // CircleEditor.addAdsorbCircles(circle);
      circle.on('dblclick', () => {
        CircleEditor.setTarget(circle);
        CircleEditor.open();
      })
    })
    polyEditor = new AMap.PolygonEditor(map);
    polyEditor.on('add', function (data) {
      let polygon = data.target;
      polyEditor.addAdsorbPolygons(polygon);
      polygon.on('dblclick', () => {
        polyEditor.setTarget(polygon);
        polyEditor.open();
      })
    })
  },
  methods: {
    a() {
      this.clear();
      [path, path1].forEach(e => {
        this.setPolygon(e)
      })
    },
    clear() {
      if (!polyEditor) return
      CircleEditor.close();
      polyEditor.close();
      let polygons = map.getAllOverlays('polygon');
      let circles = map.getAllOverlays('circle');
      map.remove(polygons)
      map.remove(circles)
    },
    createPolygon() {
      polyEditor.close();
      polyEditor.setTarget();
      polyEditor.open()
    },
    createCircle() {
      CircleEditor.close();
      CircleEditor.setTarget();
      CircleEditor.open()
    },
    setPolygon(e) {
      let thisPolygon = new AMap.Polygon({path: e});
      thisPolygon.on('dblclick', () => {
        polyEditor.setTarget(thisPolygon);
        polyEditor.open();
      })
      map.add(thisPolygon)
      map.setFitView()
    },
    getAreaData() {
      let polygons = map.getAllOverlays('polygon');
      let circles = map.getAllOverlays('circle');
      let list = polygons.map(e => e._opts.path)//多边形
      let list1 = circles.map(e => {//圆形
        return {
          center: e._opts.center,
          radius: e._opts.radius
        }
      })
      let params = []
      let params1 = []
      list.forEach((e, index) => {
        e.forEach(val => {
          params.push({
            longitude: val[0],
            latitude: val[1],
            index: index
          })
        })
      })
      list1.forEach((e, index) => {
        params1.push({
          center: e.center,
          radius: e.radius,
          index: index
        })
      })

      if (params.length > 0) {
        this.form.polygonAreaListStr = JSON.stringify(params);
      }
      if (params1.length > 0) {
        this.form.circleAreaListStr = JSON.stringify(params1);
      }

    },

    getEditedElectronicFence(){
      const electronicFenceId = this.$route.params && this.$route.params.electronicFenceId;
      if(electronicFenceId!=undefined){
        getElectronicFence(electronicFenceId).then(response => {
          this.form = response.data;
          alert(this.form.circleAreaListStr);
          alert(this.form.polygonAreaListStr);
        });
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.getAreaData();
          if (this.form.electronicFenceId != null) {
            updateElectronicFence(this.form).then(response => {
              this.$modal.msgSuccess(response.msg);
              alert(response.code)
              if (response.code === 200) {
                this.close();
              }
            });
          } else {
            addElectronicFence(this.form).then(response => {
              this.$modal.msgSuccess(response.msg);
              if (response.code === 200) {
                this.close();
              }
            });
          }
        }
      });
    },

  }
};
</script>
<style lang="less" scoped>
.container {
  height: calc(100vh - 84px)
}

.map {
  width: 100%;
  height: 100%;
}
</style>
