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

export default {

  // 组件名称
  name: map3DPopup,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${map3DPopup}" class="${map3DPopup}"></div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${map3DPopup} {
          position: absolute;
          border-radius: 5px;
          border-style: solid;
          border-width: 1px;
          border-color: transparent;
          padding: 10px;
          width: 1040px;
          height: 780px;
        }
        .${map3DPopup} .mapChart{
          width: 100%;
          height: 100%;
        }
        .${map3DPopup} .xly-box-1 .seperate-line, .${map3DPopup} .xly-box-2 .seperate-line {
          width: 100%;
          height: 1px;
          border: 1px solid rgba(255,255,255,1);
          margin-bottom: 5px;
        }
        .${map3DPopup} .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;
        }
        .${map3DPopup} .xly-box-1 .popup-title-1, .${map3DPopup} .xly-box-2 .popup-title-2 {
          position: relative;
          width: 100%;
          height: 34px;
          padding-left: 20px;
          font-size:16px;
          color:#C8E8FF;
          line-height:34px;
        }
        .${map3DPopup} .xly-box-1 .popup-list {
          position: relative;
          width: 100%;
          height: 140px;
          font-size:12px;
          color:#FFFFFF;
          line-height:30px;
          overflow: auto;
        }
        .${map3DPopup} .xly-box-1 .popup-list ul {
          margin: 0;
          padding: 0;
          list-style: none;
        }
        .${map3DPopup} .xly-box-1 .popup-list ul > li {
          margin: 0;
          padding: 0;
          display: flex;
          align-items: center;
        }
        .${map3DPopup} .xly-box-1 .popup-list ul li .link:hover {
          color: blue;
          text-decoration:underline;
          cursor: pointer;
        }
        .${map3DPopup} .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;
        }
        .${map3DPopup} .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;
        }
        .${map3DPopup} .popup-close:hover {
          background-color: rgba(0,0,0,0.2); 
        }
        .${map3DPopup} .xly-box-2 .popup-list{
          position: relative;
          width: 100%;
          height: 250px;
          font-size:12px;
          color:#FFFFFF;
          line-height:30px;
          overflow: auto;
        }
        .${map3DPopup} .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" version="1.1" xmlns="http://www.w3.org/2000/svg" ><path d="M408 881l-210-50V333l210 50z" fill="#D4E3FF" p-id="40786"></path><path d="M408 897h-4l-210-50c-7-2-12-8-12-16V333c0-5 2-9 6-12s9-5 14-3l210 49c7 2 12 9 12 16v498a16 16 0 0 1-16 16z m-194-78l178 42V396l-178-43v466z" fill="#4780FF" p-id="40787"></path><path d="M830 367l-98-23c-9-2-18 3-20 12-2 8 4 17 12 19l87 20v466l-178-42v-86c0-9-7-16-16-16s-16 7-16 16v86l-178 42V395l86-20a16 16 0 0 0-7-31l-99 23c-7 2-12 8-12 16v498a16 16 0 0 0 20 16l206-49 206 49h4a16 16 0 0 0 16-16V383c0-8-5-14-13-16z" fill="#4780FF" p-id="40788"></path><path d="M723 238a110 110 0 1 0-122 110v281c0 9 7 16 16 16s16-7 16-16V347c51-10 90-55 90-109z m-110 78a78 78 0 1 1 1-156 78 78 0 0 1-1 156z"  p-id="40789"></path></svg>
        <div class="gjs-block-label">弹框3D地图</div>
      `,
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '弹框3D地图',
      icon: 'globe',
      docUrl: 'https://www.yuque.com/docs/share/062e7a46-b543-470c-bbcc-2f4e0466de79#',
      author: '宗介',
      email: 'zongjie.wxt@xuelangyun.com',
      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: map3DPopup,
      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: '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, "类别2"],
        ["泉州", 10, "类别2"]
      ]).replace(/\"/g, "\\\""),
      'mapName': 'china',
      'mapColor': '#002c4d',
      'mapBorderColor': '#66b5ff',
      'mapLabel': false,
      'mapLabelColor': '#fff',
      '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 ]}';
    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) => {
        const key = item.split(':')[0].trim();
        const value = item.split(':')[1].trim();
        legend[`${key}`] = value;
      });
    }
    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, "类别2"], ["泉州", 10, "类别2"]];


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

    const canvasEl = $(self).find('.mapChart')[0];
    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);
    }

    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) {
      myChart.clear();
      const series = getSeries(source);

      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();
    }

    myChart.on('click', function (params) {
      const {componentType} = params;
      if (componentType === "series") {
        const { data } = params;
        popupEl.style.display = "block";

        console.log("select map data",data);
        const dataCategory = data.value[5];
        const categoryIndex = categories.indexOf(dataCategory);
        let displayData = [];
        const filterKey = "city";
        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);
        }
        console.log(displayData);
        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.device_name;
          spanDom_1.style.flexBasis = "50%";
          liDom.appendChild(spanDom_1);

          const spanDom_2 = document.createElement("span");
          spanDom_2.innerHTML = record.equipment_id || 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.quality_status === "-"  ? "" : `(${record.quality_status})`;
            spanDom_3.innerHTML = qualityStatus;
            spanDom_3.style.flexBasis = "20%";
            liDom.appendChild(spanDom_3);
          }

          ulDomNew.appendChild(liDom);
        })

      } else {
        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) {
      console.log("详细弹框",record);
      popupDetailEl.style.display = "block";

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

      const keys = Object.keys(record);
      const displayKey = keys.filter(key => (["city", "device_name", "equipment_id", "quality_status","device_code"].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 getDisplayPopupTable = function(list, filterKey, filterVal) {
      const displayData = list.filter(listEl => listEl[filterKey] === filterVal);
      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)

    let hasTransfer = 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);
            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}
                });
              }
            }
          }
          let _in2Str = _data.data.in2;
          if (_in2Str) {
            const sourceIn2 = JSON.parse(_in2Str);
            defaultDataInput2 = [].concat(sourceIn2);
          }

          let _in3Str = _data.data.in3;
          if (_in3Str) {
            const sourceIn3 = JSON.parse(_in3Str);
            defaultDataInput3 = [].concat(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: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: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)));
  }
}
