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

export default {

  // 组件名称
  name: mapScatter,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${mapScatter}" class="${mapScatter}"></div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${mapScatter} {
          position: absolute;
          border-radius: 5px;
          border-style: solid;
          border-width: 1px;
          border-color: transparent;
          padding: 10px;
          width: 600px;
          height: 400px;
        }
        .${mapScatter} .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="M938.667 292.978v-73.956h-5.69l-19.91 22.756c-2.845 2.844-5.69 2.844-8.534 2.844H896c-2.844 0-8.533-2.844-8.533-5.689l-14.223-11.377c-2.844-2.845-5.688-5.69-8.533-5.69h-17.067c-2.844 0-8.533-2.844-11.377-5.688l-31.29-45.511c-2.844-2.845-5.688-5.69-8.533-5.69l-19.91-2.844h-5.69l-31.288 11.378v17.067l-5.69 36.978c0 2.844-2.844 5.688-2.844 5.688l-5.689 5.69c-2.844 2.844-5.689 2.844-8.533 2.844h-5.689c-5.689 0-11.378 2.844-11.378 8.533l-5.689 14.222c-2.844 8.534 2.845 17.067 11.378 17.067h14.222l11.378-8.533 8.534 5.689c5.688 5.688 2.844 17.066-5.69 19.91l-25.6 8.534v17.067h-25.6l-5.688 17.066-22.756-2.844c-5.689 0-8.533 2.844-11.378 5.689l-5.688 8.533 8.533 8.533-22.756 25.6c-2.844 2.845-5.689 2.845-8.533 2.845h-34.133c-2.845 0-5.69 0-8.534 2.844l-8.533 8.534c-2.844 2.844-5.689 2.844-8.533 2.844h-25.6c-2.845 0-5.69 0-8.534-2.844l-17.066-14.223c-2.845 0-2.845-2.844-5.69-2.844l-62.577-2.844c-2.844 0-5.689-2.845-8.533-5.69l-34.134-45.51c-2.844-2.845-5.689-5.69-8.533-5.69h-2.844c-5.69 0-11.378-5.688-11.378-11.377v-19.911l-2.845-17.067c0-2.844-2.844-5.689-5.689-8.533h-19.91c-2.845 0-5.69-2.845-5.69-5.69l-5.688-17.066h-14.223L307.2 256h-14.222v14.222h-28.445c-2.844 0-8.533 2.845-8.533 5.69l-11.378 17.066c-2.844 2.844-5.689 5.689-11.378 5.689h-14.222c-5.689 0-11.378 5.689-11.378 11.377v17.067c0 2.845 0 5.689-2.844 5.689l-8.533 14.222c-2.845 2.845-2.845 5.69-8.534 5.69l-31.289 8.532H108.09c-2.845 0-5.689 2.845-8.533 2.845l-8.534 11.378c-5.689 8.533-5.689 11.377-5.689 14.222v14.222h11.378v45.511c0 2.845 2.845 5.69 5.689 8.534l19.911 17.066c2.845 2.845 2.845 2.845 2.845 5.69l5.688 19.91V537.6h-11.377v22.756c0 2.844 2.844 5.688 2.844 8.533l25.6 22.755h14.222l56.89 56.89 2.844 2.844 48.355 19.91 8.534-11.377h17.066c5.69 0 8.534 2.845 11.378 5.689l8.533 17.067c2.845 2.844 5.69 5.689 11.378 5.689h14.222c2.845 0 2.845 0 5.69-2.845l28.444-17.067c2.844-2.844 8.533-2.844 11.377 0l25.6 11.378v-11.378h14.223l5.689 17.067v25.6c0 2.845 0 5.689-2.845 8.533l-14.222 14.223v14.222l11.378 2.844c2.844 0 8.533 2.845 8.533 8.534l2.844 8.533v19.911l28.445 19.911c2.844 2.845 5.689 2.845 5.689 2.845h5.689c5.689 0 11.377-5.69 11.377-11.378s5.69-11.378 11.378-11.378h28.445c2.844 0 5.689 0 8.533-2.844l8.533-5.69c5.69-2.844 11.378-2.844 17.067 2.845l19.911 22.756c2.845 2.844 5.689 5.689 8.533 5.689h34.134l2.844 14.222-19.91 22.755v14.223l14.221 8.533c5.69 2.844 14.223 0 17.067-5.689l14.222-19.911c2.845-2.844 2.845-5.689 2.845-8.533l-2.845-19.911c0-5.69 2.845-14.223 8.534-14.223l19.91-5.689h5.69l11.377 2.845 14.223-5.689 2.844-14.222c0-5.69 5.689-8.534 8.533-8.534l17.067-5.688c2.844 0 2.844 0 5.689-2.845l54.044-48.355c2.845-2.845 2.845-2.845 2.845-5.69l8.533-42.666c0-2.844 2.845-5.689 5.689-8.533l14.222-8.534c2.845-2.844 5.69-8.533 5.69-11.377l-5.69-51.2c0-2.845-2.844-5.69-5.689-8.534l-11.377-8.533c-2.845-2.845-5.69-5.689-5.69-8.533l-2.844-11.378c0-2.845-2.844-5.69-5.689-8.534l-19.91-17.066c-5.69-2.845-5.69-11.378-2.845-17.067l11.378-19.911c0-2.844 2.844-2.844 5.688-5.689l22.756-8.533v-14.222h-22.756c-2.844 0-8.533 2.844-11.377 5.688l-8.534 11.378-8.533 8.534-2.844-14.223-19.912-5.689 48.356-62.577 5.689 8.533v17.067c0 2.844 0 8.533 2.844 8.533l2.845 2.844c5.689 2.845 11.378 2.845 17.066 0l39.823-39.822c2.844-2.844 2.844-5.689 2.844-11.378l-2.844-11.377 25.6-2.845c2.844 0 5.689-2.844 8.533-2.844l22.756-22.756c2.844-2.844 5.688-8.533 2.844-14.222l-14.222-31.289 11.378-11.378h19.91zM799.289 762.31c0 2.845-2.845 2.845-2.845 5.689v22.756c0 2.844 0 5.688 2.845 8.533l11.378 17.067 8.533-11.378c0-2.845 2.844-2.845 2.844-5.69l5.69-59.732H813.51L799.29 762.31z" data-spm-anchor-id="a313x.7781069.0.i25" class="selected"></path><path d="M668.444 412.444c-71.11 0-128 56.89-128 128 0 110.934 128 201.956 128 201.956s128-91.022 128-201.956c0-71.11-56.888-128-128-128z m0 182.045c-31.288 0-54.044-25.6-54.044-54.045 0-31.288 25.6-54.044 54.044-54.044s54.045 25.6 54.045 54.044c0 31.29-22.756 54.045-54.045 54.045z" fill="#C3C3D5"></path></svg>
        <div class="gjs-block-label">散点地图</div>
      `,
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '散点地图',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/c7b9873d-0e3e-4263-9e70-3a703d5bd8d2?# 《散点地图》',
      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 {
      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: 'zoom',
          label: '放大镜',
          type: 'number',
          changeProp: 1,
          min: 0,
          step: 0.1
        }, {
          name: 'aspectScale',
          label: '长宽比',
          changeProp: 1,
          type: 'number',
          step: 0.1
        }, {
          name: 'useScale',
          label: '启用滚轮缩放',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'useMove',
          label: '启用鼠标拖动',
          changeProp: 1,
          type: 'checkbox'
        }, {
          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: 'visualDimension',
        //   label: '视觉映射维度',
        //   changeProp: 1,
        //   min: 0,
        //   step: 1,
        //   type: 'number'
        // }, 
        {
          name: 'categories',
          label: '枚举型数据',
          changeProp: 1
        }, {
          name: 'inRangeColor',
          label: '范围内颜色',
          changeProp: 1
        }, {
          name: 'outRangeColor',
          label: '范围外颜色',
          changeProp: 1,
          type: 'color'
        }, {
          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: 'csv',
          label: '示例数据',
          changeProp: 1,
          type: 'csvDownload',
          preFileName: '散点地图',
          //datas: [["position", "value","categroy","longitude", "latitude"], ["湖南建华建材有限公司",10, "类别1", 112.8806033100, 28.6995060100], ["无锡", 10, "类别1"], ["盐城", 10, "类别1"], ["青岛", 10, "类别2"], ["泉州", 10, "类别2"]]
          datas: [["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"],]
        },
        {
          name: 'defaultData',
          changeProp: 1,
          type: 'hide'
        }
      ],
      'defaultData':JSON.stringify([
        ["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"],
      ]).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,
      'useScale':false,
      'useMove':false,
      'visualPosition': 'center-right',
      // 'visualDimension': 2,
      //'categories': '类别1,类别2',
      'categories': '掘进,特装',
      'inRangeColor': '#0084ff, #339cff, #66b5ff, #99ceff, #cce6ff',
      'outRangeColor': '#ddd',
      'zoom': 1,
      'aspectScale': 0.75,
      'leftTopRightBottom': 'auto,auto,auto,auto',
      'symbol': 'circle',
      'symbolPath': null,
      'symbolSize': '40',
      'symbolLabel': false,
      'symbolLabelPosition': 'inside',
      'color': '#ff962e,#ff5c5f,#70cc62,#86d1ca'
    }
  },

  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 ]}';
    const useVisual = Boolean('{[ useVisual ]}');
    const visualPosition = ('{[ visualPosition ]}').toString();
    const useScale = Boolean('{[ useScale ]}');
    const useMove = Boolean('{[ useMove ]}');
    // const visualDimension = Number('{[ visualDimension ]}');
    let categories = ('{[ categories ]}').toString();
    const inRangeColor = '{[ inRangeColor ]}';
    const outRangeColor = ('{[ outRangeColor ]}').toString();
    const zoom = Boolean('{[ zoom ]}') ? parseFloat('{[ zoom ]}') : 0;
    const aspectScale = Boolean('{[ aspectScale ]}') ? parseFloat('{[ aspectScale ]}') : 0;
    let leftTopRightBottom = ('{[ leftTopRightBottom ]}').toString();
    const symbol = ('{[ symbol ]}').toString();
    const symbolPath = Boolean('{[ symbolPath ]}') && ('{[ symbolPath ]}').toString();
    let symbolSize = ('{[ symbolSize ]}').toString();
    const symbolLabel = Boolean('{[ symbolLabel ]}');
    const symbolLabelPosition = ('{[ symbolLabelPosition ]}').toString();
    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(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],data[i][cityDimension],data[i][valueDimension],data[i][visualDimension]]
              });
            }
          }
        },
        error: function () {
          console.log('fetch geoCoordMap error')
        }
      });
      return res;
    };

    const geo = {
      map: mapName,
      roam: false,
      zoom: zoom,
      aspectScale: aspectScale,
      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
        }
      }
    }

    const visualMap = {
      type: 'piecewise',
      dimension: visualDimension + 2, // 数据转换后 数组最前面添加经、纬度数据
      categories: categories,
      inRange: {},
      outOfRange: {},
      controller: {
        inRange: {},
        outOfRange: {}
      },
      textStyle: {
        color: fontColor
      }
    }


    if (Boolean(inRangeColor)) {
      const _inRangeColor = inRangeColor.indexOf(',') > 0 ? inRangeColor.split(',').map(function(color) { return  color.trim() }) : [inRangeColor];
      visualMap.inRange.color = _inRangeColor;
      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, "类别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 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: "scatter",
      coordinateSystem: 'geo',
      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,
              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];
      const filterOptionNew = Object.entries(filterValues);
      filterOptionNew.forEach((option) => {
        const key = option[0];
        const val = option[1];
        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,
        geo: geo,
        series: series
      };

      if (useVisual) option.visualMap = visualMap;
      if (Boolean(colors)) option.color = colors;
      if (useScale&&!useMove) option.geo.roam = 'scale';
      if (useMove&&!useScale) option.geo.roam = 'move';
      if (useScale&&useMove) option.geo.roam = true;
      if (!useScale&&!useMove) option.geo.roam = false;
      
      myChart.setOption(option);
      myChart.resize();
    }

    var initMap3D = function() {
      window.mapRegister = true;
      $.get("/common_static/data/echarts/map/" + mapName + ".json", function (json) {
        echarts.registerMap(mapName, json);
        initChart(defaultData);
      });
    }
  
    if (window.mapRegister) {
      initChart(defaultData);
    } else {
      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) {
      var eventName = `call-` + self.getAttribute('id');
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          let _in1Str = _data.data.in1;
          if (_in1Str) {
            const source = JSON.parse(_in1Str);
            // 数据格式-> [["position", "value","categroy"], ["无锡", 10, "类别4"], ["盐城", 10, "类别1"], ["青岛", 10, "类别3"], ["泉州", 10, "类别2"]]
            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(filterOptions.length > 0) {
              //hasTransfer = true
              initChart(source);
              myChart.setOption({
                visualMap: {categories: categoriesNew}
              });
            } else {
              // initChart(filterOriginalSource,true);
              myChart.setOption({
                series: getSeries(source),
                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:useScale
    change:useMove
    change:categories
    change:inRangeColor
    change:outRangeColor
    change:visualPosition
    change:visualDimension
    change:symbolLabel
    change:symbolLabelPosition
    change:mapName change:mapColor change:mapBorderColor change:mapLabel change:mapLabelColor change:symbol change:symbolSize change:symbolPath change:zoom change:aspectScale change:leftTopRightBottom
    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)));
  }
}
