<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="请选择" :disabled="sceneDisable">
            <el-option
              v-for="(scene, index) in editedScenes"
              :key="index"
              :label="scene.sceneName"
              :value="scene.sceneId"
              :disabled="scene.selectedDisable && scene.selectedDisable == 1"
            ></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 {
  getElectronicFence,
  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: [],
      sceneDisable: true,
      // 表单校验
      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() {
    this.getEditedScenes();
  },
  async mounted() {
    await this.isAMap()
    this.getEditedElectronicFence();
    map = new AMap.Map('map', {
      zoom: 11,
      center: [113.4, 23.35],
    });
    await this.isMapLoading()
    CircleEditor = new AMap.CircleEditor(map);
    CircleEditor.on('add', function (data) {
      let circle = data.target;
      // CircleEditor.addAdsorbCircles(circle);
      circle.on('dblclick', () => {
        CircleEditor.setTarget(circle);
        polyEditor.close();
        CircleEditor.open();
      })
      circle.on('rightclick', () => {
        CircleEditor.close();
        map.remove(circle);
      })
    })
    polyEditor = new AMap.PolygonEditor(map);
    polyEditor.on('add', function (data) {
      let polygon = data.target;
      polyEditor.addAdsorbPolygons(polygon);
      polygon.on('dblclick', () => {
        polyEditor.setTarget(polygon);
        CircleEditor.close();
        polyEditor.open();
      })

      polygon.on('rightclick', () => {
        CircleEditor.close();
        polyEditor.close();
        map.remove(polygon);
      })
    })
  },
  methods: {
    getEditedScenes() {
      getEditedScenes().then(response => {
        this.editedScenes = response.data;
      });
    },
    isAMap() {
      return new Promise((a, b) => {
        let fun = () => {
          if (typeof AMap === 'object') {
            a()
          } else {
            setTimeout(fun, 100)
          }
        }
        fun()
      })
    },
    isMapLoading() {
      return new Promise((a, b) => {
        let fun = () => {
          if (map) {
            a()
          } else {
            setTimeout(fun, 100)
          }
        }
        fun()
      })
    },
    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() {
      CircleEditor.close();
      polyEditor.close();
      polyEditor.setTarget();
      polyEditor.open()
    },
    createCircle() {
      polyEditor.close();
      CircleEditor.close();
      CircleEditor.setTarget();
      CircleEditor.open()
    },
    setPolygon(e) {
      let thisPolygon = new AMap.Polygon({path: e});
      thisPolygon.on('dblclick', () => {
        polyEditor.setTarget(thisPolygon);
        polyEditor.open();
      })
      thisPolygon.on('rightclick', () => {
        polyEditor.close();
        map.remove(thisPolygon);
      })
      map.add(thisPolygon)
      map.setFitView()
    },
    setCircle(e) {
      let thisCircle = new AMap.Circle({center: e.center, radius: e.radius});
      thisCircle.on('dblclick', () => {
        CircleEditor.setTarget(thisCircle);
        CircleEditor.open();
      })
      thisCircle.on('rightclick', () => {
        CircleEditor.close();
        map.remove(thisCircle);
      })
      map.add(thisCircle)
      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
        })
      })

      this.form.polygonAreaListStr = JSON.stringify(params);

      this.form.circleAreaListStr = JSON.stringify(params1);

    },

    getEditedElectronicFence() {
      const electronicFenceId = this.$route.params && this.$route.params.electronicFenceId;
      if (electronicFenceId != undefined) {
        this.sceneDisable = true;
        getElectronicFence(electronicFenceId).then(response => {
          this.form = response.data;
          let circleAreaList = JSON.parse(response.data.circleAreaListStr)
          let polygonAreaList = JSON.parse(response.data.polygonAreaListStr)
          let polygonData1 = {}
          let polygonData = []
          polygonAreaList.forEach(e => {
            if (polygonData1[e.index]) {
              polygonData1[e.index].push([e.longitude, e.latitude])
            } else {
              polygonData1[e.index] = [[e.longitude, e.latitude]]
            }
          })
          Object.keys(polygonData1).forEach(e => {
            polygonData[e] = polygonData1[e]
          })
          polygonData.forEach(e => {
            this.setPolygon(e)
            console.log(e)
          })

          circleAreaList.forEach(e => {
            let center = JSON.parse(e.center)
            let radius = e.radius
            this.setCircle({center, radius})
          })
        });
      } else {
        this.sceneDisable = false;
      }
    },

    /** 提交按钮 */
    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);
              if (response.code === 200) {
                this.close();
              }
            });
          } else {
            addElectronicFence(this.form).then(response => {
              this.$modal.msgSuccess(response.msg);
              if (response.code === 200) {
                this.close();
              }
            });
          }
        }
      });
    },

    /** 关闭按钮 */
    close() {
//      alert(this.$route.query.pageNum);
      const obj = {path: "/alarm/electronicFence", query: {t: Date.now(), pageNum: this.$route.query.pageNum}};
      this.$tab.closeOpenPage(obj);
    },


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

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