<template>
  <div :class="$style.mapBox">
    <div
      id="map"
      style="position: relative; width: 100%; height: 1200px; padding: 0; margin: 0; cursor: default; border-width: 0;"
    >
    </div>
    <div id="map1">
      <span
        ref="clickSpan"
        style="position: absolute; top: 105px; right: 90px;font-size:14px;font-weight:bold;color:#00C;text-decoration: underline; cursor: pointer;"
        >查看审计覆盖情况</span
      >
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import axios from '@/common/services/axios-instance'
import 'echarts/lib/chart/map'
import 'echarts/map/js/china.js'
import 'echarts/map/js/world.js'
import worldjson from './new/world.json'
import geoCoordMap from './world.json'
import china from 'echarts/map/json/china.json'
import world from 'echarts/map/json/world.json'
import chinaGeoCoordMap from './chinamap.json'
import MapService from './map-service.js'
import components from './_import-components/xm-audit-chinamap-import'
import { getUserInfo } from '@/common/store-mixin'
function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  var result = []
  var prevX = encodeOffsets[0]
  var prevY = encodeOffsets[1]
  for (var i = 0; i < coordinate.length; i += 2) {
    var x = coordinate.charCodeAt(i) - 64
    var y = coordinate.charCodeAt(i + 1) - 64
    // ZigZag decoding
    x = (x >> 1) ^ -(x & 1)
    y = (y >> 1) ^ -(y & 1)
    // Delta deocding
    x += prevX
    y += prevY
    prevX = x
    prevY = y
    // Dequantize
    result.push([x / encodeScale, y / encodeScale])
  }
  return result
}
function decode(json) {
  if (!json.UTF8Encoding) {
    return json
  }
  var encodeScale = json.UTF8Scale
  if (encodeScale == null) {
    encodeScale = 1024
  }
  var features = json.features
  for (var f = 0; f < features.length; f++) {
    var feature = features[f]
    var geometry = feature.geometry
    var coordinates = geometry.coordinates
    var encodeOffsets = geometry.encodeOffsets
    for (var c = 0; c < coordinates.length; c++) {
      var coordinate = coordinates[c]
      if (geometry.type === 'Polygon') {
        coordinates[c] = decodePolygon(coordinate, encodeOffsets[c], encodeScale)
      } else if (geometry.type === 'MultiPolygon') {
        for (var c2 = 0; c2 < coordinate.length; c2++) {
          var polygon = coordinate[c2]
          coordinate[c2] = decodePolygon(polygon, encodeOffsets[c][c2], encodeScale)
        }
      }
    }
  }
  // Has been decoded
  json.UTF8Encoding = false
  return json
}

function fnshowdiv(id) {
  console.log('---1')
}

