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

export default {

  // 组件名称
  name: list,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${list}" class="${list}">
      </div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${list} {
          overflow: auto;
        }
        .${list} > ul {
          margin: 0;
          padding: 0;
          list-style: none;
          overflow: hidden;
        }
        .${list} > ul.header {
          font-weight: bold;
        }
        .${list} > ul > li {
          margin: 0;
          padding: 0;
          display: flex;
          align-items: center;
        }
        .${list} > ul > li > span {
          flex: 0 0 auto;
          padding: 0 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  // blockOptions() {
  //   return {
  //     category: CATEGORIES.TEXT,
  //     label: "列表",
  //     attributes: { class: 'fa fa-list' },
  //   };
  // },

  spOptions() {
    return {
      label: '列表',
      icon: 'globe',
      docUrl: '#',
      author: '秋水',
      email: 'qiushui.smy@xuelangyun.com',
      inPorts: [{
        uuid: 'in1',
        subType: 'json',
        description: {
          zh_CN: '输入Json'
        }
      }],
    }
  },

  // 组件属性
  componentOptions() {
    return {
      droppable: false,
      resizable: true,
      dmode: 'absolute',
      highlightable: false,
      disableChildEdit: true,
      traits: [{
        name: 'fontSize',
        label: '字体大小',
        changeProp: 1,
        type: 'number',
        min: 8
      }, {
        name: 'color',
        label: '字体颜色',
        changeProp: 1,
        type: 'color'
      }, {
        name: 'thColor',
        label: '列名字体颜色',
        changeProp: 1,
        type: 'color'
      }, {
        name: 'rowHeight',
        label: '行高',
        changeProp: 1,
        type: 'number',
        min: 20
      }, {
        name: 'oddBgColor',
        label: '跳行背景色',
        changeProp: 1,
        type: 'color'
      }, {
        name: 'borderColor',
        label: '边框颜色',
        changeProp: 1,
        type: 'color'
      }, {
        name: 'thColor',
        label: '列名颜色',
        changeProp: 1,
        type: 'color'
      }, {
        name: 'hasTableTh',
        label: '返回数据是否包含表头',
        changeProp: 1,
        type: 'checkbox'
      }, {
        name: 'customTableTh',
        label: '自定义表头列名',
        changeProp: 1,
        placeholder: 'eg. ID,姓名,性别,年龄,采集时间'
      }, {
        name: 'flowUp',
        label: '向上滚动',
        changeProp: 1,
        type: 'checkbox'
      }, {
        name: 'pinlv',
        label: '数据刷新频率',
        changeProp: 1,
        type: 'select',
        options: [{id: 'auto', name: '自动'}, {id: '600', name: '10分钟'}, {id: '3600', name: '1小时'}]
      },{
        name: 'topN',
        label: 'TopN',
        changeProp: 1,
        type: 'number',
        min: 0
      },{
        name: 'fontSizeTopN',
        label: '字体大小(TopN)',
        changeProp: 1,
        type: 'number',
        min: 8
      },{
        name: 'colorTopN',
        label: '字体颜色(TopN)',
        changeProp: 1,
        type: 'color'
      },{
        name: 'rowHeightTopN',
        label: '行高(TopN)',
        changeProp: 1,
        type: 'number',
        min: 20
      },{
        name: 'weightTopN',
        label: '字体粗细(TopN)',
        changeProp: 1,
        type: 'select',
        options: [{ id: 'auto', name: '自动' },{ id: 'thin', name: '细' },{ id: 'normal', name: '常规' }, { id: 'bold', name: '粗' }]
      },{
        name: 'isColumnWidth',
        label: '自定义列宽',
        changeProp: 1,
        type: 'checkbox'
      },{
        name: 'flexBasis',
        label: '各列宽百分比',
        changeProp: 1,
      },{
        name: 'defaultData',
        changeProp: 1,
        type: 'hide'
      }],
      defaultData:JSON.stringify([
        ["id", "姓名", "性别", "年龄", "采集时间"],
        ["001", "李磊", "男", "12", "2020-01-02 14:28:36"],
        ["002", "王华", "女", "42", "2020-01-02 14:28:36"],
        ["003", "孙南", "男", "34", "2020-01-02 14:28:36"],
        ["004", "李明", "男", "12", "2020-01-02 14:28:36"],
        ["005", "孙华", "女", "42", "2020-01-02 14:28:36"],
        ["006", "苏如花", "男", "34", "2020-01-02 14:28:36"]
      ]).replace(/\"/g, "\\\""),
      fontSize: 14,
      color: '#333',
      oddBgColor: "none",
      borderColor: '#ddd',
      thColor: "none",
      rowHeight: 30,
      hasTableTh: true,
      customTableTh: '',
      flowUp: false,
      pinlv: 'auto',
      topN: 0,
      fontSizeTopN: 14,
      colorTopN: '#333',
      rowHeightTopN: 30,
      weightTopN: 'auto',
      isColumnWidth: true,
      flexBasis: "15,20,15,15,35"
    }
  },

  onModelScript() {
    const fontSize = parseInt('{[ fontSize ]}');
    const color = '{[ color ]}';
    const borderColor = '{[ borderColor ]}';
    const oddBgColor = '{[ oddBgColor ]}';
    const thColor = '{[ thColor ]}';
    const hasTableTh = Boolean('{[ hasTableTh ]}');
    const customTableTh = '{[ customTableTh ]}';
    const showTableTh = hasTableTh || Boolean('{[ customTableTh ]}');
    const flowUp = Boolean('{[ flowUp ]}');
    const rowHeight = parseInt('{[ rowHeight ]}');
    const topN = Boolean('{[ topN ]}') ? parseInt('{[ topN ]}') : 0;
    const fontSizeTopN = parseInt('{[ fontSizeTopN ]}');
    const colorTopN = '{[ colorTopN ]}';
    const rowHeightTopN = parseInt('{[ rowHeightTopN ]}');
    const defaultData = JSON.parse('{[ defaultData ]}'.replace(/\\\"/g, "\""));
    let weightTopN = '{[ weightTopN ]}';
    if(weightTopN === 'thin') {
      weightTopN = 300;
    }
    let isColumnWidth = Boolean('{[ isColumnWidth ]}');
    let flexBasis =  '{[ flexBasis ]}';
    if( Boolean(flexBasis)) {
      flexBasis = flexBasis.split(',').map(item => item.trim())
    } else {
      flexBasis = [];
    }

    let pinlv = ('{[ pinlv ]}').toString();
    const self = this;
    const _id = self.getAttribute('id');
    const eventName = `call-` + _id;
    var timerId = 'timer-' + _id;
    if (window.timer) {
      window.timer[timerId] && clearInterval(window.timer[timerId]);
    } else {
      window.timer = {};
    }
    window.timer[timerId]  = null;

    $(self).empty();
    $(self).append('<ul></ul>');
    $(self).css({'font-size': fontSize + 'px', 'color': color});
    let $header = null;
    const $body = $(self).children('ul');
    if (showTableTh) {
      $(self).prepend('<ul class="header"></ul>');
      $header = $(self).children('ul.header');
    }
    const render = function (data) {
      if (window.timer[timerId]) {
        clearInterval(window.timer[timerId]);
        window.timer[timerId]  = null;
      }
      $body.empty();
      const topNStartIndex = showTableTh ? 1 : 0;
      const topNEndIndex = showTableTh ? topN : topN - 1;

      // 如果设置了自定义表头且返回数据不包含表头，则向data头部追加自定义表头
      // 如果设置了自定义表头且返回数据包含表头，则替换返回数据里的表头
      if (customTableTh !== '') {
        if (hasTableTh) {
          data.shift();
        }
        data.unshift(customTableTh.split(','));
      }

      $.each(data, function (index, row) {
        const $li = $('<li></li>');
        let $children;
        if (isColumnWidth) {
          const dom = [];
          for(let i = 0; i < row.length; i += 1) {
            dom.push(`<span style="flex-basis:${flexBasis[i]}%;" >${row[i]}</span>`)
          }
          $children = $(dom.join(''));
        } else {
          const _w = (100 / row.length).toFixed(2) + "%";
          $children = $('<span>' + row.join('</span><span>') + '</span>');
          $children.css('flex-basis', _w);
        }
        $li.height(rowHeight);
        if (index == 0 && showTableTh) {
          $header.empty();
          $li.css({ 'border-bottom': '1px solid ' + borderColor, 'color': thColor || color });
          $li.append($children);
          $header.append($li);
        } else {
          $li.append($children);
          $body.append($li);
        }
        if (!oddBgColor) {
          $li.css('border-top', '1px solid ' + borderColor);
        } else if (index % 2 == 0) {
          $li.css("background-color", oddBgColor);
        }
        if(index >= topNStartIndex && index <= topNEndIndex) {
          $li.css({'height':rowHeightTopN + 'px', 'font-size': fontSizeTopN + 'px', 'color': colorTopN, 'font-weight': weightTopN });
          if(weightTopN !== 'auto') {
            $li.css({'font-weight': weightTopN });
          }
        }
      });
      if (flowUp) {
        setBodyFlowup();
      } else if (window.timer[timerId]) {
        clearInterval(window.timer[timerId]);
        window.timer[timerId]  = null;
      }
    };

    const setBodyFlowup = function () {
      $(self).css({overflow: 'hidden'});
      const li_h = rowHeight;
      window.timer[timerId] = setInterval(function () {
        if (!$(document).find('#' + _id).length) {
          clearInterval(window.timer[timerId]);
          window.timer[timerId]  = null;
        }
        const timer = window.timer[timerId];
        $body.children().first().animate({marginTop: -li_h + "px"}, 1000, function () {
          if (window.timer[timerId] == timer) {
            $(this).appendTo($body);
            $(this).css({marginTop: 0});
          }
        })
      }, 2000)
    };

    render(defaultData);
    pinlv = pinlv !== 'auto' ? Number(pinlv) : 'auto';
    if (window.spSocket) {
      var rendered = null;
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          var now = (new Date()).getTime();
          if (pinlv == 'auto' || (!rendered || now - rendered > pinlv * 1000)) {
            if (_data.data.in1) {
              let data = JSON.parse(_data.data.in1);
              render(data);
              rendered = now;
            }
          }
        }
      });
    }
  },

  onViewInit() {
    const evn = "change:defaultData change:flexBasis change:isColumnWidth change:topN change:fontSizeTopN change:colorTopN change:rowHeightTopN change:weightTopN change:color change:fontSize change:borderColor change:oddBgColor change:thColor change:flowUp change:hasTableTh change:customTableTh change:rowHeight change:pinlv"
    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)));
  }
}
