<!-- 灌溉地图展示 -->
<template>
  <div class="map">
    <div id="container">加载数据，请稍候...</div>
    <!-- 设备列表 -->
    <div class="equipListBox">
      <div class="searchTop">
        <div>设备列表</div>
        <!-- <div>
          <el-input
            size="small"
            placeholder="请选择设备"
            suffix-icon="el-icon-search"
            v-model="searchVal"
          ></el-input>
        </div> -->
      </div>
      <div class="inner">
        <div class="scroll">
          <el-scrollbar>
            <div class="equipList">
                <div class="item"
                v-for="(item,index) in equipData" :key="index" @click="lookEquip(item)">
                    <div class="">
                        <img :src="require('../../../../static/images/disasterWarn/navicon.png')" alt="">
                        <span :ref="`equipName${index}`" v-if="item.key==0">{{item.name}}</span>
                        <el-input class="changeNameVal" v-else v-model="editNameval" placeholder="请输入内容"></el-input>
                    </div>
                    <div>
                      <i @click.stop="editName('edit',item,index)" v-show="item.key==0" class="el-icon-edit"></i>
                      <i @click.stop="editName('cancel',item,index)" v-show="item.key==1" class="el-icon-close"></i>
                      <i @click.stop="editName('save',item,index)" v-show="item.key==1" class="el-icon-check"></i>
                    </div>
                </div>
                <div class="item" v-if="!equipData.length">
                   暂无数据 
                </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
    <!-- 设备提示框 -->
    <windowPopUp ref="windowPopUp"></windowPopUp>
    <sidebarWarn :qxzName="equips.qxzName" :jkName="equips.jkName" :projectName="equips.projectName" @setQxzEleName='setQxzEleName' ref="sidebarWarnRef"></sidebarWarn>
    <div class="popupInner">
      <!-- 设备预警 -->
      <div v-show="equipWarnBox" class="equipWarnBox suspensionBox">
        <div class="top">
          <div>设备预警</div>
          <!-- <div >
            <i class="el-icon-caret-right"></i>
          </div> -->
        </div>
        <div class="inner">
          <div class="wranTitle">
            <div
              v-for="(item,index) in wranTitle"
              v-bind:key="item"
              :class="[index==1?'wranmsg':'']"
            >{{item}}</div>
          </div>
          <div class="equipList">
            <div
              class="scroll-content"
              ref="scrollContent"
              :style="{ top }"
              @mouseenter="Stop()"
              @mouseleave="Up()"
            >
              <div class="wranInfo" v-for="item in scrollWranList" v-bind:key="item.id">
                <div>{{item.device_id}}</div>
                <div class="wranmsg">{{item.warning_info}}</div>
                <div>{{item.warning_time | formatTime}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 气象站修改要素名称 -->
    <el-dialog
      class="figEldialog"
      :visible.sync="qxzDialogVisible"
      width="450px"
      top="230px"
      :modal="false"
      :close-on-click-modal="true"
      v-dialogDrag
      @close="closeQxzDialogVisible"
    >
      <template slot="title">
          <div class="avue-crud__dialog__header">
              <span class="el-dialog__title">
              <span style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
                要素名称修改
              </span>
          </div>
        </template>
        <div class="equipEleData">
          <el-scrollbar >
            <div class="equipEleList">
              <div v-for="(item,index) in changeQxzEleName" :key="index">
                <span>{{item.e}}</span>
                <span>{{item.defaultName}}</span>
                <span class="inp">
                  <el-input v-model="item.editname" @blur="changeQxzName(item,index)" placeholder="请输入内容"></el-input>
                </span>
              </div> 
            </div>
          </el-scrollbar>
        </div>
        <!-- <div class="equipEleSaveBtn">
          <el-button type="grayInfo" size="small" >重置</el-button>
          <el-button type="blueInfo" size="small" >保存</el-button>
        </div> -->
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import windowPopUp from "./windowPopUp"
import sidebarWarn from "./sidebarWarn"

// 要素配置表
import eleList from "../../../../static/js/irrigate/eleList.json"
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    windowPopUp,
    sidebarWarn
  },
  data() {
    //这里存放数据
    return {
      user_id:'',
      equips:{
        qxzId:'',
        qxzDid:'',
        qxzName:'',
        jkId:'',
        jkDid:'',
        jkName:'',
        projectName:'',
      },
      map: null,
      center: [116.3683244, 39.915085],
      zoom: 4.5,
      tileLayer1: null,
      tileLayer2: null,
      equipWarnBox:true,//预警信息弹框
      // 设备列表
      equipData: [],
      equipAllList: [],
      editNameval:'',
      // 设备预警滚动
      wranTitle: ["设备ID", "预警信息", "时间"],
      scrollWranList: [],
      activeIndex: 0,
  
      searchVal: "",
      marker: null,
      markerList: [],
      infoWindow: null,
      qxzDialogVisible:false,
      changeQxzEleName:[],
    };
  },
  //监听属性 类似于data概念
  computed: {
    top() {
      return -this.activeIndex * 22 + "px";
    }
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    initMap() {
      //创建地图
      var that = this;
      this.map = new AMap.Map("container", {
        resizeEnable: true,
        center: that.center,
        zoom: that.zoom
      });
      AMap.plugin(
        [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.MouseTool",
          "AMap.Geocoder",
          "AMap.PolyEditor"
        ],
        () => {
          //   this.map.addControl(new AMap.ToolBar());
          this.map.addControl(new AMap.Scale({ position: "LB" }));

          this.geocoder = new AMap.Geocoder({
            city: "全国",
            radius: 1000
          });
        }
      );
      this.tileLayer1 = new AMap.TileLayer({
        tileUrl:
          "http://t{0,1,2,3,4,5,6,7}.tianditu.gov.cn/DataServer?T=img_w&tk=888bc7de1a5f14aa1b335b02e558d9b3&x=[x]&y=[y]&l=[z]",
        zIndex: 10
      }); //卫星图层
      this.tileLayer2 = new AMap.TileLayer({
        // 图块取图地址
        tileUrl:
          "http://t{0,1,2,3,4,5,6,7}.tianditu.gov.cn/DataServer?T=cta_w&tk=888bc7de1a5f14aa1b335b02e558d9b3&x=[x]&y=[y]&l=[z]",
        zIndex: 101
      });
      this.map.add(this.tileLayer1);
      this.map.add(this.tileLayer2);
      this.getEquipList();
      this.getWranInfo();
    },
    getEquipList() {
      this.equipData = [
        // {
        //   name:'灾害预警项目一',
        //   lnglat:[113,46],
        //   equips:[
        //     {id:123,type:11},
        //     {id:123,type:11},
        //   ]
        // }
      ];
      this.$axios({
        method: "post",
        url: "/api/api_gateway?method=weather.weather.warning_page",
        data: this.qs.stringify({
          user_id:this.user_id
        })
      }).then(res => {
        var dat = res.data.data.ids;
        this.equipAllList = [];
        for(var i = 0;i<dat.length;i++){
          if(i == 0){
            this.equipAllList.push({
              name:dat[i].name,
              lnglat:dat[i].lnglat,
              equips:[dat[i]]
            })
          }else{
            for(var z = 0;z<this.equipAllList.length;z++){
              if(dat[i].name == this.equipAllList[z].name){
                this.equipAllList[z].equips.push(dat[i])
                break;
              }
              if(z == this.equipAllList.length-1){
                this.equipAllList.push({
                  name:dat[i].name,
                  lnglat:dat[i].lnglat,
                  equips:[dat[i]]
                })
                break;
              }
            }
          }
          if(i == dat.length-1){
            console.log(this.equipAllList);
            this.equipData = this.equipAllList.filter((item)=>{
              item.key=0;//用于修改设备名input是否展示
              return item.equips.length==2
            })
            console.log(this.equipData);
            this.renderEle();
          }
        }

      });
    },
    // 渲染点标注
    renderEle() {
      this.map.remove(this.markerList);
      this.markerList = [];
      this.equipData.forEach(item => {
        var icon = "../../../../static/images/disasterWarn/disasterWarnIcon.svg";
        var itemlnglat = item["lnglat"];
        this.marker = new AMap.Marker({
          position: new AMap.LngLat(itemlnglat[0], itemlnglat[1]), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          icon: new AMap.Icon({            
              image: icon,
              size: new AMap.Size(50, 50),  //图标大小
              imageSize: new AMap.Size(50, 50)
          }),
          offset: new AMap.Pixel(-13, -30),
          title: item["name"]
        });
        // 设置点标记的动画效果，此处为弹跳效果
        // this.marker.setAnimation('AMAP_ANIMATION_BOUNCE');
        this.markerList.push(this.marker);
        //信息窗体
        this.marker.content = item["name"];
        AMap.event.addListener(this.marker, "click", event => {
          this.markerClick(event, item);
        });
        AMap.event.addListener(this.map, "click", event => {
          if (this.infoWindow) {
            this.infoWindow.close();
          }
        });
      });
      this.$nextTick(() => {
        this.map.add(this.markerList);
        this.map.setFitView();
      });
      this.infoWindow = new AMap.InfoWindow({
        isCustom: true, //使用自定义窗体
        offset: new AMap.Pixel(-105, -20)
        // anchor:'bottom-righ'
      });
    },
    markerClick(event, item) {
      console.log(item);
      if(item.equips[0].device_type_id == 11){
        this.equips.qxzId = item.equips[0].device_id
        this.equips.qxzName = item.equips[0].device_name
        this.equips.qxzDid = item.equips[0].d_id
      }else{
        this.equips.qxzId = item.equips[1].device_id
        this.equips.qxzName = item.equips[1].device_name
        this.equips.qxzDid = item.equips[1].d_id
      }
      if(item.equips[0].device_type_id == 12){
        this.equips.jkId = item.equips[0].device_id
        this.equips.jkName = item.equips[0].device_name
        this.equips.jkDid = item.equips[0].d_id
      }else{
        this.equips.jkId = item.equips[1].device_id
        this.equips.jkName = item.equips[1].device_name
        this.equips.jkDid = item.equips[1].d_id
      }
      this.equips.projectName=item.name
      this.$store.commit('setData',{
        name:'jk_wran_id',
        val:this.equips.jkId
      })
      this.$store.commit('setData',{
        name:'jk_wran_did',
        val:this.equips.jkDid
      })
      this.$store.commit('setData',{
        name:'jk_wran_name',
        val:this.equips.projectName
      })
      this.$store.commit('setData',{
        name:'qxz_wran_id',
        val:this.equips.qxzId
      })
      this.$store.commit('setData',{
        name:'qxz_wran_did',
        val:this.equips.qxzDid
      })
      this.equipWarnBox = false;
      this.$refs.sidebarWarnRef.toggleMenuShow();
      this.$refs.sidebarWarnRef.getQxzEle();
      this.$refs.sidebarWarnRef.getMonitor();
      this.infoWindow = new AMap.InfoWindow({
        isCustom: true, //使用自定义窗体
        offset: new AMap.Pixel(16, -45)
      });
      this.$refs.windowPopUp.initialize({
        currEquip: {device_type_id:1234},
        visible: true,
        infoWindow: this.infoWindow
      });
      this.infoWindow.setContent(this.$refs.windowPopUp.$el);
      this.infoWindow.open(this.map, event.target.getPosition());
    },
    lookEquip(item){
      this.map.setCenter(item.lnglat)
      this.map.setZoom(17)
    },
    getWranInfo(){
      this.$axios({
        method: "post",
        url: "/api/api_gateway?method=weather.weather.warning_info", //forecast.forecast_system.equip_photo
        data: this.qs.stringify({
          page_size: 10,
        }),
      })
      .then((res) => {
        if(res.data.message == ""){
          this.scrollWranList = res.data.data.data
        }
      })
      .catch((err) => {
        console.log(err);
      });
    },
    ScrollUp() {
      this.intnum = setInterval(_ => {
        this.$refs.scrollContent.style.transition = "top 0.5s";
        if (this.activeIndex < this.scrollWranList.length - 5) {
          this.activeIndex += 1;
        } else {
          this.$refs.scrollContent.style.transition = "none";
          this.activeIndex = 0;
        }
      }, 1000);
    },
    Stop() {
      clearInterval(this.intnum);
    },
    Up() {
      this.ScrollUp();
    },
    equipWarnBoxShow(){
      this.equipWarnBox=true;
    },
    editName(ctrl,item,index){
      if(ctrl == 'edit'){
        this.equipData.forEach((item)=>{
          item.key = 0
        })
        this.equipData[index].key = 1
        this.editNameval = this.equipData[index].name;
      }
      if(ctrl == 'cancel'){
        this.equipData.forEach((item)=>{
          item.key = 0
        })
      }
      if(ctrl == 'save'){
        var id = item.equips[0].device_id+','+item.equips[1].device_id
        this.$axios({
          method: "post",
          url: "/api/api_gateway?method=weather.weather.warning_change",
          data: this.qs.stringify({
            device_id: id,
            name: this.editNameval,
          })
        }).then(res => {
          if (res.data.message == "") {
                this.$message({
                  type: "success",
                  message: "修改成功",
                });
                this.equipData.forEach((item)=>{
                  item.key = 0
                })
                this.equipData[index].name = this.editNameval
              }else{
                this.$message({
                  type: "error",
                  message: res.data.message,
                });
              }
        })
      }
      
    },
    setQxzEleName(data){
      this.qxzDialogVisible = true
      this.changeQxzEleName = data;     
    },
    changeQxzName(item,index){
      this.$confirm('是否更改要素名称?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios({
        method: "post",
        url: "/api/api_gateway?method=weather.weather.qxz_config_change",
        data: this.qs.stringify({
          device_id:this.$store.state.qxz_wran_id,
          ekey:item.e,
          conf:item.editname+'#'+item.unit
        })
      }).then(res => {
        if(res.data.message == ""){
          this.$message({
            message: '修改成功',
            type: 'success'
          });
        }
      })
      }).catch(() => {
          this.changeQxzEleName[index].editname = this.changeQxzEleName[index].name
      });
    },
    closeQxzDialogVisible(){
      this.$refs.sidebarWarnRef.getQxzEle();
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.user_id = this.$store.state.disasterWarnUserId;
    this.initMap();
    this.$nextTick(() => {
      this.ScrollUp();
    });
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {
    this.Stop();
  }, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang='less'>
.map,
#container {
  width: 100%;
  height: 100%;
  position: relative;
}

