import { map3D, CATEGORIES } from '../../configuration/constants'
import { echartsBasicListen } from '../../feature/traits/common'
import { throttle } from '../../utils'

export default {

  // 组件名称
  name: map3D,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${map3D}" class="${map3D}"></div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${map3D} {
          position: absolute;
          border-radius: 5px;
          border-style: solid;
          border-width: 1px;
          border-color: transparent;
          padding: 10px;
          width: 600px;
          height: 400px;
        }
        .${map3D} .filterOptionContent {
          position: absolute;;
          top: 0;
          left: 0;
          width: 100%;
          height: 24px;
          z-index: 99;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: `
      <svg class="gjs-block-svg" viewBox="0 0 1024 1024"  xmlns="http://www.w3.org/2000/svg" ><path d="M635.957895 846.147368l-91.621053-53.894736-75.452631 37.726315-80.842106-113.178947v-48.505263l-59.28421 26.947368-43.11579-53.894737H188.631579L64.673684 506.610526 48.505263 414.989474 16.168421 344.926316l32.336842-53.894737L134.736842 269.473684l16.168421-53.894737L323.368421 156.294737l32.336842 102.4 75.452632 53.894737 134.736842 43.115789 140.126316-102.4v-53.894737L808.421053 64.673684 916.210526 161.684211l91.621053-21.557895-43.11579 113.178947 21.557895 70.063158-118.568421 107.789474-43.115789-32.336842-21.557895 16.168421 26.947368 43.115789-5.389473 43.11579 53.894737 118.568421-86.231579 150.905263-156.294737 75.452631z m-91.621053-113.178947l91.621053 53.894737 129.347368-64.673684 64.673684-113.178948-53.894736-107.789473 5.389473-37.726316-37.726316-64.673684L829.978947 323.368421l37.726316 32.336842 59.284211-53.894737-16.168421-53.894737 10.778947-32.336842-16.168421 5.389474-86.231579-75.452632-48.505263 70.063158v64.673685l-183.242105 134.736842-172.463158-53.894737-102.4-70.063158-21.557895-70.063158-91.621053 37.726316-16.168421 59.28421-97.010526 21.557895-10.778947 10.778947 21.557894 53.894737L113.178947 485.052632 215.578947 592.842105h97.010527l37.726315 43.11579 97.010527-43.11579v107.789474l37.726316 64.673684 59.28421-32.336842z" ></path><path d="M592.842105 878.484211l59.284211 26.947368-26.947369 53.894737-64.673684-21.557895 32.336842-59.28421zM916.210526 803.031579l-91.621052 123.957895-26.947369-91.621053 80.842106-75.452632 37.726315 43.11579z" ></path></svg>
        <div class="gjs-block-label">3D中国地图</div>
      `,
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '3D地图',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/372a16ea-f9c6-45c9-b54e-177ab66f71cf?# 《3D地图》',
      author: '秋水',
      email: 'qiushui.smy@xuelangyun.com',
      inPorts: [
        {
          uuid: 'in1',
          subType: 'json',
          description: {
            zh_CN: '输入1'
          }
        }
        // , {
        //   uuid: 'in2',
        //   subType: 'json',
        //   description: {
        //     zh_CN: '输入2'
        //   }
        // }, {
        //   uuid: 'in3',
        //   subType: 'json',
        //   description: {
        //     zh_CN: '输入3'
        //   }
        // }
      ]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: map3D,
      resizable: true,
      dmode: 'absolute',
      childrenSelectable: false,
      highlightable: false,
      droppable: false,
      traits: [
        {
          name: 'mapName',
          label: '地图名称',
          changeProp: 1
        }, {
          name: 'mapColor',
          label: '地图颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'mapBorderColor',
          label: '地图边框颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'leftTopRightBottom',
          label: '左,上,右,下',
          changeProp: 1,
        }, {
          name: 'mapLabel',
          label: '标签',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'mapLabelColor',
          label: '标签颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'selectOption',
          label: '下拉过滤列表',
          changeProp: 1,
          type: 'textarea'
        }, {
          name: 'selectWidth',
          label: '下拉列表宽度',
          changeProp: 1,
          type: 'number',
        }, {
          name: 'selectHeight',
          label: '下拉列表宽度',
          changeProp: 1,
          type: 'number',
        }, {
          name: 'selectFontSize',
          label: '下拉列表文字大小',
          changeProp: 1,
          type: 'number',
        }, {
          name: 'selectFontColor',
          label: '下拉列表文字颜色',
          changeProp: 1,
          type: 'color',
        }, {
          name: 'selectBgColor',
          label: '下拉列表背景颜色',
          changeProp: 1,
          type: 'color',
        }, {
          name: 'selectBorderColor',
          label: '下拉列表边框颜色',
          changeProp: 1,
          type: 'color',
        }, {
          name: 'useVisual',
          label: '视觉映射',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'visualPosition',
          label: '视觉映射图例',
          changeProp: 1,
          type: 'select',
          options: [
            { id: 'none', name: '无' },
            { id: 'top-left', name: '顶部居左' },
            { id: 'top-right', name: '顶部居右' },
            { id: 'center-left', name: '中部居左' },
            { id: 'center-right', name: '中部居右' },
            { id: 'bottom-left', name: '底部居左' },
            { id: 'bottom-right', name: '底部居右' },
          ]
        }, {
          name: 'visualItemWidth',
          label: '视觉映射图例标记宽度',
          changeProp: 1,
          type: 'number',
          min: 1
        }, {
          name: 'visualItemHeight',
          label: '视觉映射图例标记高度',
          changeProp: 1,
          type: 'number',
          min: 1
        },{
          name: 'visualItemAlign',
          label: '视觉映射图例标记位置',
          changeProp: 1,
          type: 'select',
          options: [
            { id: 'auto', name: '自动' },
            { id: 'left', name: '左部' },
            { id: 'right', name: '右部' },
          ]
        },{
          name: 'categories',
          label: '枚举型数据',
          changeProp: 1
        }, {
          name: 'inRangeColor',
          label: '范围内颜色',
          changeProp: 1
        }, {
          name: 'useForTextColor',
          label: '应用到图例文字',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'outRangeColor',
          label: '范围外颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'distance',
          label: '距离',
          type: 'number',
          changeProp: 1,
          min: 40,
          max: 400,
          step: 1,
        }, {
          name: 'alpha',
          label: '上下旋转角度',
          type: 'number',
          changeProp: 1,
          min: -360,
          max: 360,
          step: 1,
        }, {
          name: 'beta',
          label: '左右旋转角度',
          type: 'number',
          changeProp: 1,
          min: -360,
          max: 360,
          step: 1,
        }, {
          name: 'symbol',
          label: '节点',
          type: 'select',
          changeProp: 1,
          options: [{ id: 'emptyCircle', name: '空心圆' }, { id: 'circle', name: '圆形' }, { id: 'rect', name: '矩形' }, { id: 'roundRect', name: '圆角矩形' }, { id: 'triangle', name: '三角形' }, { id: 'diamond', name: '菱形' }, { id: 'pin', name: '大头针' }, { id: 'arrow', name: '箭头' }, { id: 'none', name: '无' }]
        }, {
          name: 'symbolPath',
          label: '路径节点',
          changeProp: 1
        }, {
          name: 'symbolSize',
          label: '节点大小(h,v)',
          changeProp: 1
        }, {
          name: 'symbolLabel',
          label: '节点标签',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'symbolLabelPosition',
          label: '节点标签位置',
          changeProp: 1,
          type: 'select',
          options: [
            { id: 'inside', name: '内部' },
            { id: 'top', name: '顶部' },
            { id: 'left', name: '左边' },
            { id: 'right', name: '右边' },
            { id: 'bottom', name: '底部' },
          ]
        },{
          name: 'symbolLabelDistance',
          label: '节点标签距离',
          type: 'number',
          changeProp: 1,
          min: 1,
          step: 1,
        }, {
          name: 'center',
          label: '视觉中心点',
          changeProp: 1
        }, {
          name: 'csv',
          label: '示例数据',
          changeProp: 1,
          type: 'csvDownload',
          preFileName: '3D地图',
          datas: [["position", "value","categroy","longitude", "latitude"], ["湖南建华建材有限公司",10, "类别1", 112.8806033100, 28.6995060100], ["无锡", 10, "类别1"], ["盐城", 10, "类别1"], ["青岛", 10, "类别2"], ["泉州", 10, "类别2"]]
        }, {
          name: 'defaultData',
          changeProp: 1,
          type: 'hide'
        }
      ],
      'defaultData':JSON.stringify([
        ["position", "value","categroy","longitude", "latitude"],
        ["湖南建华建材有限公司",10, "类别1", 112.8806033100, 28.6995060100],
        ["无锡", 10, "类别1"],
        ["盐城", 10, "类别1"],
        ["青岛", 10, "类别1"],
        ["泉州", 10, "类别1"],
        ["武汉", 10, "类别2"],
        ["岳阳", 10, "类别2"],
        ["湖州", 10, "类别2"],
        ["广州", 10, "类别2"]
      ]).replace(/\"/g, "\\\""),
      'mapName': 'china',
      'mapColor': '#002c4d',
      'mapBorderColor': '#66b5ff',
      'mapLabel': false,
      'mapLabelColor': '#fff',
      'selectOption': JSON.stringify([]),
      // 'selectOption': JSON.stringify([
      //   {label: '行业', key: 'trade', value: ['行业1', '行业2', '行业3', '行业4']},
      //   {label: '区域', key: 'area', value: ['区域1', '区域2', '区域3', '区域4']},
      // ]),
      'selectWidth': 100,
      'selectHeight': 25,
      'selectFontSize': 14,
      'selectFontColor': '#fff',
      'selectBgColor': 'rgba(4,23,34,1)',
      'selectBorderColor': 'rgba(18,111,154,1)',
      'useVisual': true,
      'visualPosition': 'center-right',
      'visualItemWidth': 20,
      'visualItemHeight': 14,
      'visualItemAlign': 'auto',
      // 'visualDimension': 2,
      'categories': '类别1,类别2',
      'inRangeColor': '#0084ff, #339cff, #66b5ff, #99ceff, #cce6ff',
      'useForTextColor': false,
      'outRangeColor': '#ddd',
      'distance': 100,
      'alpha': 40,
      'beta': 5,
      'symbol': 'circle',
      'symbolPath': null,
      'symbolSize': '40',
      'leftTopRightBottom': 'auto,auto,auto,auto',
      'symbolLabel': false,
      'symbolLabelPosition': 'inside',
      'symbolLabelDistance': 5,
      'color': '#ff962e,#ff5c5f,#70cc62,#86d1ca',
      'center': '0,0,0'
    }
  },

  onModelScript() {
    const dataSource = '{[ dataSource ]}';
    const bgColor = '{[ bgColor ]}';
    const borderColor = '{[ borderColor ]}';
    const fontColor = '{[ fontColor ]}';
    let colors = '{[ colors ]}';
    let legendPosition = ('{[ legendPosition ]}').toString();
    const legendOrient = ('{[ legendOrient ]}').toString();
    let legendMap = '{[ legendMap ]}';
    const legendItemGap = Number('{[ legendItemGap ]}');
    const legendItemWidth = Number('{[ legendItemWidth ]}');
    const legendItemHeight = Number('{[ legendItemHeight ]}');
    const legendFontSize = Number('{[ legendFontSize ]}');
    const titleText = '{[ titleText ]}';
    const titleColor = '{[ titleColor ]}';
    const titlePosition = ('{[ titlePosition ]}').toString();
    const mapName = '{[ mapName ]}';
    const mapColor = '{[ mapColor ]}';
    const mapBorderColor = '{[ mapBorderColor ]}';
    const mapLabel = Boolean('{[ mapLabel ]}');
    const mapLabelColor = '{[ mapLabelColor ]}';
    const selectOption = '{[ selectOption ]}';
    const selectWidth = Number('{[ selectWidth ]}');
    const selectHeight = Number('{[ selectHeight ]}');
    const selectFontSize = Number('{[ selectFontSize ]}');
    const selectFontColor = '{[ selectFontColor ]}';
    const selectBgColor = '{[ selectBgColor ]}';
    const selectBorderColor = '{[ selectBorderColor ]}';
    let leftTopRightBottom = ('{[ leftTopRightBottom ]}').toString();
    const useVisual = Boolean('{[ useVisual ]}');
    const visualPosition = ('{[ visualPosition ]}').toString();
    const visualItemWidth = Number('{[ visualItemWidth ]}');
    const visualItemHeight = Number('{[ visualItemHeight ]}');
    const visualItemAlign = ('{[ visualItemAlign ]}').toString();
    // const visualDimension = Number('{[ visualDimension ]}');
    let categories = ('{[ categories ]}').toString();
    const inRangeColor = '{[ inRangeColor ]}';
    const useForTextColor = Boolean('{[ useForTextColor ]}');
    const outRangeColor = ('{[ outRangeColor ]}').toString();
    const alpha = Boolean('{[ alpha ]}') ? parseFloat('{[ alpha ]}') : 0;
    const beta = Boolean('{[ beta ]}') ? parseFloat('{[ beta ]}') : 0;
    const symbol = ('{[ symbol ]}').toString();
    const symbolPath = Boolean('{[ symbolPath ]}') && ('{[ symbolPath ]}').toString();
    let symbolSize = ('{[ symbolSize ]}').toString();
    const distance = Number('{[ distance ]}');
    const center = ('{[ center ]}').toString().split(',').map(function(item){return Number(item.trim())});
    const symbolLabel = Boolean('{[ symbolLabel ]}');
    const symbolLabelPosition = ('{[ symbolLabelPosition ]}').toString();
    const symbolLabelDistance = Number('{[ symbolLabelDistance ]}');
    const defaultData = JSON.parse('{[ defaultData ]}'.replace(/\\\"/g, "\""));

    if (legendMap.indexOf(',')) {
      legendMap = legendMap.split(',').map(function(item) { return item.trim() });
    } else if (Boolean(legendMap)) {
      legendMap = [legendMap];
    } else {
      legendMap = ['输入1', '输入2', '输入3'];
    }
    leftTopRightBottom = leftTopRightBottom.split(',').map(function(item) { return item.trim() });

    if (symbolSize.indexOf(',') > 0) {
      symbolSize = symbolSize.split(',').map(function(item) { return Number(item.trim()) });
    } else if (Boolean(symbolSize)) {
      symbolSize = Number(symbolSize);
    }

    Boolean(bgColor) ? $(this).css({ backgroundColor: bgColor }) : $(this).css({ backgroundColor: 'transparent' });
    Boolean(borderColor) ? $(this).css({ borderColor: borderColor }) : $(this).css({ borderColor: 'transparent' });
    if (colors.indexOf(',') > -1) {
      colors = colors.split(',').map(item => item.trim())
    } else if (Boolean(colors)) {
      colors = [colors]
    }

    if (categories.indexOf(',') > 0) {
      categories = categories.split(',').map(function(item) { return item.trim() })
    } else {
      categories = [categories]
    }
    const cityDimension = 0;
    const valueDimension = 1;
    const visualDimension = 2;
    const longitudeDimension = 3;
    const latitudeDimension = 4;

    const titlePositionArr = titlePosition.split(',');
    const title = {
      text: titleText,
      left: titlePositionArr[0],
      top: titlePosition.indexOf(',') > 0 ? titlePositionArr[1] : titlePositionArr[0],
      textStyle: {
        fontSize: 16,
        color: titleColor || fontColor
      }
    };

    const legendShow = legendOrient != 'null';
    const legend = {
      show: legendShow,
      type: 'scroll',
      itemGap: legendItemGap,
      itemWidth: legendItemWidth,
      itemHeight: legendItemHeight,
      textStyle: {
        fontSize: legendFontSize,
        color: fontColor,
      },
      data: legendMap
    };
    if (Boolean(legendPosition)) {
      legendPosition.split(',').forEach((item, i) => {
        if (item.indexOf(':') > 0) {
          const key = item.split(':')[0].trim();
          const value = item.split(':')[1].trim();
          legend[`${key}`] = value;
        } else {
          legend[`${i ? 'top' : 'left'}`] = item.trim();
        }
      });
    }
    if (legendShow) {
      legend.orient = legendOrient;
    } else {
      legend.show = false;
    }

    var convertData = function (data) {
      var res = [];
      $.ajax({
        type: 'GET',
        url: "/common_static/data/echarts/map/geoCoordMap.json",
        async: false,
        success: function (geoCoordMap) {
          for (var i = 0; i < data.length; i++) {
            var geoCoord = geoCoordMap[data[i][cityDimension]];
            if (geoCoord) {
              res.push({
                name: data[i][cityDimension],
                value: geoCoord.concat(10,data[i][cityDimension],data[i][valueDimension],data[i][visualDimension])
              });
            } else if (data[i][longitudeDimension] && data[i][latitudeDimension] && data[i][longitudeDimension]!=='longitude') {
              res.push({
                name: data[i][cityDimension],
                value: [data[i][longitudeDimension],data[i][latitudeDimension],10,data[i][cityDimension],data[i][valueDimension],data[i][visualDimension]]
              });
            }
          }
        },
        error: function () {
          console.log('fetch geoCoordMap error')
        }
      });
      return res;
    };

    const geo3D = {
      map: mapName,
      roam: true,
      left: leftTopRightBottom[0] || 'auto',
      top: leftTopRightBottom[1] || 'auto',
      right: leftTopRightBottom[2] || 'auto',
      bottom: leftTopRightBottom[3] || 'auto',
      itemStyle: {
        color: mapColor,
        borderColor: mapBorderColor,
        borderWidth: 1
      },
      label: {
        show: mapLabel,
        textStyle: {
          color: mapLabelColor,
          fontSize: 10,
        },
      },
      emphasis: {
        label: {
          show: mapLabel,
          textStyle: {
            color: mapLabelColor,
            backgroundColor: 'rgba(0,0,0,0.6)'
          }
        },
        itemStyle: {
          color: mapColor
        }
      },
      viewControl: {
        distance: distance,
        alpha: alpha,
        beta: beta,
        center: center
      }
    }

    const visualMap = {
      type: 'piecewise',
      dimension: visualDimension + 3, // 数据转换后 数组最前面添加经、纬度、高度数据
      categories: categories,
      itemWidth: visualItemWidth,
      itemHeight: visualItemHeight,
      align: visualItemAlign,
      inRange: {},
      outOfRange: {},
      controller: {
        inRange: {},
        outOfRange: {}
      },
      textStyle: {
        color: useForTextColor ? [] : fontColor,
        fontSize: legendFontSize
      }
    }

    if (Boolean(inRangeColor)) {
      const _inRangeColor = inRangeColor.indexOf(',') > 0 ? inRangeColor.split(',').map(function(color) { return  color.trim() }) : [inRangeColor];
      visualMap.inRange.color = _inRangeColor;
      visualMap.inRange.symbol = symbolPath ? "path://" + symbolPath : symbol;
      visualMap.inRange.symbolSize = _inRangeColor.map(item => symbolSize);
      visualMap.controller.inRange.color = _inRangeColor;
    }

    if (Boolean(outRangeColor)) {
      const _outOfRangeColor = outRangeColor.indexOf(',') > 0 ? outRangeColor.split(',').map(function(color) { return  color.trim() }) : outRangeColor;
      visualMap.outOfRange.color = _outOfRangeColor;
      visualMap.controller.outOfRange.color = _outOfRangeColor;
    }

    if (visualPosition == 'none') {
      visualMap.show = false;
    } else{
      const visualPositionArr = visualPosition.split('-');
      if (visualPositionArr == 'center' && visualPositionArr[1] == 'right') {
        visualMap[visualPositionArr[1]] = visualPositionArr[1];
      } else {
        visualMap.left = visualPositionArr[1];
      }
      visualMap.top = visualPositionArr[0];
    }

    // const defaultSource = [["position", "value","categroy","longitude", "latitude"], ["湖南建华建材有限公司",10, "类别1", 112.8806033100, 28.6995060100], ["无锡", 10, "类别1"], ["盐城", 10, "类别1"], ["青岛", 10, "类别1"], ["泉州", 10, "类别1"], ["武汉", 10, "类别2"], ["岳阳", 10, "类别2"], ["湖州", 10, "类别2"], ["广州", 10, "类别2"]]
    // const defaultSource = [
    //   ["position", "value", "categroy", "longitude", "latitude", "trade", "area"],
    //   ["长沙",      10,      "掘进",      113.009351,  28.208469, "行业1", "区域3"],
    //   ["长沙",      10,      "掘进",      113.009351,  28.208469, "行业2", "区域2"],
    //   ["北京",      10,      "特装",      116.397947,  39.908173, "行业3", "区域1"],
    //   ["青岛",      10,      "特装",      120.415961,  36.107933, "行业2", "区域2"],
    //   ["太原",      10,      "掘进",      112.522305,  37.835742, "行业1", "区域3"],
    //   ["广州",      10,      "掘进",      113.341527,  23.127041, "行业2", "区域1"],
    //   ["深圳",      10,      "掘进",      114.057795,  22.544230, "行业3", "区域2"],
    //   ["广州",      10,      "掘进",      113.341527,  23.127041, "行业1", "区域3"],
    //   ["重庆",      10,      "特装",      106.548425,  29.554914, "行业2", "区域3"],
    //   ["重庆",      10,      "特装",      106.548425,  29.554914, "行业3", "区域2"],
    //   ["上海",      10,      "掘进",      121.469269,  31.238176, "行业3", "区域1"],
    //   ["成都",      10,      "掘进",      104.088668,  30.710589, "行业2", "区域2"],
    //   ["保山",      10,      "特装",      99.1625980,  25.116213, "行业1", "区域1"],
    // ];

    const myChart = window.echarts.init(this);
    const self = this;
    const _id = self.getAttribute('id');
    var eventName = `call-${_id}`;

    const filterEl = $('.filterOptionContent');
    if (filterEl[0]) {
      $(self)[0].removeChild(filterEl[0]);
    }

    let filterOptions = selectOption ? JSON.parse(selectOption) : [];
    const filterValues = {};
    let filterOriginalSource = [];
    if (filterOptions.length) {
      let selectStyle = `style="`;
      selectStyle += `width: ${selectWidth + 'px'};`;
      selectStyle += `height: ${selectHeight + 'px'};`;
      selectStyle += `background-color: ${selectBgColor};`;
      selectStyle += `border: ${'1px solid ' + selectBorderColor};`;
      selectStyle += `font-size: ${selectFontSize + 'px'};`;
      selectStyle += `color: ${selectFontColor};`;
      selectStyle += `line-height: ${selectHeight + 'px'};`;
      selectStyle += `"`;

      let selectStr = ``;
      selectStr += '<div class="filterOptionContent">';
      for (let i = 0; i < filterOptions.length; i++) {
        selectStr += `<select id="map-filter-${i}" ${selectStyle}>`;

        const {label, value} = filterOptions[i];
        selectStr += `<option value ="">全部${label}</option>`;
        for (let j = 0; j < value.length; j++) {
          selectStr += `<option value ="${value[j]}">${value[j]}</option>`;
        }

        selectStr += '</select>';
      }
      selectStr += '</div>';
      $(self).append(selectStr);

      for (let i = 0; i < filterOptions.length; i++) {
        const {key} = filterOptions[i];
        $(self).find(`#map-filter-${i}`).change(function(){
          filterValues[key] = $(this).val();
          initChart(filterOriginalSource, true);
        });
      }
    }

    const temp = {
      type: "scatter3D",
      coordinateSystem: 'geo3D',
      // symbol: symbol,
      // symbolSize: symbolSize,
      opacity: 1,
      label: {
        show: false,
        formatter: '{b}'
      },
      itemStyle: {
        opacity: 1,
      },
      emphasis: {
        label: {
          show: true,
        }
      }
    };

    const getSeries = function(source) {
      const series = [];
      if (source.length > 0) {
        const _data = convertData(source);
        let formatData=[];
        if(symbolLabel) {
          formatData = _data.map(el => {
            const newData = JSON.parse(JSON.stringify(el));
            newData.label = {
              show: true,
              position: symbolLabelPosition,
              distance: symbolLabelDistance,
              color: mapLabelColor
            }
            return newData
          })
        } else {
          formatData = JSON.parse(JSON.stringify(_data));
        }
        const obj = Object.assign({}, temp, {data: formatData});
        // if (symbolPath) {
        //   obj.symbol = "path://" + symbolPath;
        // }
        series.push(obj);
      }
      return series;
    }

    function initChart(source, isFilter) {
      if (!isFilter) {
        filterOriginalSource = source;
      }

      let filterResult = source;
      const headerKeys = source[0];
      Object.entries(filterValues).forEach(([key, val]) => {
        if (val) {
          const colIndex = headerKeys.indexOf(key);
          if (colIndex !== -1) {
            filterResult = filterResult.filter(row => row[colIndex] === key || row[colIndex] === val);
          }
        }
      });

      myChart.clear();
      const series = getSeries(filterResult);

      const option = {
        title: title,
        legend: legend,
        geo3D: geo3D,
        series: series
      };

      if (useVisual) option.visualMap = visualMap;
      if (Boolean(colors)) option.color = colors;

      myChart.setOption(option);
      myChart.resize();
    }

    var initMap3D = function() {
      window.map3DRegister[_id] = true;
      $.get("/common_static/data/echarts/map/" + mapName + ".json", function (json) {
        echarts.registerMap(mapName, json);
        initChart(defaultData);
      });
    }

    if (window.map3DRegister && window.map3DRegister[_id]) {
      initChart(defaultData);
    } else {
      if (!window.map3DRegister) window.map3DRegister = {};
      initMap3D();
    }

    // const loader = $('<div class="loader"><span class="dot"></span><span class="dot"></span><span class="dot"></span><span class="dot"></span><span class="dot"></span></div>')

    window.addEventListener('resize', function () {
      myChart.resize();
    }, false)
    let hasTransfer = false;
    // 有 dashboardHost 说明是运行模式
    if (window.spSocket) {
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          let _in1Str = _data.data.in1;
          if (_in1Str) {
            const source = JSON.parse(_in1Str);
            const categoriesNew = [];
            source.forEach((data,index) => {
              if(index !== 0 && data[2] !== undefined) {
                const category = data[2].trim();
                if(category !== "" && categoriesNew.indexOf(category) === -1) {
                  categoriesNew.push(category)
                }
              }
            });
            if(!hasTransfer) {
              hasTransfer = true
              initChart(source);
              if (useVisual) {
                myChart.setOption({
                  visualMap: {categories: categoriesNew}
                });
              }
            } else {
              myChart.setOption({
                series: getSeries(source),
              })
              if (useVisual) {
                myChart.setOption({
                  visualMap: {categories: categoriesNew}
                });
              }
            }
          }
        }
      });
    }

    Boolean(dataSource) && $.get(dataSource, function (ds) {
      myChart.hideLoading();
      initChart(JSON.parse(ds))
    });
  },

  onViewInit() {
    this.updateScript();
    const evn = echartsBasicListen + `
    change:defaultData
    change:useVisual
    change:categories
    change:inRangeColor
    change:useForTextColor
    change:outRangeColor
    change:visualPosition
    change:visualDimension
    change:visualItemWidth
    change:visualItemHeight
    change:visualItemAlign
    change:symbolLabel
    change:symbolLabelPosition
    change:symbolLabelDistance
    change:mapName
    change:leftTopRightBottom
    change:mapColor
    change:mapBorderColor
    change:mapLabel
    change:mapLabelColor
    change:selectOption
    change:selectWidth
    change:selectHeight
    change:selectFontSize
    change:selectFontColor
    change:selectBgColor
    change:selectBorderColor
    change:symbol
    change:symbolSize
    change:distance
    change:symbolPath
    change:alpha
    change:beta
    change:center`;
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
    this.listenTo(this.em, 'update:component:style:height update:component:style:width', throttle.bind(this, this.updateScript.bind(this)));
  }
}
