<template>
  <div>
    <!--筛选条件-->
    <div class="map-search-div">
      <el-form ref="selectForm" :inline="true" :model="listQuery" class="form-container">
        <el-row>
          <el-form-item label="搜索：">
            <el-input v-model.trim="listQuery.keywords" placeholder="闸井编号/地址" clearable/>
          </el-form-item>
          <el-form-item v-if="wellTypeList.length>1">
            <el-select v-model="listQuery.wellType" placeholder="选择闸井类型" clearable>
              <el-option
                v-for="item in wellTypeList"
                :key="item.value"
                :label="item.name"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <dept-select v-model="listQuery.deptid" :need-top="deptShowTop" dept-type="03" placeholder="选择权属单位"/>
          </el-form-item>
          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
          <el-form-item style="margin-left:10px">
            <el-checkbox v-model="showAll">显示全部闸井</el-checkbox>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="refresh-div">
      <span class="font-red">{{ count }}</span>  s后刷新<i class="el-icon-refresh" @click="refreshAlarm"/>
    </div>
    <div v-if="alarmWells.length>0" class="map-alarm-div">
      <div class="map-alarm-div-header">
        告警列表
        <span class="icon-right" @click="tableShow=!tableShow">
          <i v-if="tableShow" class="el-icon-arrow-up"/>
          <i v-else class="el-icon-arrow-down"/>
        </span>
      </div>
      <transition name="el-collapse-transition">
        <el-scrollbar
          v-show="tableShow"
          :style="{visibility: tableShow?'visible':'hidden'}"
          :class="{moredatascollor:alarmList.length>6}"
          :native="false">
          <el-table
            :data="alarmList"
            class="alarm-list-table"
            border
            @row-click="alarmRowClick">
            <el-table-column v-for="column in columns" :key="column.value" :label="column.text" :width="column.width" :align="column.align" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row[column.value] }}
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </transition>
    </div>
    <div v-loading="loading" class="overview-map-container">
      <!--地图-->
      <el-amap ref="map" :center="center" :zoom="zoom" :plugin="plugins" vid="overview" class="map-demo">
        <!--闸井marker-->
        <el-amap-marker
          v-for="(marker,index) in markers"
          :key="'well'+marker.wellId"
          :position="marker.position"
          :offset="offset"
          :vid="index"
          :visible="marker.visible"
        >
          <div>
            <svg-icon :icon-class="marker.icon" @click="openInfoWindow(marker.wellId)" />
          </div>
        </el-amap-marker>
        <!--报警marker-->
        <el-amap-marker
          v-for="(alarm,index) in alarmWells"
          :key="alarm.wellId"
          :position="alarm.position"
          :offset="alarmOffset"
          :visible="alarm.visible"
          :vid="index"
          animation="AMAP_ANIMATION_BOUNCE"
        >
          <div>
            <svg-icon icon-class="alarm-well" class="alarm-icon" @click="openAlarmWindow(alarm.wellId,alarm.position)" />
          </div>
        </el-amap-marker>
        <!--正常信息弹窗-->
        <el-amap-info-window
          v-if="wellInfo"
          :position="currentWindow.position"
          :visible="currentWindow.visible"
          :class="infoWindowClass"
        >
          <div v-if="currentWindow.windowType=='info'?true:false" class="info-window">
            <div class="info-header">{{ wellInfo.wellCode }}</div>
            <div class="info-body">
              <div>闸井类型：{{ wellInfo.wellTypeName }}</div>
              <div>井深：{{ wellInfo.deep }}(m)</div>
              <div>权属单位：{{ wellInfo.deptName }}</div>
              <div>详细地址：{{ wellInfo.position }}</div>
            </div>
          </div>
          <div v-if="currentWindow.windowType=='alarm'?true:false" class="alarm-window">
            <div class="alarm-header">
              <svg-icon icon-class="alarm-red" />
              {{ alarmInfo.wellCode }}
            </div>
            <div class="alarm-body">
              <div v-for="alarm in alarmInfo.alarms" :key="alarm.id">
                <div>告警原因：<span class="alarm-red">{{ alarm.alarmContent }}</span></div>
                <div>设备编号：<span>{{ alarm.devcode }}</span></div>
              </div>
              <el-divider/>
              <div>井深：{{ alarmInfo.deep }}(m)</div>
              <div>权属单位：{{ alarmInfo.deptName }}</div>
              <div>详细地址：{{ alarmInfo.position }}</div>
            </div>
          </div>
        </el-amap-info-window>
      </el-amap>
    </div>
  </div>
