import { gaugeChart, CATEGORIES } from '../../configuration/constants'
import { throttle } from '../../utils'

export default {

  // 组件名称
  name: gaugeChart,

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

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      category: CATEGORIES.ECHARTS,
      label: `
        <svg class="gjs-block-svg" viewBox="-4 -4 32 32" xmlns="http://www.w3.org/2000/svg">
          <path d="M10.1,15.9c-0.7,1.2-0.2,2.2,0.7,2.7c1,0.6,2,0.5,2.7-0.7c0.7-1.2,5-11.9,4.7-12.1C17.9,5.6,10.8,14.7,10.1,15.9z M12,8.3
          c0.4,0,0.9,0,1.3,0.1c0.4-0.5,0.9-1.2,1.4-1.7c-0.9-0.3-1.8-0.4-2.7-0.4C6.4,6.3,2,11,2,17.1c0,0.4,0,0.7,0,1.1c0,0.6,0.5,1,1.1,0.9
          C3.7,19,4.1,18.6,4,18c0-0.3,0-0.6,0-0.9C4,12.2,7.5,8.3,12,8.3z M19.2,9.6c-0.3,0.8-0.6,1.5-0.8,2.2c1,1.5,1.6,3.3,1.6,5.3
          c0,0.3,0,0.6,0,0.9c0,0.6,0.4,1,0.9,1c0.5,0,1-0.4,1-0.9c0-0.4,0.1-0.7,0.1-1.1C22,14.1,20.9,11.5,19.2,9.6L19.2,9.6z"/>
        </svg>
        <div class="gjs-block-label">仪表盘</div>
      `
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '仪表盘',
      icon: 'globe',
      docUrl: 'https://www.yuque.com/docs/share/c165c0ac-8b86-4aaf-8618-efd0547fcee0#',
      author: '秋水',
      email: 'qiushui.smy@xuelangyun.com',
      inPorts: [
        {
          uuid: 'in1',
          subType: 'json',
          description: {
            zh_CN: '输入1'
          }
        }, {
          uuid: 'in2',
          subType: 'all',
          description: {
            zh_CN: 'loading'
          }
        }
      ]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: gaugeChart,
      resizable: true,
      dmode: 'absolute',
      droppable: false,
      traits: [{
        type: 'color',
        name: 'bgColor',
        label: '背景色',
        changeProp: 1,
      }, {
        type: 'color',
        name: 'borderColor',
        label: '边框颜色',
        changeProp: 1
      }, {
        type: 'color',
        name: 'fontColor',
        label: '字体颜色',
        changeProp: 1
      }, {
        type: 'number',
        name: 'fontSize',
        label: '字号',
        changeProp: 1,
        min: 10,
        step: 1
      }, {
        name: 'titleText',
        label: '图表名称',
        changeProp: 1
      }, {
        name: 'titlePosition',
        label: '名称位置',
        changeProp: 1,
        type: 'select',
        options: [
          { id: 'top-left', name: '顶部居左' },
          { id: 'top-center', name: '顶部居中' },
          { id: 'top-right', name: '顶部居右' },
          { id: 'center-center', name: '居中' },
          { id: 'bottom-left', name: '底部居左' },
          { id: 'bottom-center', name: '底部居中' },
          { id: 'bottom-right', name: '底部居右' },
        ]
      }, {
        name: 'startAngle',
        label: '起始角度',
        changeProp: 1,
        type: 'number'
      }, {
        name: 'endAngle',
        label: '结束角度',
        changeProp: 1,
        type: 'number'
      }, {
        name: 'radius',
        label: '半径(%)',
        changeProp: 1,
        type: 'number'
      }, {
        name: 'minData',
        label: '最小值',
        changeProp: 1,
        type: 'number'
      }, {
        name: 'maxData',
        label: '最大值',
        changeProp: 1,
        type: 'number'
      }, {
        name: 'splitNumber',
        label: '分隔段数',
        changeProp: 1,
        type: 'number'
      }, {
        type: 'checkbox',
        name: 'axisLine',
        label: '轴线',
        changeProp: 1,
      }, {
        name: 'axisLineSplit',
        label: '轴线分段颜色',
        changeProp: 1,
      }, {
        type: 'number',
        name: 'axisLineWidth',
        label: '轴线宽度(px)',
        changeProp: 1,
      }, {
        type: 'checkbox',
        name: 'axisLabel',
        label: '刻度值',
        changeProp: 1,
      }, {
        type: 'number',
        name: 'axisLabelSize',
        label: '刻度值字号',
        changeProp: 1,
      }, {
        name: 'axisLabelFontFamily',
        label: '刻度值字体',
        changeProp: 1,
        type: 'select',
        options: [
          { id: 'sans-serif', name: '默认' },
          { id: '庞门正道', name: '庞门正道' },
          { id: 'DS-Digital', name: 'DS-Digital' }
        ]
      }, {
        type: 'color',
        name: 'axisLabelColor',
        label: '刻度值颜色',
        changeProp: 1,
      }, {
        type: 'checkbox',
        name: 'axisTick',
        label: '刻度线',
        changeProp: 1,
      }, {
        type: 'number',
        name: 'axisTickWidth',
        label: '刻度线宽度(px)',
        changeProp: 1,
      }, {
        type: 'number',
        name: 'axisTickLength',
        label: '刻度线长度(px)',
        changeProp: 1,
      }, {
        type: 'color',
        name: 'axisTickColor',
        label: '刻度线颜色',
        changeProp: 1,
      }, {
        type: 'checkbox',
        name: 'splitLine',
        label: '分隔线',
        changeProp: 1,
      }, {
        type: 'number',
        name: 'splitLineWidth',
        label: '分隔线宽度(px)',
        changeProp: 1,
      }, {
        type: 'number',
        name: 'splitLineLength',
        label: '分隔线长度(px)',
        changeProp: 1,
      }, {
        type: 'color',
        name: 'splitLineColor',
        label: '分隔线颜色',
        changeProp: 1,
      }, {
        type: 'checkbox',
        name: 'pointer',
        label: '指针',
        changeProp: 1,
      }, {
        type: 'number',
        name: 'pointerWidth',
        label: '指针宽度(px)',
        changeProp: 1,
      }, {
        type: 'number',
        name: 'pointerLength',
        label: '指针长度(%)',
        changeProp: 1,
      }, {
        name: 'gaugeTitle',
        label: '仪表板标题',
        changeProp: 1,
        type: 'checkbox'
      }, {
        name: 'gaugeTitleColor',
        label: '标题颜色',
        changeProp: 1,
        type: 'color'
      }, {
        type: 'number',
        name: 'gaugeTitleSize',
        label: '标题字号(px)',
        changeProp: 1,
      }, {
        name: 'gaugeTitleFontFamily',
        label: '标题字体',
        changeProp: 1,
        type: 'select',
        options: [
          { id: 'sans-serif', name: '默认' },
          { id: '庞门正道', name: '庞门正道' },
          { id: 'DS-Digital', name: 'DS-Digital' }
        ]
      }, {
        name: 'detail',
        label: '显示数据',
        changeProp: 1,
        type: 'checkbox'
      }, {
        type: 'number',
        name: 'detailSize',
        label: '数据字号(px)',
        changeProp: 1,
      }, {
        name: 'detailFontFamily',
        label: '数据字体',
        changeProp: 1,
        type: 'select',
        options: [
          { id: 'sans-serif', name: '默认' },
          { id: '庞门正道', name: '庞门正道' },
          { id: 'DS-Digital', name: 'DS-Digital' }
        ]
      }, {
        type: 'color',
        name: 'detailColor',
        label: '数据颜色',
        changeProp: 1,
      }, {
        name: 'csv',
        label: '示例数据',
        changeProp: 1,
        type: 'csvDownload',
        preFileName: '仪表盘',
        dataType: 'gauge',
        datas: [{value: 30, name: 'km/h'}]
      },{
        name: 'defaultData',
        changeProp: 1,
        type: 'hide'
      }
      ],
      'defaultData':JSON.stringify([{value: 30, name: 'km/h'}]).replace(/\"/g, "\\\""),
      'bgColor': null,
      'borderColor': null,
      'fontColor': '#333',
      'titleText': null,
      'titlePosition': 'top-left',
      'startAngle': 225,
      'endAngle': -45,
      'radius': 75,
      'minData': 0,
      'maxData': 100,
      'splitNumber': 10,
      'axisLine': true,
      'axisLineSplit': '0.2:#0084ff, 0.8:#339cff, 1:#66b5ff',
      'axisLineWidth': 10,
      'axisLabel': true,
      'axisLabelSize': 12,
      'axisLabelFontFamily': "sans-serif",
      'axisLabelColor': 'auto',
      'axisTick': true,
      'axisTickWidth': 1,
      'axisTickLength': 18,
      'axisTickColor': 'auto',
      'splitLine': true,
      'splitLineWidth': 2,
      'splitLineLength': 20,
      'splitLineColor': 'auto',
      'pointer': true,
      'pointerWidth': 8,
      'pointerLength': 80,
      'gaugeTitle': true,
      'gaugeTitleColor': '#333',
      'gaugeTitleSize': 15,
      'gaugeTitleFontFamily': "sans-serif",
      'detail': true,
      'detailSize': 15,
      'detailFontFamily': "sans-serif",
      'detailColor': 'auto',
    }
  },

  onModelScript() {
    const bgColor = '{[ bgColor ]}';
    const borderColor = '{[ borderColor ]}';
    const fontColor = '{[ fontColor ]}';
    const fontSize = Number('{[ fontSize ]}');
    const titleText = '{[ titleText ]}';
    const titleColor = '{[ titleColor ]}';
    const titlePosition = ('{[ titlePosition ]}').toString();
    
    const radius = ('{[ radius ]}').toString() + '%';
    const minData = Number('{[ minData ]}');
    const maxData = Number('{[ maxData ]}');
    const splitNumber = Number('{[ splitNumber ]}');
    const startAngle = Number('{[ startAngle ]}');
    const endAngle = Number('{[ endAngle ]}');

    const axisLine = Boolean('{[ axisLine ]}');
    let axisLineSplit = ('{[ axisLineSplit ]}').toString();
    const axisLineWidth = '{[ axisLineWidth ]}';

    const axisLabel = Boolean('{[ axisLabel ]}');
    const axisLabelSize = '{[ axisLabelSize ]}';
    const axisLabelColor = '{[ axisLabelColor ]}';

    const axisTick = Boolean('{[ axisTick ]}');
    const axisTickWidth = '{[ axisTickWidth ]}';
    const axisTickLength = '{[ axisTickLength ]}';
    const axisTickColor = '{[ axisTickColor ]}';
    const axisLabelFontFamily = ('{[ axisLabelFontFamily ]}').toString();

    const splitLine = Boolean('{[ splitLine ]}');
    const splitLineWidth = '{[ splitLineWidth ]}';
    const splitLineLength = '{[ splitLineLength ]}';
    const splitLineColor = '{[ splitLineColor ]}';

    const pointer = Boolean('{[ pointer ]}');
    const pointerWidth = '{[ pointerWidth ]}';
    const pointerLength = ('{[ pointerLength ]}').toString() + '%';

    const gaugeTitle = Boolean('{[ gaugeTitle ]}');
    const gaugeTitleColor = '{[ gaugeTitleColor ]}';
    const gaugeTitleSize = '{[ gaugeTitleSize ]}';
    const gaugeTitleFontFamily = ('{[ gaugeTitleFontFamily ]}').toString();

    const detail = Boolean('{[ detail ]}');
    const detailSize = '{[ detailSize ]}';
    const detailFontFamily = ('{[ detailFontFamily ]}').toString();
    const detailColor = '{[ detailColor ]}';
    const defaultData = JSON.parse('{[ defaultData ]}'.replace(/\\\"/g, "\""));
    
    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: fontSize ? fontSize + 4 : 16,
        color: titleColor || fontColor
      }
    };
    
    if (axisLineSplit.indexOf(',') > 0) {
      const axisLineSplitArr = axisLineSplit.split(',');
      const len = axisLineSplitArr.length;
      axisLineSplit = axisLineSplitArr.map(function(item, i) {
        item = item.trim();
        if (item.indexOf(':') > 0) {
          return item.split(':').map(function(key, i) {
            key = key.trim();
            return i ? key : Number(key)
          })
        } else {
          return [i+1/len, item]
        }
      })
    } else if (Boolean(axisLineSplit)) {
      if (axisLineSplit.indexOf(':') > 0) {
        return axisLineSplit.split(':').map(function(key, i) {
          key = key.trim();
          return i ? key : Number(key)
        })
      } else {
        return [1, axisLineSplit]
      }
    } else {
      axisLineSplit = [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']];
    }

    const seriesTemp = {
      type: 'gauge',
      radius: radius,
      center: ['50%', '50%'],
      min: minData,
      max: maxData,
      splitNumber: splitNumber,
      startAngle: startAngle,
      endAngle: endAngle,
      axisLine: {
        show: axisLine,
        lineStyle: {
          color: axisLineSplit,
          width: axisLineWidth,
        }
      },
      axisLabel: {
        show: axisLabel,
        fontSize: axisLabelSize || fontSize,
        fontFamily: axisLabelFontFamily,
        color: axisLabelColor
      },
      axisTick: {
        show: axisTick,
        length: axisTickLength,
        lineStyle: {
          width: axisTickWidth,
          color: axisTickColor
        }
      },
      splitLine: {
        show: splitLine,
        length: splitLineLength,
        lineStyle: {
          width: splitLineWidth,
          color: splitLineColor
        }
      },
      pointer: {
        show: pointer,
        length: pointerLength,
        lineStyle: {
          width: pointerWidth
        }
      },
      title: {
        show: gaugeTitle,
        fontSize: gaugeTitleSize || fontSize,
        fontFamily: gaugeTitleFontFamily,
        color: gaugeTitleColor
      },
      detail: {
        show: detail,
        fontSize: detailSize || fontSize,
        fontFamily: detailFontFamily,
        color: detailColor
      }
    }

    const myChart = window.echarts.init(this);

    const self = this;

    function initChart(source) {
      myChart.clear();
      seriesTemp.data = source;
      const option = {
        title: title,
        series: seriesTemp
      };

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

    initChart(defaultData);

    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) {
      var eventName = `call-` + self.getAttribute('id');
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          if (_data.data.in1) {
            const source = JSON.parse(_data.data.in1);
            seriesTemp.data = source;
            myChart.setOption({
              series: seriesTemp
            })
          }
          if (_data.data.in2) {
            $(self).append(loader);
          }
        }
      });
    }
  },

  onViewInit() {
    this.updateScript();
    const evn = `
    change:defaultData
    change:bgColor change:borderColor change:fontColor change:fontSize change:titleText change:titlePosition change:startAngle change:endAngle change:radius change:minData change:maxData change:splitNumber change:axisLine change:axisLineSplit change:axisLineWidth change:axisLabel change:axisLabelSize change:axisLabelFontFamily change:axisLabelColor change:axisTick change:axisTickWidth change:axisTickLength change:axisTickColor change:splitLine change:splitLineWidth change:splitLineLength change:splitLineColor change:pointer change:pointerLength change:pointerWidth change:gaugeTitle change:gaugeTitleFontFamily change:gaugeTitleColor change:gaugeTitleSize change:detail change:detailSize change:detailFontFamily change:detailColor`;

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