<template>
  <div class="dashboard-container">
    <!-- <el-button v-for="mine in mineList" :key="'type='+mine.mineType+',id='+mine.id" @click="cilckMine(mine)">{{ mine.name }}</el-button> -->
    <!-- <span style="color: red;font-size: 10px;">* 添加矿山时需要填写定位，否则无法在地图展示</span> -->
    <div id="amap_search_point_container" style="height: calc(100vh - 50px);" :style="{padding: 0,margin: 0,width: '100%'}" />
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import mineApi from '@/api/kd/mine'
import { mapGetters } from 'vuex'

export default {
  name: 'Home4Enterprise',
  components: { },
  data() {
    return {
      mineList: []
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  mounted() {
    if (this.user.enterpriseId === 0) { // 身份错误
      this.$router.replace('/dashboard')
      return
    }
    // 移除当前矿山信息
    const selectedMineJson = window.localStorage.getItem('kd.selected.mine')
    if (selectedMineJson) {
      window.localStorage.removeItem('kd.selected.mine')
      window.location.reload()
    }
    // 加载全部矿山信息
    mineApi.getAllMine().then(response => {
      this.mineList = response.results
      // 获取到矿山信息之后，再加载地图
      this.initMap()
    }).catch(() => {
      this.$message.error('加载矿山信息失败，请稍后刷新再试')
    })
  },
  methods: {
    initMap() {
      AMapLoader.load({
        key: 'a0efee399e638b35211705625d786e83',
        version: '2.0',
        plugins: []
      }).then((AMap) => {
        this.AMap = AMap
        // 加载地图
        let center = [119.969873, 36.753901] // 平度市
        if(this.mineList && this.mineList[0] && this.mineList[0].longitude && this.mineList[0].latitude){
          center = [this.mineList[0].longitude, this.mineList[0].latitude]
        }
        if (this.defaultPoint && this.defaultPoint.length === 2) {
          center = this.defaultPoint
        }
        this.map = new this.AMap.Map('amap_search_point_container', {
          resizeEnable: true,
          center: center,
          layers: [new AMap.TileLayer.Satellite()],
          zoom: 10
        })
        if (this.mineList) {
          this.mineList.forEach(mine => {
            if (mine.latitude && mine.longitude) {
              // 标点、悬浮窗、点击标点展示悬浮窗事件绑定、显示标点
              const mapMarker = new this.AMap.Marker({
                position: new this.AMap.LngLat(mine.longitude * 1, mine.latitude * 1)
              })
              let infoWindowContent = ''
              infoWindowContent += '矿山名称：' + mine.name
              if (mine.code) {
                infoWindowContent += '<br>矿山编号：' + mine.code
              }
              if (mine.address) {
                infoWindowContent += '<br>矿山地址：' + mine.address
              }
              if (mine.liablePerson) {
                infoWindowContent += '<br>主要负责人：' + mine.liablePerson
              }
              if (mine.liablePersonPhone) {
                infoWindowContent += '<br>联系方式：' + mine.liablePersonPhone
              }
              if (mine.mineType) {
                infoWindowContent += '<br>运行状态：' + (mine.mineType === 1 ? '基建' : mine.mineType === 2 ? '停建' : mine.mineType === 3 ? '生产' : mine.mineType === 4 ? '停产' : '')
              }
              const infoWindow = new AMap.InfoWindow({
                content: '<div style="min-width:300px;margin:10px;">' + infoWindowContent + '<div style="display:flex;justify-content:space-around;color:#409EFF;margin-top:10px;"><a href="javaScript:void(0);" id="showDatav' + mine.id + '">数据总览</a><a href="javaScript:void(0);" id="showManage' + mine.id + '">信息管理</a></div></div>',
                offset: new AMap.Pixel(0, -30)
              })
              mapMarker.on('click', () => {
                infoWindow.open(this.map, mapMarker.getPosition())
                setTimeout(() => { // 等待半秒，让dom充分渲染，再为dom绑定事件
                  const showDatavDom = document.getElementById('showDatav' + mine.id)
                  if (showDatavDom) {
                    showDatavDom.onclick = () => {
                      // 用于跳回到矿山首页
                      window.localStorage.setItem('kd.selected.mine', JSON.stringify(mine))
                      window.localStorage.setItem('kd.mine.home.need.reload', true)
                      if (mine.mineType === 1) { // 地下矿山
                        window.open(location.protocol + '//' + window.location.host + '/datav/underground.html', '_self')
                      } else if (mine.mineType === 2) { // 露天矿山
                        window.open(location.protocol + '//' + window.location.host + '/datav/open-air.html', '_self')
                      } else if (mine.mineType === 3) { // 尾矿库
                        window.open(location.protocol + '//' + window.location.host + '/datav/tailings.html', '_self')
                      } else {
                        this.$message.error('无法查看数据总览')
                      }
                    }
                  }
                  const showManageDom = document.getElementById('showManage' + mine.id)
                  if (showManageDom) {
                    showManageDom.onclick = () => {
                      this.cilckMine(mine)
                    }
                  }
                }, 500)
              })
              this.map.add(mapMarker)
            }
          })
        }
      }).catch(e => {
        this.$message.error('首页加载失败，请刷新重试')
        console.error(e)
      })
    },
    cilckMine(mine) {
      if (mine) { // 跳转至矿山首页，并强制刷新页面
        window.localStorage.setItem('kd.selected.mine', JSON.stringify(mine))
        window.localStorage.setItem('kd.mine.home.need.reload', true)
        const x = this.$router.resolve('/home4Mine')
        window.open(x.href, '_self')
      } else {
        alert(mine)
        window.localStorage.removeItem('kd.selected.mine')
      }
      // window.location.reload()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .dashboard-container {
    background-color: rgb(240, 242, 245);
    position: relative;
    height: calc(100vh - 50px);
  }
</style>