</template>

<script>
import SelectTree from '@/components/SelectTree/singleSelect'
import { getWellType } from '@/api/well'
import { getWellList, getWellInfo, getAlarmsNow, getWellAlarms } from '@/api/overview'
import DeptSelect from '../../components/DeptSelect/index'

export default {
  name: 'Overview',
  components: { DeptSelect, SelectTree },
  data() {
    return {
      listQuery: {
        keywords: '', // 关键字
        wellType: '', // 井类型
        deptid: '', // 组织机构
        isAlarm: '1' // 是否报警
      }, // 筛选条件
      columns: [
        {
          text: '闸井编号',
          value: 'wellCode',
          width: 100,
          align: 'center'
        },
        {
          text: '设备编号',
          value: 'devcode',
          width: 120,
          align: 'center'
        },
        {
          text: '告警原因',
          value: 'alarmContent',
          align: 'center',
          width: 120
        },
        {
          text: '时间',
          value: 'alarmTime',
          width: 180,
          align: 'center'
        }
      ], // 显示列
      tableShow: true, // 是否显示告警列表
      tableIcon: 'el-icon-arrow-up',
      count: 30,
      showWellType: this.showWellType(), // 是否显示闸井类型下拉
      wellTypeList: [], // 闸井类型列表
      deptProps: {
        parent: 'pid',
        value: 'id',
        label: 'name',
        children: 'children'
      }, // 权属单位树形下拉菜单
      deptTreeList: null, // 组织树列表数据
      showDeptTree: 0, // 是否显示权属单位下拉,0不显示，1显示树，2显示平面
      icons: {
        '1': 'well-rain',
        '2': 'well-sewage',
        '3': 'well-gas',
        '4': 'well-heat',
        '5': 'well-power',
        '6': 'well-heat',
        '7': 'well-sewage'
      }, // 井类型图标字典
      otherIcon: 'well-common',
      center: [this.$store.getters.lng, this.$store.getters.lat], // 地图中心
      zoom: 12, // 地图缩放比例
      markers: [], // 井列表标注marker
      alarmList: [], // 报警列表
      alarmWells: [], // 报警闸井列表
      offset: [-10, -10], // 偏移量
      alarmOffset: [-15, -30], // 偏移量
      wellInfo: {
        wellCode: '',
        position: '',
        wellTypeName: '',
        deptName: '',
        bfztName: '',
        deep: ''
      }, // 显示井详细信息气泡内容
      alarmInfo: {
        wellCode: '',
        deptName: '',
        position: '',
        deep: '',
        alarms: []
      }, // 显示报警详情气泡内容
      currentWindow: {
        visible: false, // 窗体显示与否
        position: [this.$store.getters.lng, this.$store.getters.lat],
        windowType: 'info' // 窗体类型：详情info或报警alarm
      }, // 当前窗体属性
      infoWindowClass: 'nomal-info-window',
      deptShowTop: false, // 是否显示顶级
      clock: null, // 计时器
      hasAlarm: false, // 是否有报警,
      showAll: false, // 是否显示全部闸井（包含报警和不报警，为false时只显示报警）
      firstAmount: false, // 是否第一次加载井数据
      loading: true,
      plugins: [{
        pName: 'Geolocation',
        events: {
          init(o) {
            // o 是高德地图定位插件实例
            o.getCurrentPosition((status, result) => {
              if (result && result.position) {
                console.log('geolocation')
                console.log(result)
                self.center = [result.position.lng, result.position.lat]
                self.$nextTick()
              }
            })
          }
        }
      }]
    }
  },
  watch: {
    showAll(val) {
      if (val) { // 显示全部
        this.listQuery.isAlarm = '0'
        if (this.firstAmount === false) { // 如果是第一次，从后台加载全部数据
          this.getWellList()
        } else {
          this.search()
        }
      } else { // 仅显示报警
        this.listQuery.isAlarm = '1'
        this.search()
      }
    }
  },
  created() {
    this.fetchWellType()
    this.getWellList()
    this.refreshAlarm()
    this.countDown()
  },
  methods: {
    // 倒计时
    countDown() {
      this.clock = window.setInterval(() => {
        this.count--
        if (this.count < 0) { // 当倒计时小于0时清除定时器
          this.refreshAlarm()
          this.count = 60
        }
      }, 1000)
    },
    // 获取闸井类型
    fetchWellType() {
      getWellType().then(response => {
        this.wellTypeList = []
        const wellTypes = this.$store.getters.wellTypes
        for (const wellType of response.data) {
          if (wellTypes.indexOf(wellType.value) !== -1) {
            this.wellTypeList.push(wellType)
          }
        }
        if (this.wellTypeList.length <= 1) {
          this.showWellType = false
        }
      })
    },
    // 数据筛选
    search() {
      this.currentWindow.visible = false
      const hideWellIds = []// 要隐藏的井编号
      const keywords = this.listQuery.keywords
      const deptid = this.listQuery.deptid
      const wellType = this.listQuery.wellType
      const isAlarm = this.listQuery.isAlarm
      let center = []
      // 查询全部井，是否匹配
      for (const marker of this.markers) {
        let show = true
        // 关键字不为空，且没有匹配成功，不显示
        if (keywords && keywords !== '' && !(marker.wellCode.indexOf(keywords) !== -1 || marker.positionInfo.indexOf(keywords) !== -1)) {
          show = false
        }
        // 部门不为空， 且没有匹配成功
        if (deptid && deptid !== '' && marker.deptid !== deptid) {
          show = false
        }
        // 井类型不为空，且没有匹配成功
        if (wellType && wellType !== '' && marker.wellType !== wellType) {
          show = false
        }
        // 如果只显示报警,井的状态不是报警
        if (isAlarm === '1' && marker.wellStatus !== 'alarm') {
          show = false
        }
        if (show === false) {
          hideWellIds.push(marker.wellId)
        } else {
          center = marker.position
        }
        marker.visible = show
      }
      // 如果没有找到符合要求的井
      if (hideWellIds.length === this.markers.length) {
        this.$message.warning('查无结果')
        // 将全部查询结果隐藏
        for (const alarmWell of this.alarmWells) {
          alarmWell.visible = false
        }
      } else {
        // 将报警隐藏
        for (const alarmWell of this.alarmWells) {
          if (hideWellIds.indexOf(alarmWell.wellId) > -1) {
            alarmWell.visible = false
          } else {
            alarmWell.visible = true
          }
        }
      }
      if (center.length > 0) {
        this.center = center
      }
    },
    // 获取闸井列表
    getWellList() {
      this.loading = true
      const listQuery = {
        keywords: '', // 关键字
        wellType: '', // 井类型
        deptid: '', // 组织机构
        isAlarm: this.listQuery.isAlarm
      }
      getWellList(listQuery).then(response => {
        this.loading = false
        if (response.code === 200) {
          const wells = response.data
          if (wells.length > 0) {
            // 正在报警的井
            if (listQuery.isAlarm === '1') {
              const centerxs = []
              const centerys = []
              for (const well of wells) {
                this.markers.push({
                  wellId: well.id,
                  wellCode: well.wellCode,
                  position: [parseFloat(well.lngGaode), parseFloat(well.latGaode)],
                  positionInfo: well.position,
                  wellType: well.wellType,
                  deptid: well.deptid,
                  bfzt: well.bfzt,
                  icon: this.icons[well.wellType] ? this.icons[well.wellType] : this.otherIcon,
                  visible: true,
                  wellStatus: 'alarm'
                })
                centerxs.push(parseFloat(well.lngGaode))
                centerys.push(parseFloat(well.latGaode))
              }
              centerxs.sort()
              centerys.sort()
              const index = Math.floor(centerxs.length / 2)
              this.center = [centerxs[index], centerys[index]]
            } else if (listQuery.isAlarm === '0') { // 状态正常的井
              this.firstAmount = false
              const centerxs = []
              const centerys = []
              for (const well of wells) {
                this.markers.push({
                  wellId: well.id,
                  wellCode: well.wellCode,
                  position: [parseFloat(well.lngGaode), parseFloat(well.latGaode)],
                  positionInfo: well.position,
                  wellType: well.wellType,
                  deptid: well.deptid,
                  bfzt: well.bfzt,
                  icon: this.icons[well.wellType] ? this.icons[well.wellType] : this.otherIcon,
                  visible: true,
                  wellStatus: 'normal'
                })
                centerxs.push(parseFloat(well.lngGaode))
                centerys.push(parseFloat(well.latGaode))
              }
              centerxs.sort()
              centerys.sort()
              const index = Math.floor(centerxs.length / 2)
              this.center = [centerxs[index], centerys[index]]
            }
          }
        }
      })
    },
    // 点击闸井详情气泡
    openInfoWindow(wellId) {
      this.currentWindow.visible = false
      getWellInfo(wellId).then(response => {
        if (response.code === 200) {
          const wellInfo = response.data
          this.wellInfo = {
            wellCode: wellInfo.wellCode,
            position: wellInfo.position,
            wellTypeName: wellInfo.wellTypeName,
            deptName: wellInfo.deptName,
            bfztName: wellInfo.bfztName,
            deep: wellInfo.deep
          }
          this.currentWindow.position = [wellInfo.lngGaode, wellInfo.latGaode]
          this.$nextTick(() => {
            this.currentWindow.visible = true
            this.currentWindow.windowType = 'info'
          })
        }
      })
    },
    // 刷新报警列表
    refreshAlarm() {
      console.log('refreshAlarm')
      this.count = 60
      getAlarmsNow().then(response => {
        if (response.code === 200) {
          // 获取当前报警列表
          this.alarmList = response.data
          if (this.alarmList.length > 0) {
            this.hasAlarm = true
          }
          this.alarmWells = []
          for (const alarm of response.data) {
            // 如果报警的井中找到
            // const item = this.alarmWells.findIndex(item => {
            //   return item.wellCode === alarm.wellCode
            // })
            // if (item === -1) {
            this.alarmWells.push({
              wellCode: alarm.wellCode,
              wellId: alarm.wellId,
              position: [alarm.lngGaode, alarm.latGaode],
              positionInfo: alarm.position,
              visible: true
            })
            // }
          }
        }
      })
    },
    // 点击报警详情
    openAlarmWindow(wellId, position) {
      // 旧弹窗不显示
      this.currentWindow.visible = false
      // 清空查询条件
      this.listQuery.keywords = ''
      this.listQuery.wellType = ''
      this.listQuery.deptid = ''
      this.search()
      getWellAlarms(wellId).then(response => {
        if (response.code === 200) {
          const wellInfo = response.data
          this.alarmInfo = {
            wellCode: wellInfo.wellCode,
            position: wellInfo.position,
            deptName: wellInfo.deptName,
            alarms: wellInfo.alarmList,
            deep: wellInfo.deep
          }
          this.currentWindow.position = position
          this.$nextTick(() => {
            this.currentWindow.visible = true
            this.currentWindow.windowType = 'alarm'
          })
        }
      })
    },
    // 点击报警列表
    alarmRowClick(row, column, event) {
      console.log('alarmRowClick')
      const wellId = row.wellId
      for (const alarmWell of this.alarmWells) {
        if (alarmWell.wellId === wellId) {
          this.center = alarmWell.position
          if (this.zoom < 16) {
            this.zoom = 16
          }
          this.openAlarmWindow(alarmWell.wellId, alarmWell.position)
        }
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
// 查询框
.map-search-div{
  position: absolute;
  z-index: 100;
  padding: 5px 20px;
  background-color: rgba(244, 244, 244, 0.9);
  /*left: 90px;*/
  .el-form-item{
    margin-bottom: 0px;
  }
}
// 报警列表
.map-alarm-div{
  position: absolute;
  z-index: 100;
  background-color: rgba(255, 234, 241,0.8);
  top: 60px;
  left: 10px;
  .map-alarm-div-header{
    line-height: 40px;
    width: 504px;
    padding-left: 10px;
    .icon-right{
      position: absolute;
      right: 15px;
    }
    .icon-right:hover{
      color: #409EFF;
      cursor: pointer;
    }
  }
  .el-scrollbar {
    /*height: 200px;*/
    width: 100%;
  }
  .moredatascollor{
    height: 200px;
  }
  .el-scrollbar__wrap {
    overflow-y: auto;
    overflow-x: hidden;
    margin-bottom: 0px !important;
}

.el-table th{
/*background-color: rgba(255, 229, 230, 0.8);*/
    padding: 7px 0px;
  }
  .el-table td{
    /*background-color: rgba(255, 234, 241, 0.8);*/
    padding: 5px 0px;
    /*line-height: 1;*/
  }
  .el-table td:hover{
    /*background-color: rgba(255, 234, 241, 0.8);*/
  }
  .transition-box {
    margin-bottom: 10px;
    width: 200px;
    height: 100px;
    border-radius: 4px;
    background-color: #409EFF;
    text-align: center;
    color: #fff;
    padding: 40px 20px;
    box-sizing: border-box;
    margin-right: 20px;
  }
}
// 刷新框
.refresh-div{
  position: absolute;
  right: 10px;
  top: 7px;
  z-index: 100;
  padding: 10px;
  color: #ce8b74;
  font-size: 14px;
  background-color: rgba(244, 233, 230, 1.0);
  .font-red{
    color: red;
    font-weight: bold;
  }
  .el-icon-refresh:hover{
    color: red;
    font-weight: bold;
    cursor: pointer;
  }
}
// 地图
.overview-map-container{
  width: 100%;
  padding: 5px;
  .map-demo{
    width: 100%;
    height: calc(100vh - 78px);
    .svg-icon{
      width: 20px;
      height: 20px;
    }
    .alarm-icon{
      width:30px;
      height: 30px;
    }
    .nomal-info-window{
      background-color: pink;
    }
    .info-window{
      max-width: 250px;
      /*background-color: lightcyan;*/
      .info-header{
        padding: 10px 10px 5px 10px;
        line-height: 30px;
        font-weight: bold;
        /*background-color: #eaf4ff;*/
      }
      .info-body{
        padding: 5px 10px 10px 10px;
        line-height: 23px;
        font-size: 14px;
      }
    }
    .alarm-window{
      max-width: 250px;
      /*background-color: #ffeaf1;*/
      .alarm-header {
        padding: 10px 10px 5px 10px;
        line-height: 30px;
        color: red;
        font-weight: bold;
        /*background-color: #ffecec;*/
      }
      .alarm-body{
        padding: 5px 10px 10px 10px;
        line-height: 23px;
        font-size: 14px;
        .alarm-red{
          color: #ff0000;
        }
      }
    }
  }
}
  .el-divider--horizontal{
    margin: 5px 0;
  }
</style>