.equipListBox {
  position: absolute;
  left: 35px;
  top: 30px;
  bottom: 3.125rem;
  width: 3.5rem;
  background: rgba(12, 20, 44, 0.8);
  border-radius: 8px;
  overflow: hidden;
  z-index: 200;
  .searchTop {
    display: flex;
    justify-content: space-between;
    color: #fff;
    align-items: center;
    padding: 10px;
    background: #0c142c;
    .el-input {
      width: 2.25rem;
      input {
        background: #ececec;
        color: #000;
        padding: 5px;
        height: 27px;
      }
      /deep/.el-input__inner {
        height: 28px;
        line-height: 28px;
      }
    }
  }
  .inner {
    position: absolute;
    top: 52px;
    bottom: -18px;
    left: 0;
    right: 0;
    .scroll {
      height: 100%;
      overflow: auto;
      .equipList {
        .item {
          padding: 0.175rem;
          color: #fff;
          font-size: 0.175rem;
          cursor: pointer;
          display: flex;
          justify-content: space-between;
          >div{
                display: flex;
            justify-content: left;
            align-items: center;
          }
          >span:nth-child(1){
            width: 72%;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          >div{
            i{
              font-size: 20px;
            }
            i:nth-child(1){
              font-size: 18px;
              display: none;
            }
            i:nth-child(2){
              color: red;
            }
            i:nth-child(3){
              color: green;
            }
          }
          >span:nth-child(2){
              font-size: 14px;
          }
          img {
            margin-right: 2px;
          }
          &:hover {
            background: #0c142c;
          }
          .changeNameVal{
            /deep/.el-input__inner{
              background: none;
              outline: none;
              border: 1px solid #6b6b6b;
              color: #fff;
              height: 28px;
              padding: 0 5px;
            }
          }
        }
        .item:hover{
          >div{
            i:nth-child(1){
              display: block;
            }
          }
        }
        .item.active {
          background: #0c142c;
        }
      }
    }
    .scroll {
      height: 100%;
      overflow-y: hidden;
    }
    .el-scrollbar {
      height: 100%;
    }
    .el-scrollbar__bar {
      &.is-vertical {
        width: 100px; //滚动条宽度
      }
    }
    .el-scrollbar__wrap {
      overflow-y: auto;
      overflow-x: hidden;
    }
    .el-scrollbar__thumb {
      // 可设置滚动条颜色
      background: red;
    }
  }
}
// 悬浮框样式
.popupInner {
  position: absolute;
  right: 0;
  top: 12px;
  z-index: 200;
}
.suspensionBox {
  // position: absolute;
  width: 400px;
  background: rgba(12, 20, 44, 0.8);
  border-radius: 8px;
  overflow: hidden;
  z-index: 100;
  margin-top: 20px;
  .top {
    display: flex;
    justify-content: space-between;
    color: #fff;
    align-items: center;
    padding: 10px;
    background: #0c142c;
    i {
      cursor: pointer;
      font-size: 14px;
    }
  }
}
// 设备预警
.equipWarnBox {
  height: 190px;
  right: 10px;
  // top: 160px;
  .inner {
    // height: 82px;
    // overflow: hidden;
    .wranTitle {
      display: flex;
      justify-content: space-around;
      line-height: 33px;
      color: #fff;
      .wranmsg {
        width: 157px;
      }
    }
    .equipList {
      height: 110px;
      overflow: hidden;
      .scroll-wrap {
        height: 150px;
        overflow: hidden;
      }
      .scroll-content {
        position: relative;
        transition: top 0.5s;
        .wranInfo {
          line-height: 22px;
          color: #92c2f3;
          display: flex;
          justify-content: space-around;
          .wranmsg {
            width: 157px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          .state {
            color: red;
          }
        }
      }
      .scroll-content p {
        line-height: 50px;
        text-align: center;
      }
    }
  }
}


// 设备定位弹框
/deep/.setlnglatBox{
  box-shadow: 0px 0px 4px 0px #0161ff;
  background: rgba(12, 20, 44, 0.8);
  border-radius: 8px;
}
/deep/.setlnglatBox .el-dialog__header{
  background: #0c142c;
  padding: 10px 20px;
  border-bottom: 1px solid #0c142c;
}
/deep/.setlnglatBox .el-dialog__header .el-dialog__title{
  color: #fff;
  font-size: 14px;
}
/deep/.setlnglatBox .el-dialog__headerbtn .el-dialog__close{
  color: #fff;
}
// 设置要素名称
.equipEleData{
  .el-scrollbar{
    height: 230px;
    /deep/.el-scrollbar__wrap{
      overflow-x: hidden;
    }
    /deep/.el-scrollbar__thumb{
      background: #0165b8;
    }
  }
  .equipEleList{
    display: flex;
    justify-content: left;
    flex-wrap: wrap;
    >div{
      display: flex;
      align-items: center;
      margin: 10px 0;
      width: 100%;
      span:nth-child(1){
        color: #04d5e8;
        width: 33px;
      }
      span:nth-child(2){
        color: #04d5e8;
        width: 135px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        margin-right: 10px;
      }
      .inp{
        width: 200px;
        /deep/input{
          background: none;
          outline: none;
          border: 1px solid #0c142c;
          color: #92c2f3;
          height: 36px;
          padding: 0 5px;
          background: #0c142c;
        }
      }
      
    }
  }
}
.equipEleSaveBtn{
  text-align: right;
}

</style>