<!-- 绘制基地 -->
<template>
  <div class="mappage">
    <div id="mapbox"></div>
    <div class="inputbox">
      <!-- <div class="btnbox1" @click="goBackPage">返回</div> -->
      <el-input
        size="small"
        @change="addrChange()"
        clearable
        placeholder="请输入地区检索"
        v-model="city"
      >
        <i slot="suffix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <div class="btnbox2" @click="draw">开始绘制</div>
    </div>
    <div class="tishi" v-show="underway">
      双击左键或单击右键可以结束基地绘制
    </div>
    <el-dialog
      title="基地信息"
      :visible.sync="dialogVisible"
      width="580px"
      :close-on-click-modal="false"
    >
      <div class="baseinfobox">
        <el-form
          :model="baseinfodata"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="基地名称" prop="base_name">
            <el-input
              size="mini"
              maxlength="20"
              v-model="baseinfodata.base_name"
            ></el-input>
          </el-form-item>
          <el-form-item label="负责人" prop="production_name">
            <el-input
              size="mini"
              v-model="baseinfodata.production_name"
              maxlength="10"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input size="mini" v-model="baseinfodata.phone"></el-input>
          </el-form-item>
          <el-form-item label="基地面积" prop="base_area">
            <p>{{ baseinfodata.base_area }} 亩</p>
          </el-form-item>
          <el-form-item label="基地图片" prop="img_url">
            <!-- <el-input v-model="baseinfodata.img_url"></el-input> -->
            <el-upload
              class="avatar-uploader"
              :action="$http + '/api/util/upload/img/'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-error="handleAvatarError"
            >
              <img
                v-if="baseinfodata.img_url"
                :src="baseinfodata.img_url"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="基地地址" prop="name">
            <el-input
              size="mini"
              v-model="baseinfodata.base_addr"
              v-if="baseinfodata.base_addr == ''"
            ></el-input>
            <p v-else>{{ baseinfodata.base_addr }}</p>
          </el-form-item>
          <el-form-item label="基地描述" prop="describe">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="baseinfodata.describe"
              :maxlength="256"
              show-word-limit
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="addbtnfa">取 消</el-button>
        <el-button size="mini" type="primary" @click="addbtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
