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

export default {

  // 组件名称
  name: map2DPopup,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${map2DPopup}" class="${map2DPopup}"></div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${map2DPopup} {
          position: absolute;
          border-radius: 5px;
          border-style: solid;
          border-width: 1px;
          border-color: transparent;
          padding: 10px;
          width: 1040px;
          height: 780px;
        }
        .${map2DPopup} .mapChart{
          width: 100%;
          height: 100%;
        }
        .${map2DPopup} .xly-box-1 .seperate-line, .${map2DPopup} .xly-box-2 .seperate-line {
          width: 100%;
          height: 1px;
          border: 1px solid rgba(255,255,255,1);
          margin-bottom: 5px;
        }
        .${map2DPopup} .xly-box-1 {
          z-index: 100;
          padding: 10px;
          position: absolute;
          width: 250px;
          height: 200px;
          background:rgba(27,27,27,0.8);
          top: 250px;
          left: 200px;
        }
        .${map2DPopup} .xly-box-1 .popup-title-1, .${map2DPopup} .xly-box-2 .popup-title-2 {
          position: relative;
          width: 100%;
          height: 34px;
          padding-left: 20px;
          font-size:16px;
          color:#C8E8FF;
          line-height:34px;
        }
        .${map2DPopup} .xly-box-1 .popup-list {
          position: relative;
          width: 100%;
          height: 140px;
          font-size:12px;
          color:#FFFFFF;
          line-height:30px;
          overflow: auto;
        }
        .${map2DPopup} .xly-box-1 .popup-list ul {
          margin: 0;
          padding: 0;
          list-style: none;
        }
        .${map2DPopup} .xly-box-1 .popup-list ul > li {
          margin: 0;
          padding: 0;
          display: flex;
          align-items: center;
        }
        .${map2DPopup} .xly-box-1 .popup-list ul li .link:hover {
          color: blue;
          text-decoration:underline;
          cursor: pointer;
        }
        .${map2DPopup} .xly-box-2 {
          z-index: 100;
          padding: 10px;
          position: absolute;
          width: 320px;
          height: auto;
          background:rgba(27,27,27,0.8);
          top: 250px;
          left: 470px;
        }
        .${map2DPopup} .popup-close {
          position: absolute;
          width: 30px;
          height: 30px;
          line-height: 30px;
          right: 10px;
          top: 10px;
          color: #FFFFFF;
          font-size: 9px;
          text-align: center;
          cursor: pointer;
        }
        .${map2DPopup} .popup-close:hover {
          background-color: rgba(0,0,0,0.2); 
        }
        .${map2DPopup} .xly-box-2 .popup-list{
          position: relative;
          width: 100%;
          height: 250px;
          font-size:12px;
          color:#FFFFFF;
          line-height:30px;
          overflow: auto;
        }
        .${map2DPopup} .xly-box-2 .popup-list .list-detail{
          display: flex;
          flex-wrap: wrap;
        }
        ::-webkit-scrollbar-track-piece {
          //滚动条凹槽的颜色，还可以设置边框属性
          background-color: transparent;
        }
    
        ::-webkit-scrollbar {
          //滚动条的宽度
          display: auto;
          width: 5px;
        }
    
        ::-webkit-scrollbar-thumb {
          //滚动条的设置
          background-color: rgba(255, 255, 255, 0.1);
        }
    
        ::-webkit-scrollbar-thumb:hover {
          background-color: rgba(255, 255, 255, 0.1);
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: `
      <svg class="gjs-block-svg" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" ><path d="M781.981888 1014.033538C649.277769 945.497049 431.312619 990.61918 298.608501 972.93895 165.904382 955.25872 80.23377 832.725854 35.111639 706.301971-80.32183 383.00634 113.136746 295.287826 270.483965 302.387223 427.899447 309.691411 362.093496 148.180122 582.720919 27.558632 803.348343-93.062859 862.874059 217.126192 838.367485 287.574057 813.792648 358.021923 796.863316 425.32967 963.357836 601.858915 1129.852355 778.456422 914.686006 1082.706555 781.981888 1014.033538ZM891.408175 606.432565C745.66574 458.778754 743.413046 396.044657 768.397464 329.692597 789.900446 272.214785 777.886081 13.22331 589.478999 113.229243 401.071917 213.30344 457.730569 374.746465 324.207289 370.650659 190.615746 366.554852 7.601475 440.279363 102.28286 701.250477 139.281642 803.236049 225.976205 884.810855 338.474347 897.644381 450.972489 910.54617 634.259813 878.735409 746.211847 932.868314 858.163882 987.069481 1031.0069 747.874403 891.408175 606.432565ZM650.09693 792.51869C581.014333 766.646848 565.723324 679.337914 586.270618 607.388253 606.886175 535.302065 543.947288 435.773976 514.730537 379.866222 485.58205 323.753678 553.708959 197.671113 626.068201 178.352561 743.549573 146.95138 684.365175 331.7405 689.280142 455.092528 694.331636 578.444556 870.314773 658.79062 868.47166 734.28998 866.628548 809.789339 719.111263 818.458796 650.09693 792.51869ZM471.997627 693.058865C411.379696 748.01093 334.105487 776.886363 255.943853 750.604941 177.918747 724.255255 125.902009 596.124786 186.519939 541.991882 310.076758 431.541643 323.04681 547.179903 423.803641 498.098493 524.492209 449.085346 532.547294 638.106799 471.997627 693.058865Z" ></path></svg>
        <div class="gjs-block-label">下钻热力弹框平面地图</div>
      `,
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '下钻热力弹框平面地图',
      icon: 'globe',
      inPorts: [
        {
          uuid: 'in1',
          subType: 'json',
          description: {
            zh_CN: '输入1'
          }
        },
        {
          uuid: 'in2',
          subType: 'all',
          description: {
            zh_CN: '弹框筛选数据1'
          }
        },
        {
          uuid: 'in3',
          subType: 'all',
          description: {
            zh_CN: '弹框筛选数据2'
          }
        }
      ]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: map2DPopup,
      resizable: true,
      dmode: 'absolute',
      childrenSelectable: false,
      highlightable: false,
      droppable: false,
      traits: [
        {
          name: 'categories',
          label: '枚举型数据',
          changeProp: 1
        },
        {
          name: 'echartDataURL',
          label: 'echart地图数据获取地址',
          changeProp: 1,
        },
        {
          name: 'mapBorderColor',
          label: '地图边框颜色',
          type: 'color',
          changeProp: 1,
        },
        {
          name: 'mapBorderSize',
          label: '地图边框粗细',
          type: 'number',
          changeProp: 1,
        },
        {
          name: 'mapColor',
          label: '地图颜色',
          type: 'color',
          changeProp: 1,
        },
        {
          name: 'mapLabelShow',
          label: '地图标签显示',
          type: 'checkbox',
          changeProp: 1,
        },
        {
          name: 'mapLabelColor',
          label: '地图标签字体颜色',
          type: 'color',
          changeProp: 1
        },
        {
          name: 'mapLabelSize',
          label: '地图标签字体大小',
          type: 'number',
          changeProp: 1
        },
        {
          name: 'mapEmphasisColor',
          label: '鼠标划过地图颜色',
          type: 'color',
          changeProp: 1,
        },
        {
          name: 'inRangeShow',
          label: '热力区间显示',
          type: 'checkbox',
          changeProp: 1,
        },
        {
          name: 'inRangeLabelSize',
          label: '热力区间字体大小',
          type: 'number',
          changeProp: 1,
        },
        {
          name: 'inRangeLabelColor',
          label: '热力区间字体颜色',
          type: 'color',
          changeProp: 1
        },
        {
          name: 'inRangeDataShow',
          label: '热力区间最大最小值显示',
          type: 'checkbox',
          changeProp: 1,
        },
        {
          name: 'inRangeColors',
          label: '热力区间颜色',
          changeProp: 1,
        },{
          name: 'inRangePosition',
          label: '热力区间位置',
          changeProp: 1
        },{
          name: 'inRangeLabel',
          label: '热力区间文本',
          changeProp: 1
        },
        {
          name: 'pinColor',
          label: '气泡颜色',
          changeProp: 1,
          type: 'color'
        },
        {
          name: 'pinMaxSize',
          label: '气泡最大显示',
          changeProp: 1,
          type: 'number'
        },
        {
          name: 'pinMinSize',
          label: '气泡最小显示',
          changeProp: 1,
          type: 'number'
        },
        {
          name: 'pinFontSize',
          label: '气泡字体大小',
          changeProp: 1,
          type: 'number'
        },
        {
          name: 'pinFontColor',
          label: '气泡字体颜色',
          changeProp: 1,
          type: 'color'
        },
        {
          name: 'scatterLabelShow',
          label: '数据点标签显示',
          changeProp: 1,
          type: 'checkbox'
        },
        {
          name: 'scatterLabelShowPosition',
          label: '数据点标签显示位置',
          changeProp: 1,
          type: 'select',
          options: [
            { id: 'top', name: '顶部' },
            { id: 'bottom', name: '底部' },
            { id: 'left', name: '左边' },
            { id: 'right', name: '右边' },
            { id: 'inside', name: '内部' },
          ]
        },
        {
          name: 'scatterLabelSize',
          label: '数据点标签字体大小',
          changeProp: 1,
          type: 'number',
        },
        {
          name: 'scatterColor',
          label: '数据点颜色',
          changeProp: 1,
          type: 'color'
        },
        {
          name: 'scatterMaxSize',
          label: '数据点最大显示',
          changeProp: 1,
          type: 'number'
        },
        {
          name: 'scatterMinSize',
          label: '数据点最小显示',
          changeProp: 1,
          type: 'number'
        },{
          name: 'top5ScatterLabelShow',
          label: 'top5数据点标签显示',
          changeProp: 1,
          type: 'checkbox'
        },
        {
          name: 'top5ScatterLabelShowPosition',
          label: 'top5数据点标签显示位置',
          changeProp: 1,
          type: 'select',
          options: [
            { id: 'top', name: '顶部' },
            { id: 'bottom', name: '底部' },
            { id: 'left', name: '左边' },
            { id: 'right', name: '右边' },
            { id: 'inside', name: '内部' },
          ]
        },
        {
          name: 'top5ScatterLabelSize',
          label: 'top5数据点标签字体大小',
          changeProp: 1,
          type: 'number'
        },
        {
          name: 'top5ScatterColor',
          label: 'top5数据点颜色',
          changeProp: 1,
          type: 'color'
        },{
          name: 'top5ScatterMaxSize',
          label: 'top5数据点最大显示',
          changeProp: 1,
          type: 'number'
        },
        {
          name: 'top5ScatterMinSize',
          label: 'top5数据点最小显示',
          changeProp: 1,
          type: 'number'
        },
        {
          name: 'showPopup',
          label: '显示弹框',
          changeProp: 1,
          type: 'checkbox'
        },
        {
          name: 'csv',
          label: '输入1示例数据',
          changeProp: 1,
          type: 'csvDownload',
          preFileName: '2D地图',
          datas: [
            ["position", "value","categroy","longitude", "latitude", "province"],
            ["南京市", 100, '掘进', ,, "江苏省"],
            ["南京市", 40, '特装', ,, "江苏省"],
            ["无锡", 30, '掘进', , , "江苏省"],
            ["无锡", 4, '特装', , , "江苏省"],
            ["常州市", 50, '特装', , , "江苏省"],
            ["静安区", 3, '掘进', , , "上海市"],
            ["静安区", 4, '特装', , , "上海市"],
          ]
        },
        {
          name: 'defaultData',
          changeProp: 1,
          type: 'hide'
        }
      ],
      'defaultData':JSON.stringify([
        ["position", "value","categroy","longitude", "latitude", "province"],
        ["南京市", 100, '掘进', ,, "江苏省"],
        ["南京市", 40, '特装', ,, "江苏省"],
        ["无锡", 30, '掘进', , , "江苏省"],
        ["无锡", 4, '特装', , , "江苏省"],
        ["常州市", 50, '特装', , , "江苏省"],
        ["静安区", 3, '掘进', , , "上海市"],
        ["静安区", 4, '特装', , , "上海市"]
      ]).replace(/\"/g, "\\\""),
      'echartDataURL': 'https://suanpan-public.oss-cn-shanghai.aliyuncs.com/echarts/map/',
      'categories': '',
      'mapBorderColor': '#22272e',
      'mapBorderSize': 2,
      'mapColor': '#323c48',
      'mapEmphasisColor': '#2B91B7',
      'mapLabelShow': false,
      'mapLabelColor': '#fff',
      'mapLabelSize': 14,
      'inRangeColors': '#00467F,#61c992,#e3c525,#c43632',
      'inRangePosition': 'left, center',
      'inRangeLabel': '高, 低',
      'inRangeShow': true,
      'inRangeLabelSize': 14,
      'inRangeLabelColor': '#fff',
      'inRangeDataShow': true,
      'pinMaxSize': 60,
      'pinMinSize': 20,
      'pinColor': '#F62157',
      'pinFontSize': 14,
      'pinFontColor': '#fff',
      'scatterLabelShow': true,
      'scatterLabelShowPosition': 'right',
      'scatterLabelSize': 14,
      'scatterColor': '#05c3fa',
      'scatterMaxSize': 15,
      'scatterMinSize': 4,
      'top5ScatterLabelShow': true,
      'top5ScatterLabelShowPosition': 'right',
      'top5ScatterColor': '#05c3fa',
      'top5ScatterLabelSize': 14,
      'top5ScatterMaxSize': 15,
      'top5ScatterMinSize': 4,
      'showPopup': true
    }
  },

  onModelScript() {
    const dataSource = '{[ dataSource ]}';
    const bgColor = '{[ bgColor ]}';
    const borderColor = '{[ borderColor ]}';
    const fontColor = '{[ fontColor ]}';
    let colors = '{[ colors ]}';
    let legendPosition = ('{[ legendPosition ]}').toString();
    const legendOrient = ('{[ legendOrient ]}').toString();
    const legendIcon = ('{[ legendIcon ]}').toString();
    const legendItemGap = Number('{[ legendItemGap ]}');
    const legendItemWidth = Number('{[ legendItemWidth ]}');
    const legendItemHeight = Number('{[ legendItemHeight ]}');
    const legendFontSize = Number('{[ legendFontSize ]}');
    const legendFontFamily = ('{[ legendFontFamily ]}').toString();
    const titleText = '{[ titleText ]}';
    const titleColor = '{[ titleColor ]}';
    const titlePosition = ('{[ titlePosition ]}').toString();
    // map2DPopup unique attributes
    let categories = ('{[ categories ]}').toString();
    const echartDataURL = ('{[ echartDataURL ]}').toString();
    const mapBorderColor = ('{[ mapBorderColor ]}').toString();
    const mapBorderSize = Number('{[ mapBorderSize ]}');
    const mapColor = ('{[ mapColor ]}').toString();
    const mapEmphasisColor = ('{[ mapEmphasisColor ]}').toString();
    const mapLabelShow = Boolean('{[ mapLabelShow ]}');
    const mapLabelColor = ('{[ mapLabelColor ]}').toString();
    const mapLabelSize = Number('{[ mapLabelSize ]}');
    let inRangeColors = ('{[ inRangeColors ]}').toString();
    let inRangePosition = ('{[ inRangePosition ]}').toString();
    let inRangeLabel = ('{[ inRangeLabel ]}').toString();
    const inRangeShow = Boolean('{[ inRangeShow ]}');
    const inRangeLabelSize = Number('{[ inRangeLabelSize ]}');
    const inRangeLabelColor = ('{[ inRangeLabelColor ]}').toString();
    const inRangeDataShow = Boolean('{[ inRangeDataShow ]}');
    const pinColor = ('{[ pinColor ]}').toString();
    const pinMaxSize = Number('{[ pinMaxSize ]}');
    const pinMinSize = Number('{[ pinMinSize ]}');
    const pinFontSize = Number('{[ pinFontSize ]}');
    const pinFontColor = ('{[ pinFontColor ]}').toString();
    const scatterLabelShow = Boolean('{[ scatterLabelShow ]}');
    const scatterLabelShowPosition = ('{[ scatterLabelShowPosition ]}').toString();
    const scatterLabelSize = Number('{[ scatterLabelSize ]}');
    const scatterColor = ('{[ scatterColor ]}').toString();
    const scatterMaxSize = Number('{[ scatterMaxSize ]}');
    const scatterMinSize = Number('{[ scatterMinSize ]}');
    const top5ScatterLabelShow = Boolean('{[ top5ScatterLabelShow ]}');
    const top5ScatterLabelShowPosition = ('{[ top5ScatterLabelShowPosition ]}').toString();
    const top5ScatterColor = ('{[ top5ScatterColor ]}').toString();
    const top5ScatterLabelSize = Number('{[ top5ScatterLabelSize ]}');
    const top5ScatterMaxSize = Number('{[ top5ScatterMaxSize ]}');
    const top5ScatterMinSize = Number('{[ top5ScatterMinSize ]}');
    const showPopup = Boolean('{[ showPopup ]}');
    let defaultData = JSON.parse('{[ defaultData ]}'.replace(/\\\"/g, "\""));

    let mapName = 'china';
    const cityDimension = 0;
    const valueDimension = 1;
    const visualDimension = 2;
    const longitudeDimension = 3;
    const latitudeDimension = 4;
    const provinceDimension = 5;
    let geoCoordMap = {};
    let provinceData = new Array();
    let initData;
    let legendSelected = 0;

    var provinces = {
      'china': 'china',
      '上海': 'shanghai',
      '河北': 'hebei',
      '山西': 'shanxi',
      '内蒙古': 'neimenggu',
      '辽宁': 'liaoning',
      '吉林': 'jilin',
      '黑龙江': 'heilongjiang',
      '江苏': 'jiangsu',
      '浙江': 'zhejiang',
      '安徽': 'anhui',
      '福建': 'fujian',
      '江西': 'jiangxi',
      '山东': 'shandong',
      '河南': 'henan',
      '湖北': 'hubei',
      '湖南': 'hunan',
      '广东': 'guangdong',
      '广西': 'guangxi',
      '海南': 'hainan',
      '四川': 'sichuan',
      '贵州': 'guizhou',
      '云南': 'yunnan',
      '西藏': 'xizang',
      '陕西': 'shanxi1',
      '甘肃': 'gansu',
      '青海': 'qinghai',
      '宁夏': 'ningxia',
      '新疆': 'xinjiang',
      '北京': 'beijing',
      '天津': 'tianjin',
      '重庆': 'chongqing',
      '香港': 'xianggang',
      '澳门': 'aomen',
      '台湾': 'taiwan'
    };

    var changeStringToArray = function(attribute) {
      let data = JSON.parse(JSON.stringify(attribute));
      if (data.indexOf(',') > -1) {
        data = data.split(',').map(function (item) {
          return item.trim()
        });
      } else {
        data = [data, data];
      }
      return data;
    }

    // set common attributes
    Boolean(bgColor) ? $(this).css({ backgroundColor: bgColor }) : $(this).css({ backgroundColor: 'transparent' });
    Boolean(borderColor) ? $(this).css({ borderColor: borderColor }) : $(this).css({ borderColor: 'transparent' });
    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
      }
    };
    if (colors.indexOf(',') > -1) {
      colors = colors.split(',').map(item => item.trim())
    } else if (Boolean(colors)) {
      colors = [colors]
    }
    const legendShow = legendOrient !== 'null';
    const legend = {
      show: legendShow,
      type: 'scroll',
      icon: legendIcon,
      itemGap: legendItemGap,
      itemWidth: legendItemWidth,
      itemHeight: legendItemHeight,
      textStyle: {
        fontFamily: legendFontFamily,
        fontSize: legendFontSize,
        color: fontColor,
      },
    };
    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;
    }

    // set unique attributes
    inRangePosition = changeStringToArray(inRangePosition);
    inRangeLabel = changeStringToArray(inRangeLabel);
    let visualMap = {
      show: inRangeShow,
      left: inRangePosition[0],
      top: inRangePosition[1],
      text: inRangeLabel,
      calculable: inRangeDataShow,
      inRange: {},
      textStyle: {
        fontSize: inRangeLabelSize,
        color: inRangeLabelColor
      }
    };
    if (inRangeColors.indexOf(',') > -1) {
      inRangeColors = inRangeColors.split(',').map(item => item.trim())
    } else if (Boolean(inRangeColors)) {
      inRangeColors = [inRangeColors]
    }
    if (inRangeColors.length > 0) {
      Object.assign(visualMap.inRange, { color: inRangeColors });
    }
    if (categories.indexOf(',') > 0) {
      categories = categories.split(',').map(function(item) { return item.trim() })
    } else {
      if (categories !== '') {
        categories = [categories];
      } else {
        categories = []
      }
    }

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

    const canvasEl = $(self).find('.mapChart')[0];
    const selfWidth = $(self).css('width');
    const selfHeight = $(self).css('height');

    //tab exit
    if(selfWidth && selfWidth.indexOf('px') !== '-1') {
      $(canvasEl).css("width", selfWidth);
    }
    if(selfHeight && selfHeight.indexOf('px') !== '-1') {
      $(canvasEl).css("height", selfHeight);
    }
    
    const myChart = window.echarts.init(canvasEl);

    const popupEl = $(self).find('.xly-box-1')[0];
    const popupElTitle = $(popupEl).find('.popup-title-1')[0];
    const popupElList = $(popupEl).find('.popup-list')[0];
    const popupElClose = $(popupEl).find('.popup-close')[0];

    const popupDetailEl = $(self).find('.xly-box-2')[0];
    const popupDetailElTitle = $(popupDetailEl).find('.popup-title-2')[0];
    const popupDetailElList = $(popupDetailEl).find('.popup-list')[0];
    const popupDetailElClose = $(popupDetailEl).find('.popup-close')[0];

    
    var closePopupDetail = function() {
      popupDetailEl.style.display = "none";
    }

    if(popupDetailElClose) {
      popupDetailElClose.removeEventListener("click", closePopupDetail.bind(this), false);
      popupDetailElClose.addEventListener("click", closePopupDetail.bind(this), false);
    }

    var closePopup = function() {
      popupEl.style.display = "none";
      popupDetailEl.style.display = "none";
    }

    if(popupElClose) {
      popupElClose.removeEventListener("click", closePopup.bind(this), false);
      popupElClose.addEventListener("click", closePopup.bind(this), false);
    }    

    var getProvinceData = function(data) {
      let provinces = new Array();
      data.map((val, index) => {
        if (index !== 0) {
          let hasProvince = provinces.findIndex(name => name === val[provinceDimension]);
          if (hasProvince === -1) {
            provinceData.push({
              name: val[provinceDimension],
              value: val[valueDimension],
              tooltip: [{ name: val[visualDimension], value: val[valueDimension]}]
            });
            provinces.push(val[provinceDimension]);
          } else {
            provinceData[hasProvince].value += val[valueDimension];
            let hasCategroy = false;
            provinceData[hasProvince].tooltip.map(tooltipData => {
              if (tooltipData.name === val[visualDimension]) {
                tooltipData.value += val[valueDimension];
                hasCategroy = true;
              }
            });
            if (!hasCategroy) {
              provinceData[hasProvince].tooltip.push({ name: val[visualDimension], value: val[valueDimension]});
            }
          }
        }
      });
    };

    var getCityData = function (data, province){
      let arr = new Array();
      categories.map(val => {
        arr.push([]);
      });
      data.map((val, index) => {
        if (index !== 0) {
          const cityName = Object.keys(geoCoordMap).filter(key => key.indexOf(val[cityDimension]) != -1);
          if (val[provinceDimension].indexOf(province) !== -1 || province.indexOf(val[provinceDimension]) !== -1) {
            const hasCategroy = categories.findIndex(category => category === val[visualDimension]);
            let res;
            if ( cityName.length > 0) {
              var geoCoord = geoCoordMap[cityName[0]];
              if (val[longitudeDimension] && val[latitudeDimension] && val[longitudeDimension]!=='longitude') {
                res = {
                  name: cityName[0],
                  category: val[visualDimension],
                  value: [val[longitudeDimension], val[latitudeDimension], val[valueDimension]]
                };
              } else if (geoCoord) {
                res = {
                  name: cityName[0],
                  category: val[visualDimension],
                  value: geoCoord.concat(val[valueDimension])
                };
              }
            } else {
              res = {
                name: val[cityDimension],
                category: val[visualDimension],
                value: [val[longitudeDimension], val[latitudeDimension], val[valueDimension]]
              };
            }
            if (hasCategroy > -1) {
              arr[hasCategroy].push(res);
            }
          }
        }
      });
      return arr;
    }

    var convertProvinceData = function(data) {
      var res = [];
      for (var i = 0; i < data.length; i++) {
        let provinceName, nameIndex;
        Object.keys(geoCoordMap).map((val, index) => {
          if (data[i].name.indexOf(val) !== -1 || val.indexOf(data[i].name) !== -1) {
            nameIndex = index;
            provinceName = val;
          }
        });
        if (nameIndex > -1) {
          var geoCoord = Object.values(geoCoordMap)[nameIndex];
          if (geoCoord) {
            res.push({
              name: provinceName,
              value: geoCoord.concat(data[i].value),
            });
          }
        }
      }
      return res;
    };

    var getSeries = function(data, selected, mapname) {
      let series = new Array();
      let maxValue = 1;
      const top5Data = data[selected].sort(function(a, b) {
        return b.value[2] - a.value[2];
      }).slice(0, 5);
      if (top5Data.length > 0) {
        Object.assign(visualMap, { max: top5Data[0].value[2], min: 0 });
        maxValue = top5Data[0].value[2];
      }
      data.map((val, index) => {
        let serie = {
          type: 'map',
          mapType: mapname,
          selectedMode: false,//是否允许选中多个区域
          showLegendSymbol: false,
          label: {
            normal: {
              show: mapLabelShow,
              textStyle: {
                color: mapLabelColor,
                fontSize: mapLabelSize
              },
            },
            emphasis: {
              show: false
            }
          },
          itemStyle: {
            normal: {      
              borderColor: mapBorderColor,
              borderWidth: mapBorderSize,
              areaColor: mapColor
            },
            emphasis: {
              areaColor: mapEmphasisColor,
            }
          },
          data: val
        };
        if (mapname !== 'china' && categories.length > 0) {
          Object.assign(serie, { name: categories[index] });
        }
        series.push(serie);
      });
      if (top5Data.length === 5) {
        series.push({
          type: 'effectScatter',
          coordinateSystem: 'geo',
          data: top5Data,
          symbolSize: function(val) {
            var a = (top5ScatterMaxSize - top5ScatterMinSize) / maxValue;
            var b = top5ScatterMinSize;
            b = top5ScatterMaxSize - a * maxValue;
            return a * val[2] + b;
          },
          showEffectOn: 'render',
          rippleEffect: {
            brushType: 'stroke'
          },
          animation: false,
          hoverAnimation: true,
          label: {
            normal: {
              formatter: '{b}',
              position: top5ScatterLabelShowPosition,
              show: top5ScatterLabelShow
            }
          },
          itemStyle: {
            normal: {
              color: top5ScatterColor,
              shadowBlur: 10,
              shadowColor: top5ScatterColor,
              fontSize: top5ScatterLabelSize
            }
          },
          zlevel: 1
        });
      }
      return series.concat([
        {
          type: 'scatter',
          coordinateSystem: 'geo',
          data: data[selected],
          animation: false,
          symbolSize: function(val) {
            var a = (scatterMaxSize - scatterMinSize) / maxValue;
            var b = scatterMinSize;
            b = scatterMaxSize - a * maxValue;
            return a * val[2] + b;
          },
          label: {
            normal: {
              formatter: '{b}',
              position: scatterLabelShowPosition,
              show: scatterLabelShow
            },
            emphasis: {
              show: scatterLabelShow
            }
          },
          itemStyle: {
            normal: {
              color: scatterColor,
              fontSize: scatterLabelSize
            }
          }
        },
        {
          type: 'scatter',
          coordinateSystem: 'geo',
          symbol: 'pin', //气泡
          symbolSize: function(val) {
            var a = (pinMaxSize - pinMinSize) / maxValue;
            var b = pinMinSize;
            b = pinMaxSize - a * maxValue;
            return a * val[2] + b;
          },
          animation: false,
          label: {
            normal: {
              formatter: '{@[2]}',
              show: true,
              textStyle: {
                color: pinFontColor || fontColor,
                fontSize: pinFontSize,
              },
            }
          },
          itemStyle: {
            normal: {
              color: pinColor, //标志颜色
            }
          },
          zlevel: 6,
          data: data[selected]
        },
      ])
    }

    var getTooltip = function(source) {
      return {
        trigger: 'item',
        formatter: function(params) {
          var toolTiphtml = '';
          source.map(value => {
            if ((value.name.indexOf(params.name) !== -1 || params.name.indexOf(value.name) !== -1) && typeof(value.tooltip) !== 'undefined') {
              toolTiphtml += value.name + ':<br>';
              value.tooltip.map(tooltip => {
                toolTiphtml += tooltip.name + ':' + tooltip.value + '<br>';
              });
            }
          });
          return toolTiphtml;
        }
      }
    }

    function initChart(series, selectedItem, mapname, tooltip) {
      myChart.clear();
      let selected = {};
      let seriesIndex = new Array;
      if (mapname === 'china') {
        seriesIndex.push(0);
      } else {
        categories.map((category, index) => {
          selected[category] = (index === selectedItem);
          seriesIndex.push(index);
        });
      }
      const option = {
        title: title,
        legend: Object.assign({}, legend,{
          data: categories,
          selected
        }),
        visualMap: Object.assign({}, visualMap, { seriesIndex }),
        geo: {
          show: true,
          map: mapname
        },
        tooltip,
        series: series,
      };

      if (Boolean(colors)) option.color = colors;
      
      myChart.setOption(option);
      myChart.resize();
    }

    function initMap(source, mapname) {
      let tooltip ;
      const provinceKeys= Object.keys(provinces);
      if (categories.length === 0) {
        source.forEach((data,index) => {
          if(index !== 0 && data[2] !== undefined) {
            const category = data[2].trim();
            if(category !== "" && categories.indexOf(category) === -1) {
              categories.push(category)
            }
          }
        });
      }
      if (mapname && mapname !== '' && provinceKeys.length > 0) {
        const provinceIndex = provinceKeys.findIndex(val => mapname.indexOf(val) !== -1 || val.indexOf(mapname) !== -1);
        $.get(echartDataURL + Object.values(provinces)[provinceIndex] + ".json", function (json) {
          echarts.registerMap(mapname, json);
          var mapFeatures = echarts.getMap(mapname).geoJson.features;
            mapFeatures.forEach(function(v) {
              var name = v.properties.name;
              geoCoordMap[name] = v.properties.cp;        
          });
          if (mapname === 'china') {
            provinceData = [];
            getProvinceData(source);
            initData = convertProvinceData(provinceData);
            tooltip = getTooltip(provinceData);
            const series = getSeries([initData], legendSelected, mapname);
            initChart(series, legendSelected, mapname, tooltip);
          } else {
            initData = getCityData(source, mapname);
            const series = getSeries(initData, legendSelected, mapname);
            initChart(series, legendSelected, mapname, { show: false });
          }
        });
      }
    }

    initMap(defaultData, 'china');

    myChart.on('click', function (params) {
      params.event.cancelBubble = true;
      const { componentSubType, name } = params;
      let isProvince = false;
      provinceData.map(province => {
        if (province.name.indexOf(name) !== -1 || name.indexOf(province.name) !== -1) {
          isProvince = true;
        }
      });
      let isCity = false;
      if (isProvince) {
        defaultData.map((source, index) => {
          if (index !== 0 && (source[0].indexOf(name) !== -1 || name.indexOf(source[0]) !== -1)) {
            isCity = true;
          }
        });
      }
      if (componentSubType === "scatter" && (!isProvince || (isCity && isProvince && mapName !== 'china')) && showPopup) {
        const { data } = params;
        popupEl.style.display = "block";

        const dataCategory = data.category;
        const categoryIndex = categories.indexOf(dataCategory);
        let displayData = [];
        const filterKey = "城市";
        const filterVal = data.name;
        // 设置dialog title
        if(popupElTitle) {
          popupElTitle.innerHTML = filterVal;
        }

        if(categoryIndex === 0) {
          displayData = getDisplayPopupTable(defaultDataInput2, filterKey, filterVal);
        } else {
          displayData = getDisplayPopupTable(defaultDataInput3, filterKey, filterVal);
        }
        const ulDom = $(popupElList).find("ul")[0];
        if(ulDom) {
          popupElList.removeChild(ulDom);
        }
        const ulDomNew = document.createElement("ul");
        popupElList.appendChild(ulDomNew);
        displayData.forEach( record => {
          const liDom = document.createElement("li");
                    
          const spanDom_1 = document.createElement("span");
          spanDom_1.innerHTML = record.设备名称;
          spanDom_1.style.flexBasis = "50%";
          liDom.appendChild(spanDom_1);

          const spanDom_2 = document.createElement("span");
          spanDom_2.innerHTML = record.设备编号 || record.device_code;
          spanDom_2.className = "link";
          spanDom_2.style.flexBasis = "30%";
          spanDom_2.addEventListener('click', showPopupDetail.bind(this,record), false); //鼠标单击的时候调用showMes这个函数
          liDom.appendChild(spanDom_2);

          if(record.quality_status) {
            const spanDom_3 = document.createElement("span");
            const qualityStatus = record.质保状态 === "-"  ? "" : `(${record.质保状态})`;
            spanDom_3.innerHTML = qualityStatus;
            spanDom_3.style.flexBasis = "20%";
            liDom.appendChild(spanDom_3);
          }

          ulDomNew.appendChild(liDom);
        })

      } else {
        if (isProvince) {
          mapName = name;
          initMap(defaultData, name);
        }
        popupEl.style.display = "none";
        popupDetailEl.style.display = "none";
      }
    });

    myChart.on('legendselectchanged', function(params) {
      legendSelected = categories.findIndex(val => val === params.name);
      if (legendSelected > -1) {
        const series = getSeries(initData, legendSelected, mapName);
        initChart(series, legendSelected, mapName, { show: false });
        popupEl.style.display = "none";
        popupDetailEl.style.display = "none";
      } else {
        legendSelected = 0;
      }
    });

    myChart.getZr().on('click', function(params) {
      const { target, topTarget } = params;
      if (mapName !== 'china' && typeof target === 'undefined' && typeof topTarget === 'undefined') {
        mapName = 'china';
        legendSelected = 0;
        initMap(defaultData, 'china');
        popupEl.style.display = "none";
        popupDetailEl.style.display = "none";
      }
    });

    const labelMapping = {
      city: "城市编号", 
      device_name: "设备名称",
      equipment_id: "设备编号",
      quality_status: "质保状态",
      service_process: "服务进度",
      production_date: "出厂日期",      
      customer_name: "客户名称",
      equipment_type: "设备型号", 
      state: "状态",
      service_type: "服务类型",
      equipment_state: "设备状态",
      equipment_address: "设备地址",      
      equipment_scene_contact: "现场联系人",    
      equipment_scene_phone: "联系方式",      
      equipment_last_dock_day: "最近一次对接",  
      equipment_last_dock_person: "最近一次对接人",
      equipment_last_dock_person_phone: "联系方式",      
      equipment_dock_way: "对接方式",  
      device_code: "设备编号",
      service_schedule: "服务进度",
      device_model: "设备型号",
      device_status: "状态",
      interval_distance: "合同距离",
      contract_distance: "区间距离",
      now_distance: "当前距离",
    }

    var showPopupDetail = function(record, event) {
      popupDetailEl.style.display = "block";

      // 设置dialog title
      if(popupDetailElTitle) {
        popupDetailElTitle.innerHTML = record.设备编号 || record.device_code;
      }

      const keys = Object.keys(record);
      const displayKey = keys.filter(key => (["城市", "设备名称", "设备编号", "质保状态"].indexOf(key) === -1));

      const listDom = $(popupDetailElList).find(".list-detail")[0];
      if(listDom) {
        popupDetailElList.removeChild(listDom);
      }
      const listDomNew = document.createElement("div");
      listDomNew.className = "list-detail";
      popupDetailElList.appendChild(listDomNew);

      displayKey.forEach( displayKey => {
        const divDom = document.createElement("div");
        let val = "";
        if (!Number.isNaN(record[displayKey])) {
          val = record[displayKey]
        }
        const displayName = (labelMapping[displayKey]) ? labelMapping[displayKey] : displayKey;
        divDom.innerHTML = `${displayName}: ${val}`;
        
        if (["customer_name","equipment_address","equipment_scene_contact","equipment_scene_phone", "equipment_last_dock_day"].indexOf(displayKey) !== -1) {
          divDom.style.flexBasis = "100%";
        } else {
          divDom.style.flexBasis = "50%";
        }
        listDomNew.appendChild(divDom);
      })
      
    }

    let defaultDataInput2 = [
      {"city": "无锡", "device_name": "土压平衡盾构机", "device_code": "DZ188", "service_process": "质保期满", "customer_name": "中交一公局桥隧工程有限公司", "equipment_type": "ZTE6410", "state": "质保期满", "service_type": "新机销售"}, 
      {"city": "无锡市", "device_name": "土压平衡盾构机", "device_code": "DZ036", "service_process": "质保期满", "customer_name": "中铁十七局集团第六工程有限公司", "equipment_type": "ZTE6250", "state": "质保期满", "service_type": "新机销售"}, 
      {"city": "南京", "device_name": "土压平衡盾构机", "equipment_id": "DZ325", "quality_status": "-", "service_process": "质保中", "customer_name": "中铁二十一局集团有限公司呼和浩特市轨道交通2号线一期工程02标项目部", "equipment_type": "ZTE6250", "state": "质保中", "service_type": "新机销售"}, 
      {"city": "南京", "device_name": "敞开式TBM", "equipment_id": "DZ116", "quality_status": "-", "service_process": "质保期满", "customer_name": "中交一公局第三工程有限公司", "equipment_type": "ZTT6830", "state": "质保期满", "service_type": "新机销售"}, 
      {"city": "静安区", "device_name": "敞开式TBM", "equipment_id": "DL359G1", "quality_status": "-", "service_process": "试掘进", "customer_name": "中铁建大桥局集团第三工程有限公司", "equipment_type": "ZTT6300", "state": "在用", "service_type": "旧机租赁"}, 
      {"city": "静安区", "device_name": "土压平衡盾构机", "equipment_id": "DL416", "quality_status": "-", "service_process": "租赁监管", "customer_name": "-", "equipment_type": "ZTE8800", "state": "在用", "service_type": "新机租赁"}, 
      {"city": "静安区", "device_name": "敞开式TBM", "equipment_id": "DZ300", "quality_status": "-", "service_process": "质保中", "customer_name": "中铁十一局集团第五工程有限公司", "equipment_type": "ZTT7030", "state": "质保中", "service_type": "新机销售"}, 
    ]

    let defaultDataInput3 = [
      {"city": "苏州", "device_name": "-", "equipment_id": "G070117093", "quality_status": "-", "service_process": "-", "production_date": "-", "customer_name": "中铁十七局集团第六工程有限公司", "equipment_type": "HPS3016SW", "state": "在用", "equipment_state": "正常", "equipment_address": "-", "equipment_scene_contact": "-", "equipment_scene_phone": "-", "equipment_last_dock_day": "-", "equipment_last_dock_person": "-", "equipment_last_dock_person_phone": "-", "equipment_dock_way": "-"}, 
      {"city": "南京", "device_name": "连续墙", "equipment_id": "YFG301112", "quality_status": "-", "service_process": "-", "production_date": "-", "customer_name": "株洲唯能隧道机械化工程有限公司-山东省", "equipment_type": "LSJ60", "state": "在用", "equipment_state": "正常", "equipment_address": "-", "equipment_scene_contact": "-", "equipment_scene_phone": "-", "equipment_last_dock_day": "-", "equipment_last_dock_person": "-", "equipment_last_dock_person_phone": "-", "equipment_dock_way": "-"}, 
      {"city": "常州市", "device_name": "-", "equipment_id": "G070117095", "quality_status": "-", "service_process": "-", "production_date": "-", "customer_name": "-", "equipment_type": "HPS3016SW", "state": "在用", "equipment_state": "正常", "equipment_address": "-", "equipment_scene_contact": "-", "equipment_scene_phone": "-", "equipment_last_dock_day": "-", "equipment_last_dock_person": "-", "equipment_last_dock_person_phone": "-", "equipment_dock_way": "-"}, 
      {"city": "常州市", "device_name": "喷射台车", "equipment_id": "G07010283", "quality_status": "-", "service_process": "-", "production_date": "2017-02-24 00:00:00", "customer_name": "重庆斌鑫建筑工程有限公司", "equipment_type": "HPS3016SW", "state": "在用", "equipment_state": "正常", "equipment_address": "重庆市万州区巫山县三溪乡", "equipment_scene_contact": "-", "equipment_scene_phone": "-", "equipment_last_dock_day": "-", "equipment_last_dock_person": "-", "equipment_last_dock_person_phone": "-", "equipment_dock_way": "-"}, 
      {"city": "静安区", "device_name": "喷射台车", "equipment_id": "G07010144", "quality_status": "-", "service_process": "-", "production_date": "2016-02-06 00:00:00", "customer_name": "陕西恒通盛路桥建设工程有限公司（中铁港航局集团有限公司蒙华铁路MHTJ-30标段项目经理部）", "equipment_type": "HPS3016", "state": "在用", "equipment_state": "正常", "equipment_address": "-", "equipment_scene_contact": "-", "equipment_scene_phone": "-", "equipment_last_dock_day": "-", "equipment_last_dock_person": "-", "equipment_last_dock_person_phone": "-", "equipment_dock_way": "-"}, 
      {"city": "无锡市", "device_name": "喷射台车", "equipment_id": "G070117027", "quality_status": "-", "service_process": "-", "production_date": "2018-03-04 00:00:00", "customer_name": "-", "equipment_type": "HPS3016S", "state": "在用", "equipment_state": "正常", "equipment_address": "-", "equipment_scene_contact": "-", "equipment_scene_phone": "-", "equipment_last_dock_day": "-", "equipment_last_dock_person": "-", "equipment_last_dock_person_phone": "-", "equipment_dock_way": "-"}, 
    ]

    var dataframeToJson = function(data){
      var res = [];
      for(var i = 1; i < data.length; i++)
      {
        var jstr = "{";
        for(var j = 0; j < data[0].length; j++)
        {
          jstr = jstr + "\"" + data[0][j] + "\":\"" + data[i][j] + "\",";
        }
        jstr = jstr.substr(0,jstr.length-1);
        jstr += "}";
        res.push(JSON.parse(jstr.replace(/\s*/g,"")));
      }
      return res;
    }

    var getDisplayPopupTable = function(list, filterKey, filterVal) {
      const displayData = list.filter(listEl => (filterVal && filterVal.indexOf(listEl[filterKey]) !== -1) || (listEl[filterKey] && listEl[filterKey].indexOf(filterVal) !== -1));
      return displayData;
    }

    // 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)

    // 有 dashboardHost 说明是运行模式
    if (window.spSocket) {
      closePopup();
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          let _in1Str = _data.data.in1;
          if (_in1Str) {
            const source = JSON.parse(_in1Str);
            initMap(source, mapName);
            defaultData = [].concat(source);
          }
          let _in2Str = _data.data.in2;
          if (_in2Str) {
            const sourceIn2 = JSON.parse(_in2Str);
            //defaultDataInput2 = [].concat(sourceIn2);
            defaultDataInput2 = sourceIn2;
          }

          let _in3Str = _data.data.in3;
          if (_in3Str) {
            const sourceIn3 = JSON.parse(_in3Str);
            //defaultDataInput3 = [].concat(sourceIn3);
            defaultDataInput3 = sourceIn3;
          }
        }
      });
    }
    Boolean(dataSource) && $.get(dataSource, function (ds) {
      myChart.hideLoading();
      initChart(JSON.parse(ds))
    });
  },

  onViewInit() {
    const comps = this.model.get('components');
    if (!comps.length) {
      comps.reset();
      comps.add(`
        <div class="mapChart" draggable="false"></div>
        <div class="xly-box-1" draggable="false">
          <div class="popup-title-1" draggable="false"></div>
          <div class="popup-close" draggable="false">X</div>
          <div class="seperate-line" draggable="false"></div>
          <div class="popup-list" draggable="false"></div>
        </div>
        <div class="xly-box-2" draggable="false">
          <div class="popup-title-2" draggable="false"></div>
          <div class="popup-close" draggable="false">X</div>
          <div class="seperate-line" draggable="false"></div>
          <div class="popup-list" draggable="false"></div>
        </div>
      `)
    }
    this.updateScript();
    const evn = echartsBasicListen + `
      change:defaultData
      change:echartDataURL
      change:inRangeColors
      change:inRangePosition
      change:inRangeLabel
      change:pinColor
      change:pinMaxSize
      change:pinMinSize
      change:pinFontSize
      change:pinFontColor
      change:scatterColor
      change:scatterLabelShow
      change:scatterLabelShowPosition
      change:scatterLabelSize
      change:top5ScatterColor
      change:top5ScatterLabelSize
      change:top5ScatterLabelShow
      change:top5ScatterLabelShowPosition
      change:mapEmphasisColor
      change:mapLabelShow
      change:mapLabelColor
      change:mapColor
      change:mapBorderColor
      change:mapBorderSize
      change:scatterMinSize
      change:scatterMaxSize
      change:top5ScatterMinSize
      change:top5ScatterMaxSize
      change:showPopup
      change:categories
      change:inRangeShow
      change:inRangeLabelSize
      change:inRangeLabelColor
      change:inRangeDataShow
      change:legendFontSize
      change:mapLabelSize
    `;
    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)));
  }
}
