<!-- 绘制地块  -->
<template>
  <div class="plotbox">
    <div id="mapbox"></div>
    <div class="inputbox">
      <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="createPolygon">绘制地块</div>
    </div>
    <div class="listbox" v-loading="loading">
      <div class="listbox_base">
        <p>{{ alreadyhave.base_name }}</p>
        <p>
          <span>{{ alreadyhave.area_addr[0] }}</span>
          <span>{{ alreadyhave.area_addr[1] }}</span>
          <span>{{ alreadyhave.area_addr[2] }}</span>
        </p>
        <p>
          <i
            class="iconfont icon-zongmianji"
            style="color: #999; font-size: 14px"
          ></i>
          基地面积：{{ alreadyhave.base_area }}
          亩
        </p>
        <p>
          <i
            class="iconfont icon-dikuaishuliang"
            style="color: #999; font-size: 14px"
          ></i>
          地块数量：{{ faclist.length }}
          块
        </p>
      </div>
      <div class="listbox_fac">
        <div class="table_page">
          <p class="table_page_act">地块信息</p>
          <p @click="tofac" class="table_page_no">设备信息</p>
        </div>
        <div class="listbox_facbox">
          <div class="tishi" v-if="faclist.length == 0">暂无地块</div>
          <div
            class="listbox_facbox_item"
            v-for="(item, index) in faclist"
            :key="index"
          >
            <p class="title">{{ item.massif_name }}</p>
            <p>{{ item.crop_name }}</p>
            <div class="caozuo">
              <div>地块面积：{{ item.massif_area }} 亩</div>
              <div>
                <p
                  @click="
                    getpoltlistinfo(item.massif_name),
                      getcroplist(item.massif_id)
                  "
                >
                  修改
                </p>
                <p @click="delfac(item.massif_id)">删除</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="地块信息"
      :visible.sync="dialogVisible"
      width="580px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="baseinfobox">
        <el-form
          :model="polyinfo"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="地块名称" prop="massif_name">
            <el-input
              size="mini"
              maxlength="15"
              v-model="polyinfo.massif_name"
            ></el-input>
          </el-form-item>
          <el-form-item label="地块面积" prop="massif_area">
            <p>{{ polyinfo.massif_area }} 亩</p>
          </el-form-item>
          <el-form-item label="地形" prop="terrain">
            <el-input
              size="mini"
              maxlength="15"
              v-model="polyinfo.terrain"
            ></el-input>
          </el-form-item>
          <el-form-item label="坡度" prop="slope">
            <el-input
              size="mini"
              maxlength="15"
              type="number"
              v-model="polyinfo.slope"
            ></el-input>
          </el-form-item>
          <el-form-item label="当前种植" prop="crop_id">
            <el-select
              v-model="polyinfo.crop_id"
              size="mini"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in cropoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </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>
    <el-dialog
      title="修改地块信息"
      :visible.sync="dialogVisibleinfo"
      width="580px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="baseinfobox">
        <el-form
          :model="poltlistinfo"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="地块名称" prop="massif_name">
            <el-input
              size="mini"
              maxlength="15"
              v-model="poltlistinfo.massif_name"
            ></el-input>
          </el-form-item>
          <el-form-item label="地块面积" prop="massif_area">
            <p>{{ poltlistinfo.massif_area }} 亩</p>
          </el-form-item>
          <el-form-item label="地形" prop="terrain">
            <el-input
              size="mini"
              maxlength="15"
              v-model="poltlistinfo.terrain"
            ></el-input>
          </el-form-item>
          <el-form-item label="坡度" prop="slope">
            <el-input
              size="mini"
              maxlength="15"
              type="number"
              v-model="poltlistinfo.slope"
            ></el-input>
          </el-form-item>
          <el-form-item label="当前种植" prop="crop_id">
            <el-select
              v-model="poltlistinfo.crop_id"
              size="mini"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in cropoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisibleinfo = false"
          >取 消</el-button
        >
        <el-button size="mini" type="primary" @click="addbtninfo"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    var validatePass2 = (rule, value, callback) => {
      value = value.toString();
      if (value === "") {
        callback(new Error("请输入地块坡度"));
      } else if (value.indexOf("-") != -1) {
        callback(new Error("请输入正整数"));
      } else if (value.indexOf(".") != -1) {
        callback(new Error("请输入正整数"));
      } else {
        callback();
      }
    };
    return {
      city: "",
      map: "",
      center: [],
      base_id: "",
      underway: false,
      polygon: null, //基地图层
      polygonArr: [], //基地坐标
      polyEdarr: [],
      polyEditor: null, //地块
      polygons: [], //地块坐标
      polyinfo: {
        base_id: "", //              必传    基地id
        massif_name: "", //            必传    地块名称
        massif_area: "", //            必传    地块面积
        coordinates: "", //            必传    地块坐标
        terrain: "", //                必传    地形
        slope: "", //                  必传    坡度
        crop_id: "", //                必传    农作物id
      },
      cropoptions: [],
      dialogVisible: false,
      rules: {
        massif_name: {
          required: true,
          message: "请输入地块名称",
          trigger: "blur",
        },
        terrain: {
          required: true,
          message: "请输入地块地形",
          trigger: "blur",
        },
        slope: {
          required: true,
          validator: validatePass2,
          trigger: "blur",
        },
        crop_id: {
          required: true,
          message: "请选择种植作物",
          trigger: "blur",
        },
      },
      alreadyhave: {
        area_addr: [],
      },
      faclist: [],
      dialogVisibleinfo: false,
      poltlistinfo: {},
      loading: false,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    dialogVisible(val) {
      if (val) {
        this.getcroplist();
      }
    },
  },
  //方法集合
  methods: {
    //返回上一页
    tofac() {
      this.$router.push(
        "/index/maofacility?lng=" +
          this.center[0] +
          "&lat=" +
          this.center[1] +
          "&id=" +
          this.base_id
      );
    },
    init() {
      console.log(this.center);
      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 {
          }
        });
      });
    },
    getbaslist() {
      this.loading = true;
      this.$axios({
        method: "post",
        url: "api/api_gateway?method=basemanager.baseinfo.list_land_base",
        data: this.qs.stringify({
          base_id: this.base_id,
        }),
      }).then((res) => {
        // this.loading = false;
        if (res.data.data) {
          var data = res.data.data.data;
          this.alreadyhave = data[0];
          var polygonArr = JSON.parse(data[0].coordinates);
          this.polygonArr = polygonArr;
          this.polyEdarr = [];
          this.polygon = new AMap.Polygon({
            map: this.map,
            path: polygonArr, //设置多边形边界路径
            strokeColor: "#4f71ff", //线颜色
            strokeOpacity: 0.5, //线透明度
            strokeWeight: 3, //线宽
            fillColor: "#1791fc", //填充色
            fillOpacity: 0.35, //填充透明度
          });
          // this.map.setFitView();
          this.polyEdarr.unshift(this.polygon);
          this.getpoltlist();
        }
      });
    },
    getpoltlist() {
      this.$axios({
        method: "post",
        url: "api/api_gateway?method=basemanager.baseinfo.get_massif_list",
        data: this.qs.stringify({
          base_id: this.base_id,
        }),
      }).then((res) => {
        this.loading = false;
        if (res.data.data) {
          var data = res.data.data.data;
          this.faclist = data;
          console.log(data);
          this.polygons = [];
          for (var i = 0; i < data.length; i++) {
            var polygonArr = JSON.parse(data[i].coordinates);
            var ploritem = new AMap.Polygon({
              map: this.map,
              path: polygonArr, //设置多边形边界路径
              strokeColor: data[i].crop_colors, //线颜色
              strokeOpacity: 0.5, //线透明度
              strokeWeight: 3, //线宽
              fillColor: data[i].crop_colors, //填充色
              fillOpacity: 0.35, //填充透明度
            });
            this.polyEdarr.push(ploritem);
            this.polygons.push(polygonArr);
          }
        }
      });
    },
    createPolygon() {
      if (this.underway) {
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message.warning("正在绘制中，请勿重复点击");
        }
        return;
      } else {
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message.success("开始绘制");
        }
      }
      this.underway = true;
      var polyEditor = new AMap.PolygonEditor(this.map);0
      polyEditor.addAdsorbPolygons(this.polyEdarr);
      this.polyEditor = polyEditor;
      polyEditor.on("add", this.plotend);
      polyEditor.on("addnode", this.plotaddnode);
      polyEditor.close();
      polyEditor.setTarget();
      polyEditor.open();
    },
    plotend(data) {
      var polygon = data.target;
      let land_polygon_path = data.target.getPath();
      console.log(this.polygons);
      let flag = this.polygons.some((item) => {
        // 两圈是否交叉
        var doesRingRingIntersect = AMap.GeometryUtil.doesRingRingIntersect(
          land_polygon_path,
          item
        );
        console.log(doesRingRingIntersect);
        //判断与其他地块相交
        var ringRingClip = AMap.GeometryUtil.ringRingClip(
          land_polygon_path,
          item
        );
        var ringArea = parseInt(AMap.GeometryUtil.ringArea(ringRingClip));
        console.log(ringArea);

        if (ringArea !== 0) {
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message.warning("地块与其他地块重叠，绘制无效");
          }
          this.polyEditor.close();
          this.underway = false;
          return true;
        } else {
          return false;
        }
      });
      console.log(flag);
      if (!flag) {
        this.polyEditor.addAdsorbPolygons(polygon);
        var path = data.obj.getOptions().path;
        var num = Math.round(AMap.GeometryUtil.ringArea(path));
        // console.log(num)
        this.polyinfo.massif_area = (num + num / 2) / 1000;
        this.polyinfo.coordinates = path;
        this.dialogVisible = true;
        // console.log(this.polyinfo.coordinates)
        this.polygons.push(polygon.getPath());
        setTimeout(() => {
          this.polyEditor.close();
        }, 10);
      }
      // 计算区域面积
    },
    plotaddnode(data) {
      console.log("添加了一个点");
      let Polygon = data.target;
      let point = data.lnglat;
      let isPointInRing = AMap.GeometryUtil.isPointInRing(
        point,
        this.polygonArr //基地坐标
      );
      if (!isPointInRing) {
        //true在基地范围内，false在基地范围外
        let path = Polygon.getPath();
        console.log(path);
        path = path.slice(0, -1); //去掉最后一个点
        Polygon.setPath(path);
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message.warning("超出基地范围,请在基地范围内绘制！");
        }
        return false;
      }
      //判断是否点击到地块内
      this.polygons.some((item) => {
        console.log(item);
        let flag = AMap.GeometryUtil.isPointInRing(
          point,
          item //基地坐标
        );
        if (flag) {
          //true在地块范围内，false在地块范围外，画地块时不能和其它地块重合
          let path = Polygon.getPath();
          path = path.slice(0, -1); //去掉最后一个点
          Polygon.setPath(path);
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message.warning("请不要画到已有地块内,请重新绘制！");
          }
          return true;
        }
      });
    },
    //取消
    addbtnfa() {
      // this.polyEditor.open();
      // // this.polyEditor.close()
      // this.map.remove(this.polyEditor)
      //删除围栏
      var polyArr = this.map.getAllOverlays("polygon");
      console.log(polyArr);
      if (polyArr.length == 1) {
        // $.msg("无围栏", 5);
      } else {
        this.map.remove(polyArr[0]);
        this.polygons.pop();
      }
      this.dialogVisible = false;
      this.underway = false;
    },
    //确定
    addbtn() {
      console.log(this.polyinfo);
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$axios({
            method: "post",
            url: "api/api_gateway?method=basemanager.baseinfo.add_massif",
            data: this.qs.stringify({
              base_id: this.base_id, //               必传    基地id
              massif_name: this.polyinfo.massif_name, //           必传    地块名称
              massif_area: this.polyinfo.massif_area, //           必传    地块面积
              coordinates: JSON.stringify(this.polyinfo.coordinates), //           必传    地块坐标
              terrain: this.polyinfo.terrain, //               必传    地形
              slope: this.polyinfo.slope, //                 必传    坡度
              crop_id: this.polyinfo.crop_id, //               必传    农作物id
            }),
          }).then((res) => {
            if (res.data.data) {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.success("添加成功");
              }
              this.dialogVisible = false;
              this.underway = false;
              this.polyinfo = {
                base_id: "", //              必传    基地id
                massif_name: "", //            必传    地块名称
                massif_area: "", //            必传    地块面积
                coordinates: "", //            必传    地块坐标
                terrain: "", //                必传    地形
                slope: "", //                  必传    坡度
                crop_id: "", //                必传    农作物id
              };
              this.$router.go(0);
            } else {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.error(res.data.message);
              }
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //获取种植物信息
    getcroplist(id) {
      this.$axios({
        method: "post",
        url: "api/api_gateway?method=basemanager.baseinfo.massif_by_crop_list",
        data: this.qs.stringify({
          massif_id: id,
        }),
      }).then((res) => {
        if (res.data.data) {
          var data = res.data.data;
          for (var i = 0; i < data.length; i++) {
            var obj = {
              value: data[i].crop_id,
              label: data[i].crop_name,
            };
            this.cropoptions.push(obj);
          }
        }
      });
    },
    //获取地块信息
    getpoltlistinfo(massif_name) {
      this.dialogVisibleinfo = true;
      this.$axios({
        method: "post",
        url: "api/api_gateway?method=basemanager.baseinfo.get_massif_list",
        data: this.qs.stringify({
          base_id: this.base_id,
          massif_name: massif_name,
        }),
      }).then((res) => {
        this.loading = false;
        if (res.data.data) {
          var data = res.data.data.data;
          this.poltlistinfo = data[0];
          console.log(data);
        }
      });
    },
    //提交修改信息
    addbtninfo() {
      console.log(this.poltlistinfo);
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$axios({
            method: "post",
            url: "api/api_gateway?method=basemanager.baseinfo.modify_massif",
            data: this.qs.stringify({
              massif_name: this.poltlistinfo.massif_name, //           必传    地块名称
              massif_id: this.poltlistinfo.massif_id,
              terrain: this.poltlistinfo.terrain, //               必传    地形
              slope: this.poltlistinfo.slope, //                 必传    坡度
              crop_id: this.poltlistinfo.crop_id, //               必传    农作物id
            }),
          }).then((res) => {
            if (res.data.data) {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.success("修改成功");
              }
              this.dialogVisibleinfo = false;
              this.poltlistinfo = {};
            } else {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.error(res.data.message);
              }
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //删除地块
    delfac(massif_id) {
      this.$confirm("此操作将删除该地块, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            method: "post",
            url: "api/api_gateway?method=basemanager.baseinfo.del_massif",
            data: this.qs.stringify({
              massif_id: massif_id,
            }),
          }).then((res) => {
            if (res.data.message == "") {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.map.clearMap();
              this.getbaslist();
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    if (this.$route.query.lng == "") {
      this.center = [116.412427, 39.303573];
    } else {
      this.center = [this.$route.query.lng, this.$route.query.lat];
    }
    console.log(this.center);
    this.base_id = this.$route.query.id;
  },
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.init();
    this.getbaslist();
  },
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.plotbox {
  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;
    }
  }
  .listbox {
    position: absolute;
    width: 350px;
    height: 95%;
    top: 2.5%;
    right: 15px;
    background-color: #fff;
    border-radius: 10px;
    padding: 20px;
    box-sizing: border-box;
    .listbox_base {
      width: 100%;
      border-bottom: 1px solid #f2f2f2;
      p {
        font-size: 14px;
        margin-bottom: 8px;
        overflow: hidden; //溢出隐藏
        white-space: nowrap; //禁止换行
        text-overflow: ellipsis; //...
        color: #262626;
      }
      p:first-child {
        font-size: 28px;
        margin-bottom: 10px;
        color: #262626;
      }
    }
    .listbox_fac {
      width: 100%;
      height: calc(100% - 133px);
      .table_page {
        width: 100%;
        display: flex;
        P {
          width: 50%;
          text-align: center;
          height: 30px;
          line-height: 30px;
          cursor: pointer;
        }
        .table_page_act {
          border-bottom: 2px solid #4f71ff;
          color: #4f71ff;
        }
      }
      .listbox_facbox {
        width: 100%;
        height: calc(100% - 32px);
        overflow-y: auto;
        .tishi {
          width: 100%;
          padding: 20px 0;
          box-sizing: border-box;
          text-align: center;
        }
        .listbox_facbox_item {
          width: 100%;
          background-color: #ecf5ff;
          padding: 10px;
          box-sizing: border-box;
          margin-top: 10px;
          p {
            font-size: 14px;
            color: #262626;
          }
          .title {
            font-size: 16px;
            margin-bottom: 10px;
            // font-weight: 700;
            overflow: hidden; //溢出隐藏
            white-space: nowrap; //禁止换行
            text-overflow: ellipsis; //...
            color: #262626;
          }
          .caozuo {
            display: flex;
            font-size: 14px;
            margin-top: 5px;
            div:first-child {
              width: 70%;
              overflow: hidden; //溢出隐藏
              white-space: nowrap; //禁止换行
              text-overflow: ellipsis; //...
            }
            div:nth-child(2) {
              display: flex;
              P {
                margin-left: 10px;
                cursor: pointer;
              }
              p:first-child {
                color: #4f71ff;
              }
              P:last-child {
                color: red;
              }
            }
          }
        }
      }
    }
  }
}
</style>