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

export default {

  // 组件名称
  name: heatmapChart2,

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

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label:  `
      <svg class="gjs-block-svg" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" ><path d="M128 128h768a42.666667 42.666667 0 0 1 42.666667 42.666667v682.666666a42.666667 42.666667 0 0 1-42.666667 42.666667H128a42.666667 42.666667 0 0 1-42.666667-42.666667V170.666667a42.666667 42.666667 0 0 1 42.666667-42.666667z m42.666667 85.333333v597.333334h682.666666V213.333333H170.666667z m128 341.333334h85.333333v170.666666H298.666667v-170.666666z m170.666666-256h85.333334v426.666666h-85.333334V298.666667z m170.666667 128h85.333333v298.666666h-85.333333v-298.666666z" ></path></svg>
        <div class="gjs-block-label">热力图<br/>日历坐标系</div>
      `,
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '热力图',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/abebd4d7-6c8e-4e69-8475-d5c2cc740ca6?# 《热力图日历坐标系》',
      author: '秋水',
      email: 'qiushui.smy@xuelangyun.com',
      inPorts: [
        {
          uuid: 'in1',
          subType: 'json',
          description: {
            zh_CN: '输入1'
          }
        }, {
          uuid: 'in2',
          subType: 'all',
          description: {
            zh_CN: 'loading'
          }
        }
      ]
    }
  },

  // 组件属性
  componentOptions() {
    const getVirtulData = function (year) {
      year = year || '2019';
      var date = Date.parse(year + '-01-01');
      var end = Date.parse((Number(year) + 1) + '-01-01');
      var dayTime = 3600 * 24 * 1000;
      var data = [];
      for (var time = date; time < end; time += dayTime) {
          data.push([
              new Date(time).toLocaleDateString(),
              Math.floor(Math.random() * 10000)
          ]);
      }
      return data;
    }
    const defaultDataNew = getVirtulData('2019');
    defaultDataNew.unshift(['date','value']);
    return {
      name: heatmapChart2,
      resizable: true,
      dmode: 'absolute',
      droppable: false,
      traits: [
        {
          name: 'gridPadding',
          label: '容器边距(左,上,右,下)',
          changeProp: 1
        }, {
          name: 'orient',
          label: '布局朝向',
          changeProp: 1,
          type: 'select',
          options: [{id: 'horizontal', name: '水平'}, {id: 'vertical', name: '垂直'}]
        }, {
          name: 'range',
          label: '日历范围',
          changeProp: 1
        }, {
          name: 'cellSize',
          label: '框格大小',
          changeProp: 1,
        }, {
          name: 'splitLineWidth',
          label: '分割线宽度',
          changeProp: 1,
          type: 'number',
          min: 0,
          step: 1
        }, {
          name: 'splitLineColor',
          label: '分割线颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'itemColor',
          label: '日历格颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'itemBorderColor',
          label: '日历格边框色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'itemBorderWidth',
          label: '日历格边框宽度',
          changeProp: 1,
          type: 'number',
          min: 0,
          step: 1
        }, {
          name: 'day_fristDay',
          label: '从周几开始',
          changeProp: 1,
          type: 'select',
          options: [{id: '0', name: '周日'}, {id: '1', name: '周一'}, {id: '2', name: '周二'}, {id: '3', name: '周三'}, {id: '4', name: '周四'}, {id: '5', name: '周五'}, {id: '6', name: '周六'}]
        }, {
          name: 'day_position',
          label: '星期位置',
          changeProp: 1,
          type: 'select',
          options: [{id: 'start', name: '开头'}, {id: 'end', name: '结尾'}]
        }, {
          name: 'day_nameMap',
          label: '星期标签映射',
          changeProp: 1,
        }, {
          name: 'month_align',
          label: '月份对齐',
          changeProp: 1,
          options: [{id: 'left', name: '水平居左'}, {id: 'center', name: '水平居中'}, {id: 'right', name: '水平居右'}]
        }, {
          name: 'month_position',
          label: '月份位置',
          changeProp: 1,
          type: 'select',
          options: [{id: 'start', name: '开头'}, {id: 'end', name: '结尾'}]
        }, {
          name: 'month_nameMap',
          label: '月份标签映射',
          changeProp: 1,
        }, {
          name: 'yearLabelPosition',
          label: '年份',
          changeProp: 1,
          type: 'select',
          options: [{id: 'none', name:'不显示'}, {id: 'top', name:'上方显示'}, {id: 'bottom', name:'下方显示'},{id: 'left', name:'左侧显示'},{id: 'right', name:'右侧显示'}]
        }, {
          name: 'yearLabelFontFamily',
          label: '年份字体',
          type: 'select',
          options: [
            { id: 'sans-serif', name: '默认' },
            { id: '庞门正道', name: '庞门正道' },
            { id: 'DS-Digital', name: 'DS-Digital' }
          ],
          changeProp: 1
        }, {
          name: 'yearLabelFontSize',
          label: '年份字号',
          type: 'number',
          changeProp: 1,
          min: 12,
          step: 1
        }, {
          name: 'showLabel',
          label: '显示标签',
          type: 'checkbox',
          changeProp: 1
        }, {
          name: 'labelColor',
          label: '标签颜色',
          type: 'color',
          changeProp: 1
        }, {
          name: 'visualPosition',
          label: '视觉映射',
          changeProp: 1,
          type: 'select',
          options: [
            { id: 'none', name: '无' },
            { id: 'top-left', name: '顶部居左' },
            { id: 'top-center', name: '顶部居中' },
            { id: 'top-right', name: '顶部居右' },
            { id: 'center-left', name: '中部居左' },
            { id: 'center-right', name: '中部居右' },
            { id: 'bottom-left', name: '底部居左' },
            { id: 'bottom-center', name: '底部居中' },
            { id: 'bottom-right', name: '底部居右' },
          ]
        }, {
          name: 'visualOrient',
          label: '视觉映射朝向',
          type: 'select',
          options: [{id: 'horizontal', name: '水平'}, {id: 'vertical', name: '垂直'}]
        }, {
          name: 'visualMin',
          label: '视觉最小值',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'visualMax',
          label: '视觉最大值',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'colorAlpha',
          label: '颜色透明度',
          changeProp: 1,
        }, {
          name: 'colorLightness',
          label: '颜色明暗度',
          changeProp: 1,
        }, {
          name: 'colorSaturation',
          label: '颜色饱和度',
          changeProp: 1,
        }, {
          name: 'colorHue',
          label: '颜色色调',
          changeProp: 1,
        }, {
          name: 'inRangeColor',
          label: '范围内颜色',
          changeProp: 1
        }, {
          name: 'outRangeColor',
          label: '范围外颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'csv',
          label: '示例数据',
          changeProp: 1,
          type: 'csvDownload',
          preFileName: '热力图日历坐标系',
          datas: getVirtulData('2019'),
        },{
          name: 'defaultData',
          changeProp: 1,
          type: 'hide'
        }
      ],
      'defaultData':JSON.stringify(defaultDataNew).replace(/\"/g, "\\\""),
      'gridPadding': '10%,15%,5%,15%',
      'orient': 'horizontal',
      'range': '2019',
      'cellSize': null,
      'splitLineWidth': 3,
      'splitLineColor': '#fff',
      'itemColor': null,
      'itemBorderColor': '#fff',
      'itemBorderWidth': 3,
      'day_fristDay': '0',
      'day_position': 'start',
      'day_nameMap': 'cn',
      'month_align': 'center',
      'month_position': 'start',
      'month_nameMap': 'cn',
      'yearLabelFontFamily': 'sans-serif',
      'yearLabelPosition': 'none',
      'yearLabelFontSize': 20,
      'showLabel': false,
      'labelColor': '#fff',
      "legend": "none",
      'visualPosition': 'none',
      'visualOrient': 'horizontal',
      'visualMin': 0,
      'visualMax': 10000,
      'colorAlpha': null,
      'colorLightness': null,
      'colorSaturation': null,
      'colorHue': null,
      'inRangeColor': '#0084ff, #cce6ff',
      'outRangeColor': null,
    }
  },

  onModelScript() {
    const dataSource = '{[ dataSource ]}';
    const bgColor = '{[ bgColor ]}';
    const borderColor = '{[ borderColor ]}';
    const fontColor = '{[ fontColor ]}';
    let colors = '{[ colors ]}';
    let legendPosition = ('{[ legendPosition ]}').toString();
    const legendMap = ('{[ legendMap ]}').toString();
    const legendOrient = ('{[ legendOrient ]}').toString();
    const titleText = '{[ titleText ]}';
    const titleColor = '{[ titleColor ]}';
    const titlePosition = ('{[ titlePosition ]}').toString();
    const showLabel = Boolean('{[ showLabel ]}');
    const labelColor = '{[ labelColor ]}';
    let gridPadding = '{[ gridPadding ]}';
    const orient = '{[ orient ]}';
    let range = ('{[ range ]}').toString();
    const cellSize = ('{[ cellSize ]}').toString();
    const splitLineWidth = Number('{[ splitLineWidth ]}');
    const splitLineColor = '{[ splitLineColor ]}';
    const itemColor = '{[ itemColor ]}';
    const itemBorderColor = '{[ itemBorderColor ]}';
    const itemBorderWidth = Number('{[ itemBorderWidth ]}');
    const day_fristDay = '{[ day_fristDay ]}';
    const day_position = '{[ day_position ]}';
    const day_nameMap = ('{[ day_nameMap ]}').toString();
    const month_align = '{[ month_align ]}';
    const month_position = '{[ month_position ]}';
    const month_nameMap = ('{[ month_nameMap ]}').toString();
    const yearLabelPosition = ('{[ yearLabelPosition ]}').toString();
    const yearLabelFontFamily = ('{[ yearLabelFontFamily ]}').toString();
    const yearLabelFontSize = Number('{[ yearLabelFontSize ]}');
    const visualPosition = ('{[ visualPosition ]}').toString();
    const visualOrient = '{[ visualOrient ]}';
    const visualMin = Number('{[ visualMin ]}');
    const visualMax = Number('{[ visualMax ]}');
    const colorAlpha = '{[ colorAlpha ]}';
    const colorLightness = '{[ colorLightness ]}';
    const colorSaturation = '{[ colorSaturation ]}';
    const colorHue = '{[ colorHue ]}';
    const inRangeColor = '{[ inRangeColor ]}';
    const outRangeColor = '{[ outRangeColor ]}';
    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' });
    if (colors.indexOf(',') > -1) {
      colors = colors.split(',').map(item => item.trim())
    } else if (Boolean(colors)) {
      colors = [colors]
    }

    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',
      textStyle: {
        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;
    }

    let _legendMap;
    if (legendMap.indexOf(':') > 0) {
      _legendMap = {};
      let _legendArr;
      if (legendMap.indexOf(',') > 0) {
        _legendArr = legendMap.split(',');
      } else {
        _legendArr = [legendMap]
      }
      _legendArr.forEach(function(item) {
        if (item.indexOf(':') > 0) {
          const _item = item.trim().split(':').map(v => v.trim());
          _legendMap[_item[0].toString().toLocaleLowerCase()] = _item[1];
        }
      });
    }

    const getStrOrArr = function(str, mr) {
      if (str.indexOf(',') > 0) {
        return str.split(',').map(function(item) {
          const _str = item.trim();
          const _num = Number(_str);
          return isNaN(_num) ? _str : _num;
        })
      } else if (Boolean(str)) {
        const _str = str.trim();
        const _num = Number(_str);
        return  isNaN(_num) ? _str : _num;
      } else {
        return mr
      }
    };
    range = getStrOrArr(range, '');

    const calendar = {
      orient: orient,
      range: range,
      cellSize: getStrOrArr(cellSize, 20),
      splitLine: {
        show: !!splitLineWidth,
        lineStyle: {
          width: splitLineWidth,
          color: Boolean(splitLineColor) ? splitLineColor : '#000'
        }
      },
      itemStyle: {
        color: Boolean(itemColor) ? itemColor : '#fff',
        borderColor: Boolean(itemBorderColor) ? itemBorderColor : '#ccc',
        borderWidth: itemBorderWidth
      },
      dayLabel: {
        show: true,
        position: day_position,
        firstDay: day_fristDay,
        nameMap: getStrOrArr(day_nameMap, 'en')
      },
      monthLabel: {
        position: month_position,
        align: month_align,
        nameMap: getStrOrArr(month_nameMap, 'en')
      },
      yearLabel: {
        show: yearLabelPosition != 'none',
        position:yearLabelPosition || 'left',
        fontFamily: yearLabelFontFamily || 'sans-serif',
        fontSize: yearLabelFontSize
      }
    };

    if (gridPadding.indexOf(',') > -1) {
      gridPadding = gridPadding.split(',').map(item => item.trim());
      calendar.left = gridPadding[0];
      calendar.top = gridPadding[1];
      calendar.right = gridPadding[2] || gridPadding[0];
      calendar.bottom = gridPadding[3] || gridPadding[1];
    } else if (Boolean(gridPadding)) {
      calendar.left = gridPadding;
      calendar.top = gridPadding;
      calendar.right = gridPadding;
      calendar.bottom = gridPadding;
    }
    
    const tooltip = {
      show: true
    };

    const serieTemp = {
      type: 'heatmap',
      coordinateSystem: 'calendar',
      label: {
        show: showLabel,
        color: labelColor
      },
    };
    
    const visualMap = {
      type: 'continuous',
      orient: visualOrient,
      min: visualMin,
      max: visualMax,
      calculable: true,
      textStyle: {
        color: fontColor
      },
      inRange: {
      },
      outOfRange: {
      },
      controller: {},
    }
    if (Boolean(inRangeColor)) {
      const _inRangeColor = inRangeColor.indexOf(',') > 0 ? inRangeColor.split(',').map(function(color) { return  color.trim() }) : [inRangeColor];
      visualMap.color = _inRangeColor;
      visualMap.inRange.color = _inRangeColor;
      visualMap.controller.inRange = {
          color: _inRangeColor
      }
    }
    if (Boolean(outRangeColor)) {
      visualMap.outOfRange.color = [outRangeColor];
      visualMap.controller.outOfRange = { color: [outRangeColor] };
    }
    if (Boolean(colorAlpha)) {
      const _colorAlpha = colorAlpha.indexOf(',') > 0 ? colorAlpha.split(',').map(function(color) { return  Number(color.trim()) }) : [Number(colorAlpha)];
      visualMap.inRange.colorAlpha = _colorAlpha;
    }
    if (Boolean(colorLightness)) {
      const _colorLightness = colorLightness.indexOf(',') > 0 ? colorLightness.split(',').map(function(color) { return  Number(color.trim()) }) : [Number(colorLightness)];
      visualMap.inRange.colorLightness = _colorLightness;
    }
    if (Boolean(colorSaturation)) {
      const _colorSaturation = colorSaturation.indexOf(',') > 0 ? colorSaturation.split(',').map(function(color) { return  Number(color.trim()) }) : [Number(colorSaturation)];
      visualMap.inRange.colorSaturation = _colorSaturation;
    }
    if (Boolean(colorHue) && colorHue.indexOf(',') > 0) {
      const _colorHue = colorHue.split(',').map(function(color) { return  Number(color.trim()) });
      visualMap.inRange.colorHue = _colorHue;
    }
    
    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 myChart = window.echarts.init(this);
    const self = this;

    function initChart(source) {
      myChart.clear();
      const option = {
        title: title,
        tooltip: tooltip,
        legend: legend,
        calendar: calendar,
        dataset: {
          source: source
        },
        visualMap: visualMap,
        series: serieTemp
      };
      if (_legendMap) {
        const dimensions = source[0].map(item => _legendMap[item.toLocaleLowerCase()] || item);
        option.series.dimensions = dimensions;
      }

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

    initChart(defaultData);

    window.addEventListener('resize', function () {
      myChart.resize();
    }, false)
    let hasTransfer = false;
    // 有 dashboardHost 说明是运行模式
    if (window.spSocket) {
      var eventName = `call-` + self.getAttribute('id');
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          let _in1Str = _data.data.in1;
          if(_in1Str) {
            const source = JSON.parse(_in1Str);

            if (!hasTransfer) {
              initChart(source);
              hasTransfer = true
            } else {
              myChart.setOption({
                dataset: {
                  source: source
                }
              })
            }
          }
        }
      });
    }

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

  onViewInit() {
    this.updateScript();
    const evn = echartsBasicListen + `
      change:defaultData
      change:gridPadding
      change:orient
      change:range
      change:cellSize
      change:splitLineWidth
      change:splitLineColor
      change:itemColor
      change:itemBorderColor
      change:itemBorderWidth
      change:day_fristDay
      change:day_position
      change:day_nameMap
      change:month_align
      change:month_position
      change:month_nameMap
      change:yearLabelPosition
      change:yearLabelFontFamily
      change:yearLabelFontSize
      change:showLabel
      change:labelColor
      change:visualPosition
      change:visualOrient
      change:visualMin
      change:visualMax
      change:colorAlpha
      change:colorLightness
      change:colorSaturation
      change:colorHue
      change:inRangeColor
      change:outRangeColor
    `;
    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)));
  }
}