import AMap from "AMap";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else {
        var reg = /^1[3-9]\d{9}$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确手机号"));
        }
      }
    };
    return {
      map: null,
      city: "",
      geocoder: null,
      center: [116.412427, 39.303573],
      overlays: [],
      underway: false,
      dialogVisible: false,
      baseinfodata: {
        base_name: "",
        base_area: "",
        coordinates: "",
        base_addr: "",
        img_url: "",
        img_url2: "",
        describe: "",
        production_name: "",
        phone: "",
        address: "",
      },
      rules: {
        base_name: {
          required: true,
          message: "请输入基地名称",
          trigger: "blur",
        },
        img_url: { required: true, message: "请选择基地图片", trigger: "blur" },
        base_addr: {
          required: true,
          message: "请输入基地地址",
          trigger: "blur",
        },
        phone: {
          validator: validatePass,
          trigger: "blur",
        },
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    dialogVisible(val, newval) {
      console.log(val);
      if (val == false) {
        this.map.remove(this.overlays);
      }
    },
  },
  //方法集合
  methods: {
    //返回上一页
    goBackPage() {
      this.$router.go(-1);
    },
    getbaslist() {
      this.$axios({
        method: "post",
        url: "api/api_gateway?method=basemanager.baseinfo.list_land_base",
        data: this.qs.stringify({
          page: 1,
          page_size: 9999999,
        }),
      }).then((res) => {
        this.loading = false;
        if (res.data.data) {
          var data = res.data.data.data;
          this.alreadyhave = data;
          for (var i = 0; i < data.length; i++) {
            var polygonArr = JSON.parse(data[i].coordinates);
            var polygon = new AMap.Polygon({
              map: this.map,
              path: polygonArr, //设置多边形边界路径
              strokeColor: "#4f71ff", //线颜色
              strokeOpacity: 0.5, //线透明度
              strokeWeight: 3, //线宽
              fillColor: "#1791fc", //填充色
              fillOpacity: 0.35, //填充透明度
            });
          }
          // this.map.setFitView();
        }
      });
    },
    init() {
      var map = new AMap.Map("mapbox", {
        center: this.center,
        resizeEnable: true,
        zoom: 15,
        lang: "en",
        layers: [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()],
      });
      AMap.plugin(["AMap.ToolBar", "AMap.Geocoder"], () => {
        map.addControl(new AMap.ToolBar());
        this.geocoder = new AMap.Geocoder({
          city: "全国",
          radius: 1000,
        });
      });
      this.map = map;
    },
    addrChange() {
      var that = this;
      this.map.plugin(["AMap.Geocoder"], function () {
        console.log(that.city);
        that.geocoder.getLocation(that.city, (status, result) => {
          console.log(status, result);
          if (status === "complete" && result.geocodes.length) {
            var lat = result.geocodes[0].location.lat;
            var lng = result.geocodes[0].location.lng;
            console.log(result.geocodes[0]);
            // marker.setPosition(lnglat);
            setTimeout(() => {
              that.map.setZoomAndCenter(7, that.center);
              setTimeout(() => {
                that.map.setZoomAndCenter(7, [lng, lat]);
                setTimeout(() => {
                  that.map.setZoomAndCenter(14, [lng, lat]);
                }, 1000);
              }, 1000);
            }, 500);
          } else {
          }
        });
      });
    },
    //开始编辑
    draw() {
      if (this.underway) {
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message.warning("正在绘制中，请勿重复点击");
          return;
        }
        return;
      }
      // var PolyEditor = null;
      this.underway = true;
      this.map.plugin(["AMap.MouseTool"], () => {
        var mousetool = new AMap.MouseTool(this.map);
        mousetool.polygon({
          strokeColor: "#4f71ff",
          strokeOpacity: 1,
          strokeWeight: 6,
          strokeOpacity: 0.5,
          fillColor: "#1791fc",
          fillOpacity: 0.4,
          strokeStyle: "solid",
        });
        // PolyEditor = new AMap.PolyEditor(this.map);
        mousetool.on("draw", (e) => {
          console.log(e);
          //关闭绘制
          this.mousetool.close();
          this.underway = false;
          //添加信息
          this.overlays.push(e.obj);
          // 计算区域面积
          var path = e.obj.getOptions().path;
          var num = Math.round(AMap.GeometryUtil.ringArea(path));
          // console.log(num)
          this.baseinfodata.base_area = (num + num / 2) / 1000;
          // 赋值定位点
          this.baseinfodata.coordinates = path;
          this.getcity(path[0]);
          // 开启弹框
          // for (var i = 0; i < this.alreadyhave.length; i++) {
          //   this.compute(JSON.parse(this.alreadyhave[i].coordinates));
          // }
          var flag = this.alreadyhave.some((item) => {
            return this.compute(JSON.parse(item.coordinates));
          });
          console.log(flag);
          if (!flag) {
            this.dialogVisible = true;
          }
        });
        this.mousetool = mousetool;
      });
    },
    compute(data) {
      var polygon1_path = this.baseinfodata.coordinates;
      var polygon2_path = data;
      // 小圈是否在大圈内
      var isRingInRing = AMap.GeometryUtil.isRingInRing(
        polygon2_path,
        polygon1_path
      );
      // 两圈是否交叉
      var doesRingRingIntersect = AMap.GeometryUtil.doesRingRingIntersect(
        polygon2_path,
        polygon1_path
      );
      if (isRingInRing || doesRingRingIntersect) {
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message.warning("基地被覆盖，绘制无效");
        }
        this.map.remove(this.overlays);
        return true;
      } else {
        return false;
      }
    },
    getcity(path) {
      this.$jsonp(`http://restapi.amap.com/v3/geocode/regeo?output=json`, {
        key: "a6919321ca5d6b4d2f11c63fe87671de",
        location: `${path[0]},${path[1]}`,
      }).then((res) => {
        console.log(res.regeocode);
        let addressComponent = res.regeocode && res.regeocode.formatted_address;
        if (addressComponent) {
          if (
            res.regeocode.addressComponent.city == "" ||
            res.regeocode.addressComponent.city.length == 0
          ) {
            this.baseinfodata.address =
              res.regeocode.addressComponent.province +
              "," +
              res.regeocode.addressComponent.province +
              "," +
              res.regeocode.addressComponent.district;
          } else {
            this.baseinfodata.address =
              res.regeocode.addressComponent.province +
              "," +
              res.regeocode.addressComponent.city +
              "," +
              res.regeocode.addressComponent.district;
          }
          this.baseinfodata.base_addr = res.regeocode.formatted_address;
        } else {
          this.baseinfodata.base_addr = "";
        }
      });
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.baseinfodata.img_url2 = this.$http + res.img_url;
      this.baseinfodata.img_url = URL.createObjectURL(file.raw);
    },
    handleAvatarError(res) {
      console.log(res);
    },
    beforeAvatarUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    addbtnfa() {
      this.dialogVisible = false;
      this.map.remove(this.overlays);
    },
    addbtn() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$axios({
            method: "post",
            url: "api/api_gateway?method=basemanager.baseinfo.add_land_base",
            data: this.qs.stringify({
              base_name: this.baseinfodata.base_name,
              base_area: this.baseinfodata.base_area,
              coordinates: JSON.stringify(this.baseinfodata.coordinates),
              base_addr: this.baseinfodata.base_addr,
              img_url: this.baseinfodata.img_url2,
              describe: this.baseinfodata.describe,
              production_name: this.baseinfodata.production_name,
              phone: this.baseinfodata.phone,
              address: this.baseinfodata.address,
            }),
          }).then((res) => {
            if (res.data.data) {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.success("添加成功");
              }
              this.dialogVisible = false;
              this.$router.go(-1);
            } else {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.error(res.data.message);
              }
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // console.log(this.$route.query.lng);
    if (!this.$route.query.lng) {
      this.center = [116.412427, 39.303573];
    } else if (this.$route.query.lng == "") {
      this.center = [116.412427, 39.303573];
    } else {
      this.center = [this.$route.query.lng, this.$route.query.lat];
    }
  },
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.init();
    this.getbaslist();
  },
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.mappage {
  width: 100%;
  height: 100%;
  position: relative;
  #mapbox {
    width: 100%;
    height: 100%;
    /deep/.amap-logo {
      display: none !important;
    }
    /deep/.amap-copyright {
      display: none !important;
    }
  }
  .inputbox {
    position: absolute;
    top: 10px;
    left: 10px;
    display: flex;
    .btnbox2,
    .btnbox1 {
      width: 128px;
      height: 32px;
      // border: 1px solid #4f71ff;
      background-color: #4f71ff;
      text-align: center;
      border-radius: 5px;
      font-size: 14px;
      line-height: 32px;
      cursor: pointer;
      color: #fff;
    }
    .btnbox1 {
      margin-right: 15px;
    }
    .btnbox2 {
      margin-left: 15px;
    }
  }
  .tishi {
    position: absolute;
    top: 10px;
    left: 50%;
    width: 300px;
    background-color: rgba(255, 255, 255, 0.8);
    height: 32px;
    margin-left: -150px;
    text-align: center;
    line-height: 32px;
    color: #666;
    font-size: 14px;
    letter-spacing: 2px;
  }
}
.baseinfobox {
  /deep/.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  /deep/.avatar-uploader .el-upload:hover {
    border-color: #4f71ff;
  }
  /deep/.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  /deep/.avatar {
    width: 150px;
    height: 150px;
    display: block;
  }
  /deep/.el-textarea {
    .el-textarea__inner {
      font-family: "Avenir", Helvetica, Arial, sans-serif;
    }
  }
}
</style>