<template>
  <div class="middleMap">
    <div class="chart" ref="middleMap"></div>
    <div class="back" v-show="backShow" @click="backClick">〈 返回</div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import 'echarts-gl'
//引入map相关json配置
import mapJson from './config.json'
import mainMap from './mapJson/china.json'
export default {
  name: 'MapInfo',
  props: {
    // groupData:{
    //     type:Object,
    //     required:true
    // },
    // comData:{
    //     type:Object,
    //     required:true
    // },
    // userBindInfo:{
    //     type:Array,
    //     required:true
    // },
    // projectData:{
    //     type:Object,
    //     required:true,
    // },
    // setNullAndUndefinedEmpty: {
    //     type: Function,
    //     default: null
    // },
  },
  data() {
    return {
      groupAttr: null,
      //项目数据信息
      //   pData: this.projectData,
      projectChart: null,
      mdata: null,
      //集团以及区域数据信息
      // groupInfoData:this.comData.groupProjectInfo,
      groupChart: null,
      mapname: null, //子地图json数据
      mapData: [], //地图图上数据
      // groupName:this.comData.groupName,//区域名称存储
      groupName: null, //区域名称存储
      mapShowBuildData: [], //今日扫码数据
      mapShowUnBuildData: [], //今日未扫码数据
      isSilent: null, //图形是否不响应和触发鼠标事件
      mapDistance: null, //地图视角距离主体的距离
      mapBoxWidth: null, //三维地图在三维场景中的宽度
      offset: null, //三维地图中心偏移
      clickSymbol: null, //地图点击标识,0为区域点击,1为项目点击
      domImg: null, //地图背景图片
      //
      backShow: false,
      clickPermissions: false
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData() {
      this.destroyChart()
      // this.groupAttr=this.comData.groupAttr
      // if(this.groupAttr!==true){
      //     this.showWorkArea()
      // }else{
      //   this.composeScanInfo(this.groupInfoData)
      // }
      this.composeScanInfo()
    },
    /**
     * 项目信息模块
     */
    //获取工区数据
    async showWorkArea() {
      let mapData1 = [] //存储未开工信息
      let mapData2 = [] //存储在建信息
      let mapData3 = [] //存储完工信息
      let mapData4 = [] //存储停工信息
      let mapDataScan = [] //存储今日扫码信息
      const res = await GetBuildAreaStatistic_api({ prjId: this.pData.prjId })
      const { code, result } = res.data
      if (code === 1) {
        let arr = []
        result.forEach((item) => {
          arr.push(item.builtStatus)
          switch (item.builtStatus) {
            //无状态情况特殊处理，归于未施工
            case null:
              mapData1.push({
                name: item.zdwName,
                value: [item.longitude, item.latitude, 1],
                designLength: item.tfPipeLength,
                lengthPercentNew: item.lengthPercentNew
              })
              break
            case 1:
              mapData1.push({
                name: item.zdwName,
                value: [item.longitude, item.latitude, 1],
                designLength: item.tfPipeLength,
                lengthPercentNew: item.lengthPercentNew
              })
              break
            case 2:
              mapData2.push({
                name: item.zdwName,
                value: [item.longitude, item.latitude, 2],
                designLength: item.tfPipeLength,
                lengthPercentNew: item.lengthPercentNew
              })
              break
            case 3:
              mapData3.push({
                name: item.zdwName,
                value: [item.longitude, item.latitude, 3],
                designLength: item.tfPipeLength,
                lengthPercentNew: item.lengthPercentNew
              })
              break
            case 4:
              mapData4.push({
                name: item.zdwName,
                value: [item.longitude, item.latitude, 4],
                designLength: item.tfPipeLength,
                lengthPercentNew: item.lengthPercentNew
              })
              break
          }
          if (item.todayScan != null && item.todayScan > 0) {
            mapDataScan.push({
              name: item.zdwName,
              value: [item.longitude, item.latitude, 5],
              designLength: item.tfPipeLength,
              lengthPercentNew: item.lengthPercentNew
            })
          }
        })
        this.showMapInfo(
          mapData1,
          mapData2,
          mapData3,
          mapData4,
          mapDataScan,
          mapData1.length,
          mapData2.length,
          mapData3.length,
          mapData4.length,
          mapDataScan.length
        )
      } else {
        this.$message.error('工区信息获取失败')
      }
    },
    //显示地图信息
    // showMapInfo(mapData1, mapData2, mapData3, mapData4, mapDataScan, data1, data2, data3, data4, dataScan) {
    //   var that = this
    //   let mapname = null
    //   let mapRegion = null
    //   //地图数据加载
    //   let match = (name) => mapJson.regionData.filter((o) => o.name == name)
    //   if (match(that.pData.projectName.substring(0, 2)).length > 0) {
    //     mapname = require(`@/components/HomePage${match(that.pData.projectName.substring(0, 2))[0].json}`)
    //   }
    //   if (that.pData.projectName.indexOf('宜昌') != -1) {
    //     mapname = require('@/components/HomePage/mapJson/HB-YC.json') //地图json数据
    //   }
    //   if (mapname == null) return
    //   //初始加载
    //   this.projectChart = echarts.init(this.$refs.middleMap)
    //   this.projectChart.showLoading('default', {
    //     text: '统计中，请稍候...',
    //     maskColor: '#2957A2',
    //     textColor: '#fff',
    //     fontSize: 14,
    //     zlevel: 9999
    //   })
    //   let domImg = document.createElement('img')
    //   domImg.crossOrigin = 'anonymous'
    //   //   domImg.src = require('@/components/HomePage/images/projectMapImage.png')
    //   setTimeout(function () {
    //     mapInit()
    //   }, 1000)
    //   //加载方法
    //   let mapInit = () => {
    //     echarts.registerMap('mainMap', mapname)
    //     this.projectChart.hideLoading()
    //     var option = {
    //       backgroundColor: 'transparent',
    //       title: {
    //         top: 20,
    //         text: mapRegion,
    //         subtext: '',
    //         x: 'right',
    //         textStyle: {
    //           color: '#fff',
    //           fontWeight: 500,
    //           fontSize: 14
    //         }
    //       },
    //       legend: {
    //         orient: 'vertical',
    //         left: 0,
    //         bottom: 20,
    //         data: [
    //           {
    //             name: '未开工：' + data1 + '个'
    //           },
    //           {
    //             name: '施工中：' + data2 + '个'
    //           },
    //           {
    //             name: '已完工：' + data3 + '个'
    //           },
    //           {
    //             name: '停   工：' + data4 + '个'
    //           },
    //           {
    //             name: '今日扫码：' + dataScan + '个'
    //           }
    //         ],
    //         inactiveBorderWidth: 0,
    //         itemStyle: {
    //           borderWidth: 0,
    //           opacity: 1
    //         },
    //         textStyle: {
    //           color: '#fff'
    //         }
    //       },
    //       tooltip: {
    //         enterable: true,
    //         backgroundColor: 'rgba(0,2,89,0.8)',
    //         triggerOn: 'mousemove',
    //         borderWidth: 0,
    //         formatter: function (params) {
    //           var showData = params['data']
    //           if (showData) {
    //             return `<div><div style="color:#fff;float:left">${
    //               showData.name +
    //               '<br>设计里程：' +
    //               (that.setNullAndUndefinedEmpty(showData.designLength) / 1000).toFixed(3) +
    //               'km<br>实际施工百分比：' +
    //               that.setNullAndUndefinedEmpty(showData.lengthPercentNew) +
    //               '%'
    //             }</div></div>`
    //           } else {
    //             return ``
    //           }
    //         }
    //       },
    //       geo: {
    //         map: 'mainMap',
    //         aspectScale: 0.75,
    //         layoutCenter: ['50%', '50%'],
    //         layoutSize: '90%',
    //         silent: true,
    //         roam: true,
    //         z: 0,
    //         itemStyle: {
    //           areaColor: {
    //             image: domImg,
    //             repeat: 'repeat'
    //           },
    //           shadowColor: 'rgba(0, 0, 0, 0.7)',
    //           shadowBlur: 0,
    //           shadowOffsetX: 0,
    //           shadowOffsetY: 5,
    //           borderColor: 'rgba(0, 0, 0, 0.7)',
    //           borderWidth: 0.5,
    //           opacity: 1
    //         },
    //         emphasis: {
    //           areaColor: '#2AB8FF',
    //           borderWidth: 1,
    //           color: 'red',
    //           label: {
    //             show: false
    //           }
    //         }
    //       },
    //       series: [
    //         {
    //           name: '未开工：' + data1 + '个',
    //           type: 'scatter',
    //           coordinateSystem: 'geo',
    //           itemStyle: {
    //             color: '#FFFFFF',
    //             borderWidth: 1,
    //             borderColor: '#696969'
    //           },
    //           symbol: 'circle',
    //           zlevel: 3,
    //           data: mapData1
    //         },
    //         {
    //           name: '施工中：' + data2 + '个',
    //           type: 'scatter',
    //           coordinateSystem: 'geo',
    //           itemStyle: {
    //             color: '#00FFFF',
    //             borderWidth: 1,
    //             borderColor: '#696969'
    //           },
    //           symbol: 'circle',
    //           zlevel: 3,
    //           data: mapData2
    //         },
    //         {
    //           name: '已完工：' + data3 + '个',
    //           type: 'scatter',
    //           coordinateSystem: 'geo',
    //           itemStyle: {
    //             color: '#08CA5F',
    //             borderWidth: 1,
    //             borderColor: '#696969'
    //           },
    //           symbol: 'circle',
    //           zlevel: 3,
    //           data: mapData3
    //         },
    //         {
    //           name: '停   工：' + data4 + '个',
    //           type: 'scatter',
    //           coordinateSystem: 'geo',
    //           itemStyle: {
    //             color: '#EA4551',
    //             borderWidth: 1,
    //             borderColor: '#696969'
    //           },
    //           symbol: 'circle',
    //           zlevel: 3,
    //           data: mapData4
    //         },
    //         {
    //           name: '今日扫码：' + dataScan + '个',
    //           type: 'effectScatter',
    //           coordinateSystem: 'geo',
    //           rippleEffect: {
    //             scale: 5,
    //             brushType: 'stroke'
    //           },
    //           showEffectOn: 'render',
    //           itemStyle: {
    //             color: '#E2F039'
    //           },
    //           label: {
    //             color: '#fff'
    //           },
    //           symbol: 'circle',
    //           data: mapDataScan,
    //           zlevel: 3
    //         }
    //       ]
    //     }
    //     this.projectChart.resize()
    //     this.projectChart.setOption(option, {
    //       notMerge: true
    //     })
    //     //图表大小自适应
    //     window.addEventListener('resize', () => {
    //       this.projectChart.resize()
    //     })
    //   }
    // },
    //组装施工数据
    composeScanInfo(result) {
      //清空存储
      // this.mapShowBuildData.splice(0,this.mapShowBuildData.length)
      // this.mapShowUnBuildData.splice(0,this.mapShowUnBuildData.length)
      // result.forEach(item => {
      //     item.data.forEach(element=> {
      //         let median={"name":element.prjname,"value":[element.longitude,element.latitude],"datas":{region:item.detail.orgName,projectName:element.prjname,projectId:element.prjId,designLength:element.designLength,todayScan:element.todayScan}}
      //         if(element.todayScan>0){
      //             this.mapShowBuildData.push(median)
      //         }else{
      //             this.mapShowUnBuildData.push(median)
      //         }
      //     });
      // });
      // //加载空数据防止图上数据下陷
      // this.mapShowBuildData.push({"name":"","value":[0,0],"datas":{region:"",projectName:"",designLength:"",todayScan:0}})
      // this.mapShowUnBuildData.push({"name":"","value":[0,0],"datas":{region:"",projectName:"",designLength:"",todayScan:0}})
      //地图json数据加载
      this.getMapJsonData()
    },
    //地图json数据
    getMapJsonData() {
      this.mapData = []
      //地图json数据
      if (!this.groupName) {
        // if(this.groupName==null){
        this.mapname = mainMap
        // this.userBindInfo.forEach(item=>{
        //     if(item.pid=="1"){
        //         if(item.orgName.substring(0,2)=='上游'){
        this.mapData.push()
        // this.mapData.push({"name":"云南省","value":{'orgId':item.orgID,'showName':item.groupName+"/"+item.orgName}})
        // this.mapData.push({"name":"贵州省","value":{'orgId':item.orgID,'showName':item.groupName+"/"+item.orgName}})
        // this.mapData.push({"name":"重庆市","value":{'orgId':item.orgID,'showName':item.groupName+"/"+item.orgName}})
        //         }
        //         else{
        //             this.mapData.push({"name":item.orgName.substring(0,3),"value":{'orgId':item.orgID,'showName':item.groupName+"/"+item.orgName}})
        //         }
        //     }
        // })
        this.clickSymbol = 0
        this.isSilent = false
        this.mapDistance = 520
        this.mapBoxWidth = 550
        this.offset = 20
      } else {
        let match = (name) => mapJson.groupData.filter((o) => o.name == name)
        if (match(this.groupName.substring(0, 2)).length > 0) {
          this.mapname = require(`@/components/HomePage${match(this.groupName.substring(0, 2))[0].json}`)
        }
        this.clickSymbol = 1
        this.isSilent = true
        this.mapDistance = 120
        this.mapBoxWidth = 100
        this.offset = 0
        this.mapData = []
      }
      //地图初始化
      // this.mapInit(this.mapname,this.mapShowBuildData,this.mapShowUnBuildData,this.groupName,this.mapData);
      this.mapInit(this.mapname, [], [], this.groupName, this.mapData)
    },
    //地图初始化
    mapInit(initname, mapShowBuildData, mapShowUnBuildData, orgName, mapData) {
      var that = this
      //容器加载
      this.groupChart = echarts.init(this.$refs.middleMap)
      let scanImg =
        'path://M839.68 337.8176L512 665.3952 184.32 337.8176 512 0l327.68 337.8176z M384 956.5184a128 67.4816 0 1 0 256 0 128 67.4816 0 1 0-256 0Z M496.64 635.1872h30.72V915.456h-30.72z'
      this.groupChart.showLoading('default', {
        text: '统计中，请稍候...',
        maskColor: '#2957A2',
        textColor: '#fff',
        fontSize: 14,
        zlevel: 9999
      })
      //地图背景图预加载
      let domImg = document.createElement('img')
      domImg.crossOrigin = 'anonymous'
      domImg.src = require('@/views/groupPage/images/bj.png')
      setTimeout(() => {
        mapInit()
      }, 1000)
      let mapInit = () => {
        echarts.registerMap('riverBasin', initname)
        this.groupChart.hideLoading()
        //地图背景图
        //配置项
        var option = {
          backgroundColor: 'transparent',
          geo3D: {
            map: 'riverBasin',
            show: false,
            silent: that.isSilent,
            boxWidth: that.mapBoxWidth, //三维地图在三维场景中的宽度
            viewControl: {
              autoRotate: true, //是否自动旋转
              autoRotateSpeed: 5, //旋转速度
              autoRotateAfterStill: 10, //在鼠标静止操作后恢复自动旋转的时间间隔。在开启 autoRotate 后有效。
              alpha: 40, //上下旋转的角度
              maxBeta: 15, //沿y轴旋转的角度，设置Infinity控制其一直旋转
              distance: that.mapDistance, //地图视角 控制初始大小
              center: [that.offset, 0, 0]
            },
            zlevel: -10
          },
          //   tooltip: {
          //     enterable: true,
          //     backgroundColor: '#034E8C',
          //     triggerOn: 'mousemove',
          //     formatter: function (params) {
          //       var showData = params['data']
          //       if (showData && showData.datas) {
          //         return `<div><div style="color:#fff;float:left"><span>${showData.datas.region}</span><br><span>${
          //           showData.datas.projectName
          //         }</span><br><span>设计里程：${showData.datas.designLength.toFixed(3)}km</span><br><span>今日扫码：${
          //           showData.datas.todayScan
          //         }个</span></div></div>`
          //       } else {
          //         return ``
          //       }
          //     }
          //   },
          series: [
            {
              type: 'map3D',
              name: orgName,
              map: 'riverBasin',
              silent: that.isSilent,
              boxHeight: 30,
              roam: true,
              itemStyle: {
                normal: {
                  borderColor: '#94D0F2',
                  borderWidth: 1.5
                },
                emphasis: {
                  areaColor: '#2AB8FF',
                  borderWidth: 0
                }
              },
              boxWidth: that.mapBoxWidth, //三维地图在三维场景中的宽度
              label: {
                show: true,
                color: 'rgba(154, 199, 240, 1)', //文字颜色
                fontSize: 14, //文字大小
                fontWeight: 'bold'
              },
              viewControl: {
                autoRotate: true, //是否自动旋转
                autoRotateSpeed: 5, //旋转速度
                autoRotateAfterStill: 10, //在鼠标静止操作后恢复自动旋转的时间间隔。在开启 autoRotate 后有效。
                alpha: 40, //上下旋转的角度
                maxBeta: 15, //沿y轴旋转的角度，设置Infinity控制其一直旋转
                distance: that.mapDistance, //地图视角 控制初始大小
                center: [that.offset, 0, 0]
              },
              shading: 'realistic',
              realisticMaterial: {
                //纹理材质
                detailTexture: domImg,
                textureTiling: 1
              },
              light: {
                main: {
                  color: '#fff', //光照颜色#E4F7FE
                  intensity: 2.2, //光照强度
                  shadowQuality: 'high', //阴影亮度
                  shadow: true, //是否显示阴影
                  // alpha: 40,
                  beta: 30
                },
                ambient: {
                  intensity: 0.3
                }
              },
              zlevel: 1,
              data: [
                {
                  name: '四川省',
                  height: 10
                },
                {
                  name: '湖南省',
                  height: 8
                },
                {
                  name: '贵州省',
                  height: 6
                }
              ]
            }
            // {
            //   name: 'todayScan',
            //   type: 'scatter3D',
            //   coordinateSystem: 'geo3D',
            //   itemStyle: {
            //     // color: '#00f6ff',
            //     color: '#FFFF00'
            //   },
            //   emphasis: {
            //     label: {
            //       show: false
            //     }
            //   },
            //   symbol: scanImg,
            //   symbolSize: [18, 30], //宽度、高度
            //   data: mapShowBuildData,
            //   blendMode: 'source-over',
            //   zlevel: 10
            // },
            // {
            //   name: 'todayNoScan',
            //   type: 'scatter3D',
            //   coordinateSystem: 'geo3D',
            //   itemStyle: {
            //     // color: '#9ed3d8',
            //     color: 'rgb(0,255,255)'
            //   },
            //   emphasis: {
            //     label: {
            //       show: false
            //     }
            //   },
            //   symbol: scanImg,
            //   symbolSize: [18, 30],
            //   data: mapShowUnBuildData,
            //   blendMode: 'source-over',
            //   zlevel: 10
            // }
          ]
        }
        this.groupChart.resize()
        this.groupChart.setOption(option, {
          notMerge: true
        })
        //图表大小自适应
        window.addEventListener('resize', () => {
          this.groupChart.resize()
        })
      }
      //地图点击事件
      if (this.clickSymbol == 0) {
        this.chartRegionClickEvent()
      } else {
        this.chartProjectClickEvent()
      }
    },
    //地图区域点击事件
    chartRegionClickEvent() {
      if (!this.groupChart) return
      //图表点击事件
      var that = this
      this.groupChart.off('click') //清除原有的点击事件
      this.groupChart.on('click', 'series.map3D', function (e) {
        console.log('地图点击', e)
        if (e.value == null) return
        let changeData = {
          orgId: e.value.orgId,
          groupName: e.name,
          unitSymbol: e.value.orgId,
          pidSymbol: '1',
          showName: e.value.showName
        }
        that.$emit('changeGroupData', changeData)
        that.backShow = true
        that.clickPermissions = true
      })
    },
    //地图项目点击事件
    chartProjectClickEvent() {
      if (!this.groupChart) return
      var that = this
      this.groupChart.off('click') //清除原有的点击事件
      this.groupChart.on('click', 'series.scatter3D', function (e) {
        if (e.value == null) return
        let changeData = {
          prjId: e.data.datas.projectId,
          projectName: e.data.datas.projectName,
          unitSymbol: e.data.datas.projectId,
          pidSymbol: '2',
          showName: '环保集团' + '/' + e.data.datas.region + '/' + e.data.datas.projectName
        }
        that.$emit('changeProjectData', changeData)
        if (that.userBindInfo[0].groupName != '环保集团') {
          that.backShow = true
          that.clickPermissions = true
        }
      })
    },
    //返回至初始
    backClick() {
      if (this.clickPermissions) {
        let changeData = {
          orgId: null,
          groupName: null,
          unitSymbol: '',
          pidSymbol: '0',
          showName: '环保集团'
        }
        this.$emit('changeGroupData', changeData)
        this.backShow = false
      }
    },
    //图表销毁
    destroyChart() {
      if (this.projectChart != null) {
        this.projectChart.dispose()
        this.projectChart = null
      }
      if (this.groupChart != null) {
        this.groupChart.dispose()
        this.groupChart = null
      }
    }
  },
  watch: {
    projectData: {
      handler(n, o) {
        this.pData.prjId = n.prjId //赋值给data
        this.pData.days = n.days
        this.pData.projectName = n.projectName
        this.getData()
      },
      deep: true // 深度监听父组件传过来对象变化
    },
    comData: {
      handler(n, o) {
        this.groupInfoData = n.groupProjectInfo //赋值给data
        this.groupAttr = n.groupAttr
        this.groupName = n.groupName
        this.getData()
      },
      deep: true // 深度监听父组件传过来对象变化
    }
  }
}
</script>

<style lang="scss" scoped>
.middleMap {
  width: 100%;
  height: 100%;
  position: relative;
  background: url('~@/views/groupPage/images/bj.png') no-repeat;
  background-size: 100% 100%;
  .chart {
    width: 100%;
    height: 100%;
  }
  .back {
    position: absolute;
    left: 17px;
    top: 25px;
    color: rgb(222, 222, 222);
    font-size: 12px;
    cursor: pointer;
    border: 1px solid rgba(255, 255, 255, 0.5);
    padding: 0px 6px 1px 0px;
    border-radius: 3px;
    z-index: 100;
    display: block;
  }
}
</style>