<!-- 绘制设备  -->
<template>
  <div class="facilitybox">
    <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="drawfa">绑定设备</div>
    </div>
    <div class="listbox" v-loading="baseloading">
      <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 @click="tofac" class="table_page_no">地块信息</p>
          <p class="table_page_act">设备信息</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.tpye_name }}</p>
            <div class="caozuo">
              <div>{{ item.device_id }}</div>
              <div>
                <p @click="delfac(item.ld_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="facdiabox">
        <div class="top_search">
          <div class="firstsearch">
            <el-select v-model="type_id" size="mini" placeholder="请选择">
              <el-option
                v-for="item in type_idoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <div class="firstsearch">
            <el-input
              v-model="device_id"
              size="mini"
              placeholder="请输入设备ID"
            ></el-input>
          </div>
          <div class="btnbox" @click="getwormlist">查询</div>
        </div>
        <div class="bot_table" v-loading="loading">
          <el-table :data="facilitylist" style="width: 100%">
            <el-table-column width="50px">
              <template slot-scope="scope">
                <el-radio
                  v-model="facinfo.device_id"
                  :label="scope.row.device_id"
                >
                </el-radio>
              </template>
            </el-table-column>
            <el-table-column label="设备编号" width="150px">
              <template slot-scope="scope">{{ scope.row.device_id }}</template>
            </el-table-column>
            <el-table-column label="设备名称">
              <template slot-scope="scope">{{
                scope.row.device_name
              }}</template>
            </el-table-column>
            <el-table-column label="设备类型">
              <template slot-scope="scope">{{
                scope.row.device_type_name
              }}</template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination
            background
            layout="prev, pager, next,jumper"
            :total="total"
            :page-size="8"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </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文件，图片文件等等）

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      map: "",
      center: [],
      city: "",
      base_id: "",
      Polygon: null,
      polyonarr: [],
      dialogVisible: false,
      facilitylist: [],
      total: 10,
      type_id: "",
      device_id: "",
      type_idoptions: [],
      facinfo: {
        device_id: "",
        coordinates: [],
      },
      loading: false,
      marker: null,
      underway: false,
      alreadyhave: {
        area_addr: [],
      },
      faclist: [],
      baseloading: false,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    dialogVisible(val, newval) {
      console.log(val);
      if (val == true) {
        this.getfacilitylist();
      }
    },
  },
  //方法集合
  methods: {
    //返回上一页
    tofac() {
      this.$router.push(
        "/index/mapplot?lng=" +
          this.center[0] +
          "&lat=" +
          this.center[1] +
          "&id=" +
          this.base_id
      );
    },
    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;
    },
    getbaslist() {
      this.baseloading = 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.Polygon = new AMap.Polygon({
            map: this.map,
            path: polygonArr, //设置多边形边界路径
            strokeColor: "#4f71ff", //线颜色
            strokeOpacity: 0.5, //线透明度
            strokeWeight: 3, //线宽
            fillColor: "#1791fc", //填充色
            fillOpacity: 0.35, //填充透明度
          });
          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;
          console.log(data);
          for (var i = 0; i < data.length; i++) {
            var polygonArr = JSON.parse(data[i].coordinates);
            var polyon = 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.polyonarr.push(polyon);
          }
          this.getgaclisting();
        }
      });
    },
    getgaclisting() {
      this.$axios({
        method: "post",
        url: "api/api_gateway?method=basemanager.device.list_land_device",
        data: this.qs.stringify({
          base_id: this.base_id,
          page: 1,
          page_size: 99999999,
        }),
      }).then((res) => {
        this.baseloading = false;
        if (res.data.data) {
          var data = res.data.data.data;
          this.faclist = data;
          console.log(data);
          for (var i = 0; i < data.length; i++) {
            var icon = new AMap.Icon({
              size: new AMap.Size(28, 30),
              image:
                "../../../static/images/map/" + data[i].device_type_id + ".png",
              imageSize: new AMap.Size(28, 30),
            });
            //创建marker
            console.log(JSON.parse(data[i].coordinates));
            new AMap.Marker({
              position: new AMap.LngLat(
                JSON.parse(data[i].coordinates)[0],
                JSON.parse(data[i].coordinates)[1]
              ),
              icon: icon,
              map: this.map,
              offset: new AMap.Pixel(-14, -30),
            });
          }
        }
      });
    },
    drawfa() {
      if (document.getElementsByClassName("el-message").length == 0) {
        this.$message.success("开始绑定");
      }
      if (this.underway) {
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message.warning("正在绘制中，请勿重复点击");
        }
        return;
      }
      this.underway = true;
      this.map.on("click", (e) => {
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message.warning("请在基地内点击");
        }
      });
      this.Polygon.on("click", (e) => {
        var icon = new AMap.Icon({
          size: new AMap.Size(28, 30),
          image: "../../../static/images/map/all.png",
          imageSize: new AMap.Size(28, 30),
        });
        //创建marker
        this.marker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
          icon: icon,
          map: this.map,
          offset: new AMap.Pixel(-14, -30),
        });
        this.facinfo.coordinates = [e.lnglat.getLng(), e.lnglat.getLat()];
        this.dialogVisible = true;
      });
      for (var i = 0; i < this.polyonarr.length; i++) {
        this.polyonarr[i].on("click", (e) => {
          // console.log(e);
          var icon = new AMap.Icon({
            size: new AMap.Size(28, 30),
            image: "../../../static/images/map/all.png",
            imageSize: new AMap.Size(28, 30),
          });
          //创建marker
          this.marker = new AMap.Marker({
            position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
            icon: icon,
            map: this.map,
            offset: new AMap.Pixel(-14, -30),
          });
          this.facinfo.coordinates = [e.lnglat.getLng(), e.lnglat.getLat()];
          this.dialogVisible = true;
        });
      }
    },
    getwormlist() {
      this.page = 1;
      this.getfacilitylist();
    },
    handleCurrentChange(e) {
      this.page = e;
      this.getfacilitylist();
    },
    getfacilitylist() {
      this.loading = true;
      this.$axios({
        method: "post",
        url: "api/api_gateway?method=basemanager.device.get_land_device_list",
        data: this.qs.stringify({
          type_id: this.type_id, //       非必须     设备类型id
          device_id: this.device_id, //     非必须     设备编号
          page: this.page,
          page_size: 10,
        }),
      }).then((res) => {
        this.loading = false;
        if (res.data.data) {
          console.log(res.data.data);
          this.type_idoptions = []
          this.facilitylist = res.data.data.device_list;
          this.total = res.data.data.total_num;
          var type_list = res.data.data.type_list;
          for (var i = 0; i < type_list.length; i++) {
            var obj = {
              value: type_list[i].type_id,
              label: type_list[i].type_name,
            };
            this.type_idoptions.push(obj);
          }
        }
      });
    },
    addbtnfa() {
      this.dialogVisible = false;
      this.map.remove(this.marker);
    },
    addbtn() {
      console.log(this.facinfo);
      if (this.facinfo.device_id == "") {
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message.warning("请选择绑定设备");
        }
        return;
      }
      console.log(1111);
      this.$axios({
        method: "post",
        url: "api/api_gateway?method=basemanager.device.add_land_device",
        data: this.qs.stringify({
          base_id: this.base_id,
          device_id: this.facinfo.device_id, //     必须     设备编号
          coordinates: JSON.stringify(this.facinfo.coordinates), //   必须     设备坐标
        }),
      }).then((res) => {
        if (res.data.data) {
          if (res.data.data) {
            if (document.getElementsByClassName("el-message").length == 0) {
              this.$message.success("绑定成功");
            }
            this.dialogVisible = false;
            this.underway = false;
            this.facinfo = {
              device_id: "",
              coordinates: "",
            };
            this.$router.go(0);
          } else {
            if (document.getElementsByClassName("el-message").length == 0) {
              this.$message.error(res.data.message);
            }
          }
        }
      });
    },
    //删除地块
    delfac(ld_id) {
      this.$confirm("此操作将此设备与当前基地解绑, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            method: "post",
            url: "api/api_gateway?method=basemanager.device.del_land_device",
            data: this.qs.stringify({
              ld_id: ld_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];
    }
    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>
.facilitybox {
  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;
    }
  }
}
.facdiabox {
  .top_search {
    display: flex;
    margin-bottom: 20px;
    .firstsearch {
      margin-right: 10px;
    }
    .btnbox {
      width: 68px;
      height: 26px;
      border: 1px solid #4f71ff;
      text-align: center;
      border-radius: 3px;
      font-size: 14px;
      line-height: 26px;
      background-color: #4f71ff;
      color: #fff;
      cursor: pointer;
    }
  }
  /deep/.el-radio__label {
    display: none;
  }
  /deep/.el-table__header {
    th {
      background-color: #f1f1f3;
    }
  }
  .pagination {
    margin-top: 20px;
    /deep/.el-pager {
      .active {
        background-color: #4f71ff !important;
      }
    }
    /deep/.el-input__inner:hover {
      border-color: #4f71ff;
    }
  }
}
.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: 80%;
            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>