<template>
  <div>
    <div id="echartsMaps" class="echartsMaps"/>
  </div>
</template>

<script>
  // import geoJson from '@/assets/allChinaMap/anHuiMap/anhui.json'
  import geoJson from '@/assets/allChinaMap/neimengMap/city/tongliao.json'
  import map from '@/assets/allChinaMap/neimengMap/cityMap.js'
  import tomap from '@/assets/allChinaMap/neimengMap/cityToneimeng.js'
  import {fetchList as fetchElectricfieldList,homgpageAll,getServerTime} from "@/api/electricfield";
  import {homgpageAllWindTurbineInfo} from '@/api/windturbineinfo'

  export default {
    name: "echartsMaps",
    data() {
      return {
        electricfieldList: [],
        windInfo: [],
        timer: null
      }
    },
    destroyed() {
      clearInterval(this.timer)
      this.timer = null
    },
    mounted() {
      this.init()
      // this.timer = setInterval(this.getAllWindInfo,1000 * 60 * 10)
    },
    methods: {
      init() {
        fetchElectricfieldList().then(res => {
          this.electricfieldList = res.data.data.records
          this.homgpageAll()
        }).catch(e=>{
          console.log('地图获取场站信息异常：+'+e)
        })
      },
      // 风机信息
      homgpageAll() {
        homgpageAllWindTurbineInfo().then(res => {
          // console.log(res.data.data)
          this.windInfo = res.data.data
          this.createMap(this.windInfo)
        }).catch(e=>{
          console.log('地图获取风机信息异常：+'+e)
        })



        // homgpageAll().then(res => {
        //   // console.log(res.data.data)
        //   this.windInfo = res.data.data
        //   this.createMap(this.windInfo)
        // }).catch(e=>{
        //   console.log('地图获取风机信息异常：+'+e)
        // })
      },
      createMap(data) { /*, symbol*/

        var _this = this
        const _self = this
        let chart = null
        this.$echarts.extendsMap = function (id, opt) {
          // 实例
          chart = this.init(document.getElementById(id))
          let cityMap = map.cityMap
          let defaultOpt = {
            mapName: 'neimenggu', // 地图展示
            goDown: true, // 是否下钻
            bgColor: '#404a59', // 画布背景色
            activeArea: [], // 区域高亮,同echarts配置项
            data: [],
            // 下钻回调(点击的地图名、实例对象option、实例对象)
            callback: function (name, option, instance) {
            }
          }
          if (opt) opt = this.util.extend(defaultOpt, opt)

          // 层级索引
          let name = [opt.mapName]
          let idx = 0
          let pos = { //箭头的位置
            leftPlus: 33,
            leftCur: 33,
            left: 10,
            top: 20
          }
          let line = [[0, 0], [8, 11], [0, 22]]// 层级箭头
          // style
          let style = {
            font: '18px "Microsoft YaHei", sans-serif',
            textColor: '#eee',
            lineColor: 'rgba(147, 235, 248, .8)'
          }
          let length = 105
          let handleEvents = {
            /**
             * i 实例对象
             * o option
             * n 地图名
             **/
            resetOption: function (i, o, n) {
              let breadcrumb = this.createBreadcrumb(n)
              let j = name.indexOf(n)
              let l = o.graphic.length
              if (j < 0) {
                o.graphic.push(breadcrumb)
                // o.graphic[0].children[0].shape.x2 = 85
                // o.graphic[0].children[1].shape.x2 = 85

                name.push(n)
                idx++
              } else {
                o.graphic.splice(j + 2, l)
                if (o.graphic.length <= 2) {
                  o.graphic[0].children[0].shape.x2 = 45
                  o.graphic[0].children[1].shape.x2 = 45
                  let series = handleEvents.setSerise()
                  o.series.data = handleEvents.initSeriesData(series)
                }

                name.splice(j + 1, l)
                idx = j
                pos.leftCur -= pos.leftPlus * .5
              }
              o.geo.map = n
              o.geo.zoom = 1.5
              i.clear()// 清除上一个实例
              i.setOption(o)
              this.zoomAnimation()
              opt.callback(n, o, i)
              length += 40
            },

            changeStationCode: function(stationCode){
              _this.$emit("stationCode",stationCode)
            },

            /**
             * name 地图名
             **/
            createBreadcrumb: function (name) {
              let cityToMap = tomap.cityToMap
              let breadcrumb = {
                type: 'group',
                id: name,
                left: pos.leftCur + pos.leftPlus,
                top: pos.top + 3,
                children: [{
                  type: 'polyline',
                  left: 20,
                  top: -5,
                  shape: {
                    points: [[3, 0], [11, 11], [3, 22]]
                  },
                  style: {
                    stroke: '#fff',
                    key: name
                  },
                  onclick: function () {
                    let name = this.style.key
                    handleEvents.resetOption(chart, option, name)
                  }
                }, {
                  type: 'text',
                  left: 40,
                  top: 'middle',
                  style: {
                    text: name,
                    textAlign: 'center',
                    fill: style.textColor,
                    font: style.font
                  },
                  onclick: function () {
                    let name = this.style.text
                    handleEvents.resetOption(chart, option, name)
                  }
                }, {
                  type: 'text',
                  left: 40,
                  top: 10,
                  style: {

                    name: name,
                    text: cityToMap[name] ? cityToMap[name].toUpperCase() : '',
                    textAlign: 'center',
                    fill: style.textColor,
                    font: '12px "Microsoft YaHei", sans-serif'
                  },
                  onclick: function () {
                    let name = this.style.name
                    handleEvents.resetOption(chart, option, name)
                  }
                }
                ]
              }
              // pos.leftCur >= 122.5 ||
              if (name === '通辽市') {
                pos.leftCur = 53
              } else {
                if (name.length >= 4) {
                  pos.leftCur += pos.leftPlus * 4
                } else {
                  pos.leftCur += pos.leftPlus * 2.5
                }
              }
              return breadcrumb
            },

            // 设置effectscatter，气泡标志
            initSeriesData: function (data) {
              let temp = []
              for (let i = 0; i < data.length; i++) {
                let geoCoord = [data[i].longitude, data[i].latitude]
                if (geoCoord) {
                  if (data[i].type === 'ElectricField') {
                    // 场站
                    temp.push({
                      // id: data[i].name,
                      name: data[i].name,
                      record: data[i],
                      // value: geoCoord.concat(data[i].name)
                      value: geoCoord,
                      type: 'scatter', // series图表类型effectScatter
                      coordinateSystem: 'geo', // series坐标系类型
                      symbol: 'image://img/changzhan.png', // pin气泡，diamond菱形,scatter点，在这里引用svg路径，就可以自定义动图
                      showEffectOn: 'render',
                      symbolSize: 35,
                      hoverAnimation: true,
                      itemStyle: {
                        normal: {// 改用svg模式后normal不生效，字体大小被放大一般情况下字体给显示并且透明色transparent,鼠标经过显示白色

                          shadowBlur: 10,
                          shadowColor: '#333'
                        }
                      },
                    })
                  } else {
                    // 风机
                    temp.push({
                      // id: data[i].name,
                      name: data[i].name,
                      electricField: data[i].electricField,
                      record: data[i],
                      // value: geoCoord.concat(data[i].name)
                      value: geoCoord,
                      type: 'scatter', // series图表类型effectScatter
                      coordinateSystem: 'geo', // series坐标系类型
                      symbol: 'image://img/fengdianzhan.png', // pin气泡，diamond菱形,scatter点，在这里引用svg路径，就可以自定义动图
                      showEffectOn: 'render',
                      symbolSize: 35,
                      hoverAnimation: true,
                      itemStyle: {
                        normal: {// 改用svg模式后normal不生效，字体大小被放大一般情况下字体给显示并且透明色transparent,鼠标经过显示白色

                          shadowBlur: 10,
                          shadowColor: '#333'
                        }
                      },
                    })
                  }
                }
              }
              return temp
            },
            // 缩放动画
            zoomAnimation: function () {
              let count = null
              let zoom = function (per) {
                if (!count) count = per
                count = count + per
                chart.setOption({
                  geo: {
                    zoom: 1.2
                  }
                })
                if (count < 1) {
                  window.requestAnimationFrame(function () {
                    zoom(.7)
                  })
                }
              }
              window.requestAnimationFrame(function () {
                zoom(.7)
              })
            },
            /* 动态设置图标*/
            setSerise: function () {
              let temp = []
              for (let i = 0; i < opt.data.length; i++) {
                let arr = []
                arr.push(opt.data[i])
                if (opt.data[i].type === 'ElectricField') {
                  temp.push({
                    type: 'scatter', // series图表类型effectScatter
                    coordinateSystem: 'geo', // series坐标系类型
                    symbol: 'image://img/changzhan.png', // pin气泡，diamond菱形,scatter点，在这里引用svg路径，就可以自定义动图
                    showEffectOn: 'render',
                    symbolSize: 35,
                    hoverAnimation: true,
                    itemStyle: {
                      normal: {// 改用svg模式后normal不生效，字体大小被放大一般情况下字体给显示并且透明色transparent,鼠标经过显示白色

                        shadowBlur: 10,
                        shadowColor: '#333'
                      }
                    },
                    data: handleEvents.initSeriesData(arr)
                  })
                } else {
                  temp.push({
                    type: 'scatter', // series图表类型effectScatter
                    coordinateSystem: 'geo', // series坐标系类型
                    symbol: 'image://img/fengdianzhan.png', // pin气泡，diamond菱形,scatter点，在这里引用svg路径，就可以自定义动图
                    showEffectOn: 'render',
                    symbolSize: 35,
                    hoverAnimation: true,
                    itemStyle: {
                      normal: {// 改用svg模式后normal不生效，字体大小被放大一般情况下字体给显示并且透明色transparent,鼠标经过显示白色

                        shadowBlur: 10,
                        shadowColor: '#333'
                      }
                    },
                    data: handleEvents.initSeriesData(arr)
                  })
                }

              }
              return temp
            }
          }

          /* 初始化图标*/
          let series = handleEvents.setSerise()
          let option = {
            backgroundColor: opt.bgColor,
            tooltip: {
              trigger: 'item',
              // position: ['50%', '30%'],
              formatter: function (params) {
                let name = ''
                let newInfo = ''
                if (params.data.record.type === 'ElectricField') {
                  const electricfield = _self.electricfieldList.find(w => w.stationCode === params.name)
                  name = electricfield !== undefined ? electricfield.name : params.name
                  newInfo = '场站名称：' + name + '<br/>场站标识：' + params.data.record.sign + '<br/>场站类型：' + params.data.record.electricFieldTypeEnum + '<br/>装机容量：' + params.data.record.capacity + 'MW<br/>经度：' + params.value[0] + '<br/>纬度：' + params.value[1] + '<br/>'
                } else {
                  const electricfield = _self.electricfieldList.find(w => w.stationCode === params.data.electricField)
                  name = electricfield !== undefined ? electricfield.name : params.data.electricField
                  newInfo = '所属场站：' + name + '<br/>设备名称：' + params.name + '<br/>经度：' + params.value[0] + '<br/>纬度：' + params.value[1] + '<br/>'
                }
                return newInfo
              },

            },
            graphic: [{
              type: 'group',
              left: pos.left,
              top: pos.top - 4,
              children: [{
                type: 'line',
                left: 0,
                top: -20,
                shape: {
                  x1: 0,
                  y1: 0,
                  x2: 45,
                  y2: 0
                },
                style: {
                  stroke: style.lineColor
                }
              }, {
                type: 'line',
                left: 0,
                top: 20,
                shape: {
                  x1: 0,
                  y1: 0,
                  x2: 45,
                  y2: 0
                },
                style: {
                  stroke: style.lineColor
                }
              }
              ]
            },
              {
                id: name[idx],
                type: 'group',
                left: pos.left + 2,
                top: pos.top,
                children: [{
                  type: 'polyline',
                  left: 110,
                  top: -12,
                  shape: {
                    points: line
                  },
                  style: {
                    stroke: 'transparent',
                    key: name[0]
                  },
                  // onclick: function () {
                  //   let name = this.style.key
                  //   handleEvents.resetOption(chart, option, name)
                  // }
                }, {
                  type: 'text',
                  left: 0,
                  top: 'middle',
                  style: {
                    text: name[0],
                    textAlign: 'center',
                    fill: style.textColor,
                    font: style.font
                  },
                  onclick: function () {
                    handleEvents.resetOption(chart, option, '通辽市')
                  }
                }, {
                  type: 'text',
                  left: 0,
                  top: 10,
                  style: {
                    text: 'NeiMengGu',
                    textAlign: 'center',
                    fill: style.textColor,
                    font: '12px "Microsoft YaHei", sans-serif'
                  },
                  onclick: function () {
                    handleEvents.resetOption(chart, option, '通辽市')
                  }
                }]
              }],
            geo: {
              top: '22%',
              map: opt.mapName,
              roam: true, // 可缩放
              zoom: 1.2,
              label: {
                normal: {
                  show: true,
                  textStyle: {
                    color: '#fff'
                  }
                },
                emphasis: {
                  textStyle: {
                    color: '#fff'
                  }
                }
              },
              itemStyle: {
                normal: {
                  borderColor: 'rgba(147, 235, 248, 1)',
                  borderWidth: 1,
                  areaColor: {
                    type: 'radial',
                    x: 0.5,
                    y: 0.5,
                    r: 0.8,
                    colorStops: [{
                      offset: 0,
                      color: 'rgba(147, 235, 248, 0)' // 0% 处的颜色
                    }, {
                      offset: 1,
                      color: 'rgba(147, 235, 248, .2)' // 100% 处的颜色
                    }],
                    globalCoord: false // 缺省为 false
                  },
                  shadowColor: 'rgba(128, 217, 248, 1)',
                  // shadowColor: 'rgba(255, 255, 255, 1)',
                  shadowOffsetX: -2,
                  shadowOffsetY: 2,
                  shadowBlur: 10
                },
                emphasis: {
                  areaColor: '#389BB7',
                  borderWidth: 0
                }
              },
              regions: opt.activeArea.map(function (item) {
                if (typeof item !== 'string') {
                  return {
                    name: item.name,
                    itemStyle: {
                      normal: {
                        areaColor: item.areaColor || '#389BB7'
                      }
                    },
                    label: {
                      normal: {
                        show: item.showLabel,
                        textStyle: {
                          color: '#fff'
                        }
                      }
                    }
                  }
                } else {
                  return {
                    name: item,
                    itemStyle: {
                      normal: {
                        borderColor: '#91e6ff',
                        areaColor: '#389BB7'
                      }
                    }
                  }
                }
              })
            },
            series: series
          }

          chart.setOption(option)
          // 添加事件
          chart.on('click', function (params) {
            // 增加与父折线图点击事件的条件，只有是场站类型的才可以联动
            if(params.data != undefined && params.data.record.type =="ElectricField" ){
              handleEvents.changeStationCode(params.data.record.stationCode)
            }
            // 此版本系统点击地名的下钻事件已关闭
            // const _this = this
            // if (opt.goDown && params.name !== name[idx]) {
            //   if (cityMap[params.name]) {
            //     let url = cityMap[params.name]
            //     _self.$echarts.registerMap(params.name, url)
            //     handleEvents.resetOption(_this, option, params.name)
            //   }
            // }
          })
          return chart
        }

        this.$echarts.registerMap('通辽市', geoJson)
        let myChart = this.$echarts.extendsMap('echartsMaps', {
          bgColor: '', // 画布背景色
          mapName: '通辽市', // 地图名
          goDown: true, // 是否下钻
          // 下钻回调
          callback: function (name, option, instance) {

          },
          data: data
        })
        window.addEventListener('resize', () => {
          if (chart) {
            chart.resize()
          }
        })
      }
    }
  }
</script>

<style scoped>
  #echartsMaps {
    width: 100%;
    margin-left: .5%;
    height: calc(88vh)
  }

  .mapTitleBox {
    height: calc(4vh);
    display: flex;
    justify-content: space-around;
  }

  .mapTitle {
    width: 10%;
    color: white;
  }

  .mapTitle /deep/ .border-box-content {
    display: flex;
    justify-content: center;
    align-items: center;
  }

</style>