function fngetcolor(content) {
  let color = 'green' // 审计已有1年的单位
  if (content === '当年已审计') {
    // color = 'red' // 未覆盖的单位
    color = 'green'
  } else if (content === '1年未审计') {
    // color = 'green' // 审计已有1年的单位
    color = 'blue'
  } else if (content === '2年未审计') {
    // color = 'blue' // 审计已有2年的单位
    color = '#EEEE00'
  } else if (content === '3年未审计') {
    // color = '#EEEE00' // 审计已有2年的单位
    color = '#FFA500'
  } else if (content === '3年及以上未审计') {
    color = 'red'
  } else if (content === '4年及以上未审计') {
    // color = '#FFA500' // 审计已有4年的单位
    color = 'red'
  }
  return color
}
window.fnshowdiv = fnshowdiv
window.fngetcolor = fngetcolor
export default {
  name: 'XmAuditChinamap',
  metaInfo: {
    title: '审计地图',
  },
  data() {
    return {
      dataList: [],
    }
  },
  mounted() {
    //    初始化地图
    this.getList()
    this.$refs.clickSpan.addEventListener('click', this.handleClick)
  },
  methods: {
    handleClick() {
      // 处理点击事件
      const now = new Date()
      const year = now.getFullYear()
      const param = {}
      param.type = 'gn'
      param.name = '境内'
      window.open(
        '#/xm-audit-mapcoverage-list?params=' +
          encodeURIComponent(JSON.stringify(param)) +
          '&year=' +
          year
      )
      // window.open('#/xm-audit-mapcoverage-list?type=fourYearCoverage' + '&year=' + year)
    },
    getList() {
      MapService.getChinaData().then((res) => {
        // console.log(res)
        this.dataList = res.data
        this.initEchart()
      })
    },
    convertData(data, type) {
      // debugger
      var res = []
      for (var i = 0; i < data.length; i++) {
        // var geoCoord = chinaGeoCoordMap[data[i].name]
        var geoCoord = ''
        var name = ''
        if (data[i].name) {
          var list = chinaGeoCoordMap
          for (const key in list) {
            if (data[i].name.indexOf(key) !== -1) {
              name = key
              geoCoord = chinaGeoCoordMap[key]
              break
            }
          }
        }
        if (geoCoord) {
          if (type === data[i].type) {
            res.push({
              // name: data[i].name,
              name: name,
              value: geoCoord.concat(data[i].value),
              type: geoCoord.concat(data[i].type),
            })
          }
        }
        geoCoord = geoCoordMap.mapregion[data[i].name]
        if (geoCoord) {
          if (type === data[i].type) {
            res.push({
              name: data[i].name,
              value: geoCoord.concat(data[i].value),
              type: geoCoord.concat(data[i].type),
            })
          }
        }
      }
      return res
    },
    // getList(sort) {
    //   var obj = {
    initEchart() {
      const data = decode(china) // 这里调用的函数就是上面解密的函数
      const gj = [
        '北京',
        '上海',
        '四川',
        '黑龙江',
        '吉林',
        '辽宁',
        '天津',
        '内蒙古',
        '河北',
        '山东',
        '江苏',
        '浙江',
        '福建',
        '台湾',
        '香港',
        '广东',
        '澳门',
        '海南',
        '广西',
        '云南',
        '西藏',
        '新疆',
        '青海',
        '甘肃',
        '宁夏',
        '山西',
        '陕西',
        '河南',
        '安徽',
        '湖北',
        '重庆',
        '贵州',
        '湖南',
        '江西',
        '乌兰巴托',
        '阿斯塔纳',
        '塔什干',
        '伊斯兰堡',
        '蒙古',
        '哈萨克斯坦',
        '吉尔吉斯斯坦',
        '塔吉克斯坦',
        '乌兹别克斯坦',
        '阿富汗',
        '巴基斯坦',
        '尼泊尔',
        '不丹',
        '孟加拉国',
        '缅甸',
        '老挝',
        '日本',
      ]
      const regions = []
      const chinas = [
        '北京',
        '上海',
        '四川',
        '黑龙江',
        '吉林',
        '辽宁',
        '天津',
        '内蒙古',
        '河北',
        '山东',
        '江苏',
        '浙江',
        '福建',
        '台湾',
        '香港',
        '广东',
        '澳门',
        '海南',
        '广西',
        '云南',
        '西藏',
        '新疆',
        '青海',
        '甘肃',
        '宁夏',
        '山西',
        '陕西',
        '河南',
        '安徽',
        '湖北',
        '重庆',
        '贵州',
        '湖南',
        '江西',
      ]
      chinas.forEach((c) => {
        regions.push(
          // 这个地方是关键,通过设置regions,可以实现不同的省份边界线配置不同的颜色,
          {
            name: c, // 这个名字要和china.js保持一致
            itemStyle: {
              normal: {
                opacity: 1, // 透明度
                borderColor: '#ed2c2c',
                borderWidth: 1,
              },
            },
          }
        )
      })
      const worldAndChina = Object.assign({}, world) // 原本的world还需要用 所以这里用了一个深拷贝赋值世界地图数据
      console.log(worldAndChina.features)
      console.log(data.features)
      worldAndChina.features = worldAndChina.features.concat(data.features) // 对，就是这么简单用concat把两者的features合并起来就可以了
      // console.log(worldjson.features)
      // worldAndChina.features =worldjson.features
      // chart = echarts.init(this.$refs.chart)
      const dataList = this.dataList
      const _this = this
      var myChart = echarts.init(document.getElementById('map'))
      // echarts.registerMap('world', world) // 显示地图

      echarts.registerMap('world', worldAndChina)
      // echarts.registerMap('world', world)
      var option = {
        legend: {
          show: true,
          right: 20,
          top: 20,
          orient: 'vertical',
          // data: [
          //   '审计覆盖情况',
          //   '当年已审计单位',
          //   '1年未审计单位',
          //   '2年未审计单位',
          //   '3年未审计单位',
          //   '4年及以上未审计单位',
          // ],
        },
        tooltip: {
          axisPointer: {
            type: 'shadow',
          },

          enterable: true,
          backgroundColor: '#fff', // 提示浮窗背景颜色
          borderColor: 'rgba(0, 0, 0, 0.16);',
          borderWidth: 1,
          extraCssText: 'width:400px',
          // alwaysShowContent: true, // 永远显示
          confine: false,
          position: 'right',
          // 数据格式化
          formatter: function(params, callback) {
            var result = ''
            if (params.data) {
              //
              result += `<div><div style="width:15px;" id='pic' class="chinamappictp"></div><div><span style="color:#000;font-size:20px;font-weight:bold;margin:0 2px;margin-bottom:10px;">${params.data.name}</span><span  style="float:right;color:#000;font-size:20px;margin-right:2px;margin-left:10px;">${params.value[2].year}</span></div>`
              for (var i = 0; i < params.value[2].datas.length; i++) {
                let title = params.value[2].datas[i].name
                if (title.length > 10) {
                  title = title.substring(0, 10) + '...'
                }
                result += `<div  style="margin: 0 2px;" class="mapdivchina"><span style="color:gray" title="${params.value[2].datas[i].name}">${title}</span>`
                const color = fngetcolor(params.value[2].datas[i].level)
                result += `<span style="float:right;color:${color};margin-right:2px;margin-left:10px;">${params.value[2].datas[i].level}`
                if (params.value[2].datas[i].dataList) {
                  result += ` <i class="qrm-arrow-right" onclick="fnshowdiv('${params.value[2]
                    .datas[i].name +
                    '_' +
                    i.toString()}')" ></i>`
                }
                result += `</span>`
                if (params.value[2].datas[i].dataList) {
                  result += `<div id="mapdiv_${params.value[2].datas[i].name +
                    '_' +
                    i.toString()}" class="mapdivchinazitem" > `
                  for (var j = 0; j < params.value[2].datas[i].dataList.length; j++) {
                    const item = params.value[2].datas[i].dataList[j]
                    let ztitle = item.name
                    if (ztitle.length > 10) {
                      ztitle = ztitle.substring(0, 10) + '...'
                    }
                    result += `<div  style="margin: 0 2px;"><span style="color:gray" title="${item.name}">${ztitle}</span>`
                    const itemcolor = fngetcolor(item.level)
                    result += `<span style="float:right;color:${itemcolor};margin-right:2px;margin-left:10px;">${item.level}`
                    result += `</span></div>`
                  }
                  result += ` </div>`
                }
                result += `</div>`
              }
              result += `</div>  `
            }
            return result
          },
        },
        nameMap: geoCoordMap.nameMap,
        visualMap: {
          type: 'piecewise',
          inRange: { color: ['#02F6F9', '#02F6F9', '#02F6F9'] },
          pieces: [
            { min: 0, max: 1000000, color: 'red' },
            {
              min: 1000000,
              max: 50000000,
              color: {
                type: 'radial',
                x: 0.5,
                y: 0.5,
                r: 0.5,
                colorStops: [
                  { offset: 0, color: 'rgba(11,28,92,0)' },
                  { offset: 0.9, color: 'rgba(10,94,137, 0.5)' },
                  { offset: 1, color: 'rgba(2, 246, 249, 1)' },
                ],
                globalCoord: false, // 缺省为 false
              },
            },
          ],
          show: false,
          textStyle: {
            color: '#ffffff',
            fontSize: 16,
          },
        },
        geo: {
          map: 'world',
          silent: true,
          animationDurationUpdate: 0,
          roam: true,
          zoom: 5,
          label: {
            normal: {
              show: true, // 是否显示对应地名
              textStyle: {
                color: '#1a1112',
              },
              formatter: function(params) {
                if (gj.find((i) => i === params.name)) {
                  return params.name
                } else {
                  return ''
                }
              },
            },
            emphasis: {
              // 对应的鼠标悬浮效果
              show: false,
              textStyle: {
                color: '#1a1112',
              },
            },
          },
          itemStyle: {
            normal: {
              color: ['#f7f7f7'], // 地图背景色
              borderWidth: 1,
              borderColor: '#bbbbbb', // 省市边界线
            },
            // emphasis: {
            //   color: ['#f7f7f7'], // 地图背景色
            //   borderColor: '#bbbbbb', // 省市边界线
            // },
          },
          regions: regions,
          center: [104.948024, 26.263161],
        },
        backgroundColor: 'rgb(179,205,253)',
        series: [
          {
            name: '当年已审计单位',
            type: 'effectScatter',
            coordinateSystem: 'geo',
            data: this.convertData(dataList, 0),
            symbol: 'circle',
            symbolSize: 8,
            encode: {
              value: 2,
            },
            showEffectOn: 'render',
            rippleEffect: {
              brushType: 'stroke',
            },
            hoverAnimation: true,
            label: {
              formatter: '{b}',
              position: 'right',
              show: false,
            },
            itemStyle: {
              // color: 'red',
              color: 'green',
              shadowBlur: 40,
            },
            tooltip: {
              // 提示框样式
              backgroundColor: '#fff', // 提示浮窗背景颜色
              borderColor: 'rgba(0, 0, 0, 0.16);',
              borderWidth: 1,
              extraCssText: 'width:400px;box-shadow: 0 0 5px #008aff;',
            },
          },

          {
            name: '1年未审计单位',
            type: 'effectScatter',
            coordinateSystem: 'geo',
            data: this.convertData(dataList, 1),
            symbolSize: function(val) {
              return 8
            },
            encode: {
              value: 2,
            },
            showEffectOn: 'render',
            rippleEffect: {
              brushType: 'stroke',
            },
            hoverAnimation: true,
            label: {
              formatter: '{b}',
              position: 'right',
              show: false,
            },
            itemStyle: {
              // color: 'green',
              color: 'blue',
              shadowBlur: 20,
            },
            tooltip: {
              // 提示框样式
              backgroundColor: '#fff', // 提示浮窗背景颜色
              borderColor: 'rgba(0, 0, 0, 0.16);',
              borderWidth: 1,
              extraCssText: 'width:400px;box-shadow: 0 0 5px #008aff;',
            },
          },

          {
            name: '2年未审计单位',
            type: 'effectScatter',
            coordinateSystem: 'geo',
            data: this.convertData(dataList, 2),
            symbolSize: function(val) {
              return 8
            },
            encode: {
              value: 2,
            },
            showEffectOn: 'render',
            rippleEffect: {
              brushType: 'stroke',
            },
            hoverAnimation: true,
            label: {
              formatter: '{b}',
              position: 'right',
              show: false,
            },
            itemStyle: {
              // color: 'blue',
              color: '#EEEE00',
              shadowBlur: 20,
            },
            tooltip: {
              // 提示框样式
              backgroundColor: '#fff', // 提示浮窗背景颜色
              borderColor: 'rgba(0, 0, 0, 0.16);',
              borderWidth: 1,
              extraCssText: 'width:400px;box-shadow: 0 0 5px #008aff;',
            },
          },
        ],
      }
      const threeYears = {
        name: '3年未审计单位',
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: this.convertData(dataList, 3),
        symbolSize: function(val) {
          return 8
        },
        encode: {
          value: 2,
        },
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke',
        },
        hoverAnimation: true,
        label: {
          formatter: '{b}',
          position: 'right',
          show: false,
        },
        itemStyle: {
          // color: '#EEEE00',
          color: '#FFA500',
          shadowBlur: 20,
        },
        tooltip: {
          // 提示框样式
          backgroundColor: '#fff', // 提示浮窗背景颜色
          borderColor: 'rgba(0, 0, 0, 0.16);',
          borderWidth: 1,
          extraCssText: 'width:400px;box-shadow: 0 0 5px #008aff;',
        },
      }
      const threeYearsOrMore = {
        name: '3年及以上未审计单位',
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: [...this.convertData(dataList, 5),...this.convertData(dataList, 10)],
        symbolSize: function(val) {
          return 8
        },
        encode: {
          value: 2,
        },
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke',
        },
        hoverAnimation: true,
        label: {
          formatter: '{b}',
          position: 'right',
          show: false,
        },
        itemStyle: {
          // color: '#FFA500',
          color: 'red',
          shadowBlur: 20,
        },
        tooltip: {
          // 提示框样式
          backgroundColor: '#fff', // 提示浮窗背景颜色
          borderColor: 'rgba(0, 0, 0, 0.16);',
          borderWidth: 1,
          extraCssText: 'width:400px;box-shadow: 0 0 5px #008aff;',
        },
      }
      const fourYearsOrMore = {
        // name: '4年未审计单位',
        name: '4年及以上未审计单位',
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: this.convertData(dataList, 4),
        symbolSize: function(val) {
          return 8
        },
        encode: {
          value: 2,
        },
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke',
        },
        hoverAnimation: true,
        label: {
          formatter: '{b}',
          position: 'right',
          show: false,
        },
        itemStyle: {
          // color: '#FFA500',
          color: 'red',
          shadowBlur: 20,
        },
        tooltip: {
          // 提示框样式
          backgroundColor: '#fff', // 提示浮窗背景颜色
          borderColor: 'rgba(0, 0, 0, 0.16);',
          borderWidth: 1,
          extraCssText: 'width:400px;box-shadow: 0 0 5px #008aff;',
        },
      }
      const companyName = JSON.parse(getUserInfo().attrs.deptLevMap).COMPANY
      if (companyName) {
        if (companyName === '国家电力投资集团有限公司总部') {
          option.series.push(threeYears)
          option.series.push(fourYearsOrMore)
        } else {
          option.series.push(threeYearsOrMore)
        }
      } else {
        option.series.push(threeYears)
        option.series.push(threeYearsOrMore)
        option.series.push(fourYearsOrMore)
      }
      myChart.setOption(option)
      // myChart.on('click', function(params) {
      //   console.log('-------------dianjishijianchufa', params)
      //   const now = new Date()
      //   const year = now.getFullYear()
      //   window.open('#/xm-audit-mapcoverage-list?type=fourYearCoverage' + '&year=' + year)
      // })
      // 设置点击事件
      // myChart.on('legendselectchanged', function(params) {
      //   // 获取用户点击的图例名称
      //   var legendName = params.name
      //   // 根据不同的图例名称进行页面跳转
      //   if (legendName === '审计覆盖情况') {
      //     const now = new Date()
      //     const year = now.getFullYear()
      //     window.open('#/xm-audit-mapcoverage-list?type=fourYearCoverage' + '&year=' + year)
      //   }
      // })

      // const chart = echarts.init(document.getElementById('map'))
      // chart.on('georoam', function(params) {
      //   var option = chart.getOption() // 获得option对象
      //   if (params.zoom !== null && params.zoom !== undefined) {
      //     // 捕捉到缩放时
      //     option.geo[0].zoom = option.series[0].zoom // 下层geo的缩放等级跟着上层的geo一起改变
      //     option.geo[0].center = option.series[0].center // 下层的geo的中心位置随着上层geo一起改变
      //   } else {
      //     // 捕捉到拖曳时
      //     option.geo[0].center = option.series[0].center // 下层的geo的中心位置随着上层geo一起改变
      //   }
      //   chart.setOption(option) // 设置option
      // })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.mapBox {
  height: 100%;
  // position: relative;
  margin-top: 20px;
  background: #b3cefd;
}
.mapTableBox {
  position: absolute;
  right: 10px;
  bottom: 10px;
  width: 420px;
  padding: 10px;
  border: 1px solid #02f6f9;
  border-radius: 5px;
  box-shadow: 0 0 10px 5px #02f6f9;
}
.sort {
  float: right;
  margin-bottom: 10px;
}
.mapTableBox thead {
  color: #fff !important;
}
.mapTableBox .el-table {
  color: #fff !important;
  background-color: transparent !important;
}
.mapTableBox .el-table__header-wrapper th {
  background-color: rgba(2, 77, 186, 1) !important;
}
.mapTableBox tbody tr {
  background-color: #091e64 !important;
}
.mapTableBox .el-table__row--striped td {
  background-color: rgba(2, 77, 186, 1) !important;
}
.mapTableBox .el-table th.is-leaf,
.mapTableBox .el-table td {
  border: none !important;
}
.mapTableBox .el-table::before {
  display: none !important;
}
.mapTableBox .el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #091e64;
}
.mapTableBox .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  background-color: rgba(2, 77, 186, 1) !important;
  border-color: rgba(2, 77, 186, 1) !important;
  box-shadow: -1px 0 0 0 rgba(2, 77, 186, 1) !important;
  box-shadow: -1px 0 0 0 rgba(2, 77, 186, 1) !important;
}
:global .chinamappictp {
  top: 0;
  float: left;
  width: 20px !important;
  height: 20px !important;
  background-color: initial !important;
  background-image: url('./dtb.png');
  background-repeat: no-repeat;
  background-position-x: center;
  background-position-y: center;
  background-size: 100%;
  border: none !important;
}
:global .qrm-arrow-right {
  // position: absolute;
  // top: 14px;
  // right: 7px;
  display: inline-block;
  width: 8px;
  height: 10px;
  background: url('./right.png') no-repeat;
  background-color: initial !important;
  background-position-x: center;
  background-position-y: center;
  background-size: 100%;
}
:global .mapdivchina span {
  height: 30px;
  font-size: 18px;
  line-height: 30px;
}
:global .mapdivchinazitem span {
  height: 30px;
  font-size: 18px;
  line-height: 30px;
}
:global .mapdivchinazitem {
  position: absolute;
  left: 400px;
  display: none;
  width: 400px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.16);
  box-shadow: rgb(0, 138, 255) 0 0 5px;
}
:global .mapdivchina:hover {
  // width: auto;
  .mapdivchinazitem {
    display: inline;
  }
}
</style>
