<template>
  <div class="centermap">
    <div class="mapwrap" v-if="pageflag">
      <dv-border-box-12>
        <div class="loading" v-if="loading"><a-spin /></div>
        <div class="quanguo" @click="getData('china')" v-if="code !== 'china'">
          返回
        </div>
        <Echart id="CenterMap" :options="options" ref="CenterMap" />
      </dv-border-box-12>
    </div>
    <Reacquire v-else @onclick="getData('china')" style="line-height:200px" />
  </div>
</template>

<script>
import xzqCode from '@/utils/map/xzqCode'
import * as echarts from 'echarts'
import { GETNOBASE } from '@/utils/request'
import { queryMapSaleData } from '@/api/bigScreen.js'
import getDate from '@/libs/getDate.js'
export default {
  props: {
    curYear: {
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      options: {},
      code: 'china', // china 代表中国 其他地市是行政编码
      echartBindClick: false,
      isSouthChinaSea: false, // 是否要展示南海群岛  修改此值请刷新页面
      pageflag: true,
      timer: null,
      loading: false
    }
  },
  watch:{
    curYear (a,b){
      this.getData('china')
    }
  },
  mounted () {
    this.getData('china')
  },
  beforeDestroy () {
    this.clearData()
  },
  methods: {
    clearData () {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    // 轮询
    switper () {
      if (this.timer) {
        return
      }
      const looper = (a) => {
        this.getData('china')
      }
      this.timer = setInterval(looper, 30000)
    },
    getData (code) {
      this.loading = !this.timer
      queryMapSaleData(getDate.getBeDateByYear(this.curYear)).then((res) => {
        console.log('地图', res)
        if (res.status == 200) {
          this.getGeojson('china', res.data.dataList)
          // this.mapclick()
          this.$emit('onData', res.data)
          this.switper()
        } else {
          this.$Message.warning(res.msg)
        }
        this.loading = false
      })
    },
    /**
     * @description: 获取geojson
     * @param {*} name china 表示中国 其他省份行政区编码
     * @param {*} mydata 接口返回列表数据
     * @return {*}
     */
    async getGeojson (name, mydata) {
      this.code = name
      // 如果要展示南海群岛并且展示的是中国的话
      let geoname = name
      if (this.isSouthChinaSea && name == 'china') {
        geoname = 'chinaNanhai'
      }
      // 如果有注册地图的话就不用再注册 了
      let mapjson = echarts.getMap(name)
      if (mapjson) {
        mapjson = mapjson.geoJSON
      } else {
        mapjson = await GETNOBASE(`../../map-geojson/${geoname}.json`).then((res) => {
          return res
        })
        echarts.registerMap(name, mapjson)
      }
      const cityCenter = {}
      const arr = mapjson.features
      console.log(mapjson)
      // 根据geojson获取省份中心点
      arr.map((item) => {
        cityCenter[item.properties.name] =
          item.properties.centroid || item.properties.center
      })
      const newData = []
      const retData = []
      mydata.map((item) => {
        if (cityCenter[item.provinceName]) {
          newData.push({
            name: item.provinceName,
            value: cityCenter[item.provinceName].concat(item.resultAmount)
          })
        }
        retData.push({
          name: item.provinceName,
          value: item.resultAmount
        })
      })
      this.init(name, retData, newData)
    },
    init (name, data, data2) {
      // console.log(data2);
      const top = 45
      const zoom = 1.05
      const option = {
        backgroundColor: 'rgba(0,0,0,0)',
        tooltip: {
          show: false
        },
        legend: {
          show: false
        },
        visualMap: {
          left: 20,
          bottom: 20,
          pieces: [
            { gte: 10000000, label: '1000万元以上' }, // 不指定 max，表示 max 为无限大（Infinity）。
            { gte: 5000000, lte: 9999999, label: '500万元-1000万元' },
            { gte: 1000000, lte: 4999999, label: '100万元-500万元' },
            { gte: 500000, lte: 999999, label: '50万元-100万元' },
            { gte: 100000, lte: 499999, label: '10万元-50万元' },
            { lte: 99999, label: '1-10万元' } // 不指定 min，表示 min 为无限大（-Infinity）。
          ],
          inRange: {
            // 渐变颜色，从小到大
            color: [
              '#255a7e',
              '#3483b4',
              '#43a9e8',
              '#0389ff',
              '#ffaa00',
              '#ff5500'
            ]
          },
          textStyle: {
            color: '#fff'
          }
        },
        geo: {
          map: name,
          roam: false,
          selectedMode: false, // 是否允许选中多个区域
          zoom: zoom,
          top: top,
          // aspectScale: 0.78,
          show: false
        },
        series: [
          {
            name: 'MAP',
            type: 'map',
            map: name,
            // aspectScale: 0.78,
            data: data,
            selectedMode: false, // 是否允许选中多个区域
            zoom: zoom,
            geoIndex: 1,
            top: top,
            tooltip: {
              show: true,
              formatter: function (params) {
                if (params.data) {
                  return params.name + '：' + (params.data['value'] / 10000).toFixed(2) + '万元'
                } else {
                  return params.name
                }
              },
              backgroundColor: 'rgba(0,0,0,.6)',
              borderColor: 'rgba(147, 235, 248, .8)',
              textStyle: {
                color: '#FFF'
              }
            },
            label: {
              show: false,
              color: '#000',
              formatter: function (val) {
                // console.log(val)
                if (val.data !== undefined) {
                  return val.name.slice(0, 2)
                } else {
                  return ''
                }
              },
              rich: {}
            },
            emphasis: {
              label: {
                show: false
              },
              itemStyle: {
                areaColor: '#389BB7',
                borderWidth: 1
              }
            },
            itemStyle: {
              borderColor: 'rgba(147, 235, 248, .8)',
              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, .3)',
              shadowOffsetX: -2,
              shadowOffsetY: 2,
              shadowBlur: 10
            }
          },
          {
            data: data2,
            type: 'effectScatter',
            coordinateSystem: 'geo',
            symbolSize: function (val) {
              return 4
            },
            legendHoverLink: true,
            showEffectOn: 'render',
            rippleEffect: {
              // period: 4,
              scale: 6,
              color: 'rgba(255,255,255, 1)',
              brushType: 'fill'
            },
            tooltip: {
              show: true,
              formatter: function (params) {
                if (params.data) {
                  return params.name + '：' + params.data['value'][2]
                } else {
                  return params.name
                }
              },
              backgroundColor: 'rgba(0,0,0,.6)',
              borderColor: 'rgba(147, 235, 248, .8)',
              textStyle: {
                color: '#FFF'
              }
            },
            label: {
              formatter: (param) => {
                return param.name.slice(0, 2)
              },

              fontSize: 11,
              offset: [0, 2],
              position: 'bottom',
              textBorderColor: '#fff',
              textShadowColor: '#000',
              textShadowBlur: 10,
              textBorderWidth: 0,
              color: '#FFF',
              show: true
            },
            // colorBy: "data",
            itemStyle: {
              color: 'rgba(255,255,255,1)',
              borderColor: 'rgba(2255,255,255,2)',
              borderWidth: 4,
              shadowColor: '#000',
              shadowBlur: 10
            }
          }
        ]
        // 动画效果
        // animationDuration: 1000,
        // animationEasing: 'linear',
        // animationDurationUpdate: 1000
      }
      this.options = option
    },
    mapclick () {
      if (this.echartBindClick) return
      // 单击切换到级地图，当mapCode有值,说明可以切换到下级地图
      this.$refs.CenterMap.chart.on('click', (params) => {
        // console.log(params);
        const xzqData = xzqCode[params.name]
        if (xzqData) {
          this.getData(xzqData.adcode)
        } else {
          this.$message.info('暂无下级地市!')
        }
      })
      this.echartBindClick = true
    }
  }
}
</script>
<style lang="less" scoped>
.centermap {
  .mapwrap {
    height: 508px;
    width: 100%;
    // padding: 0 0 10px 0;
    box-sizing: border-box;
    position: relative;

    .quanguo {
      position: absolute;
      right: 20px;
      top: 15px;
      width: 80px;
      height: 28px;
      border: 1px solid #00aaff;
      border-radius: 10px;
      color: #00aaff;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5), 0 0 6px rgba(0, 237, 237, 0.4);
		  z-index: 10000;
    }
    .loading{
      position:absolute;
      z-index: 1000;
      left:0;
      top:0;
      width:100%;
      height:100%;
      background:rgba(0,0,0,0.5);
      display:flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
