import { Progress, CATEGORIES } from '../../configuration/constants'

export default {

  // 组件名称
  name: Progress,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${Progress}" class="${Progress}">
      </div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${Progress} {
          display: flex;
          padding: 0 10px;
          width: 200px;
          height: 32px;
          align-items: stretch;
        }
        .${Progress}-track {
          display: flex;
          margin: 10px 0;
          flex: 1 1 auto;
          border-style: solid;
        }
        .${Progress}-thumb {
          width: 0;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: flex-end;
        }
        .${Progress}-label {
          align-self: center;
          line-height: 1;
          font-size: inherit;
          color: inherit;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: `
        <svg class="gjs-block-svg" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
          <rect x="2" y="8" width="20" height="8" rx="2" ry="2" strokeWidth="1" stroke="#1890ff" fill="none" />
          <rect x="3" y="9" width="8" height="6" rx="1" ry="1" fill="#1890ff" />
        </svg>
        <div class="gjs-block-label">进度条</div>
      `
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '进度条',
      icon: 'globe',
      docUrl: 'https://www.yuque.com/docs/share/fb71c31f-3fa7-4f00-b704-16fa42e07d95#',
      author: '秋水',
      email: 'qiushui.smy@xuelangyun.com',
      inPorts: [
        {
          uuid: 'in1',
          subType: 'all',
          description: {
            zh_CN: '输入0-100的数字'
          }
        }
      ]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: Progress,
      droppable: false,
      childrenSelectable: false,
      traits: [{
        name: 'border',
        label: '边框',
        changeProp: 1,
        type: 'checkbox'
      }, {
        name: 'borderRadius',
        label: '圆角(px)',
        type: 'number',
        min: 0,
        step: 1,
        changeProp: 1
      }, {
        type: 'color',
        name: 'progressColor',
        label: '颜色',
        changeProp: 1,
      }, {
        name: 'labelType',
        label: '标签',
        changeProp: 1,
        type: 'select',
        options: [{id: 'null', name: '无标签'}, {id: 'inner', name: '内标签'}, {id: 'outer', name: '外标签'}]
      }, {
        name: 'labelInnerPosition',
        label: '标签位置',
        changeProp: 1,
        type: 'select',
        options: [{id: 'flex-start', name: '左侧'}, {id: 'center', name: '居中'}, {id: 'flex-end', name: '右侧'}]
      }, {
        name: 'writing-mode',
        label: '垂直文本',
        changeProp: 1,
        type: 'checkbox',
      }, {
        name: 'labelPadding',
        label: '标签边距',
        changeProp: 1,
        type: 'number',
      }, {
        name: 'defaultValue',
        label: '默认值',
        changeProp: 1,
        type: 'number',
        min: 0
      }],
      "border": true,
      "borderRadius": 5,
      "progressColor": "#1890ff",
      "labelType": "outer",
      "labelInnerPosition": "flex-end",
      'writing-mode': false,
      "labelPadding": 8,
      "defaultValue": 40
    }
  },

  onModelScript() {
    const border = Boolean('{[ border ]}');
    const borderRadius = Number('{[ borderRadius ]}');
    const progressColor = '{[ progressColor ]}';
    const labelType = ('{[ labelType ]}').toString();
    const labelInnerPosition = ('{[ labelInnerPosition ]}').toString();
    const writingMode = Boolean('{[ writing-mode ]}');
    const labelPadding = Boolean('{[ labelPadding ]}') ? Number('{[ labelPadding ]}') : 0;
    const defaultValue = Boolean('{[ defaultValue ]}') ? Number('{[ defaultValue ]}') : 0;

    const self = this;

    function transferColorToRgba(color, alpha=1) {
      if (typeof color !== 'string' && !(color instanceof String)) return console.error("请输入16进制字符串形式的颜色值");
      color = color.charAt(0) === '#' ? color.substring(1) : color;
      if (color.length !== 6 && color.length !== 3) return console.error("请输入正确的颜色值")
      if (color.length === 3) {
          color = color.replace(/(\w)(\w)(\w)/, '$1$1$2$2$3$3')
      }
      var reg = /\w{2}/g;
      var colors = color.match(reg);
      for (var i = 0; i < colors.length; i++) {
          colors[i] = parseInt(colors[i], 16).toString();
      }
      return 'rgba(' + colors.join() + ',' + alpha + ')';
    }

    const trackBgColor = transferColorToRgba(progressColor, 0.3);

    const innerRadius = border ? borderRadius - 2 : borderRadius;
    $(self).children('.progress-comp-track')
      .css({"background-color": trackBgColor, "border-color": progressColor, "border-radius": borderRadius + "px"})
      .children('.progress-comp-thumb').css({"background-color": progressColor, "border-radius": innerRadius + "px"});
    if (border) {
      $(self).children('.progress-comp-track').css({"border-width": "1px", "padding": "2px"})
    } else {
      $(self).children('.progress-comp-track').css({"border-width": 0, "padding": 0})
    }

    $(self).find('.progress-comp-label').remove();
    const $label = $('<span class="progress-comp-label"></span>');
    const $thumb = $(self).find('.progress-comp-thumb');

    const renderInner = function() {
      if ($thumb.width() < $label.innerWidth()) {
        $thumb.after($label);
      } else {
        $thumb.append($label);
      }
    };

    if (labelType == 'inner') {
      if (labelInnerPosition == 'flex-start') {
        $label.css({'padding-left': labelPadding, 'padding-right': 8});
      } else {
        $label.css({'padding-left': 8, 'padding-right': labelPadding});
      }
      $thumb.css('justify-content', labelInnerPosition).append($label);
      requestAnimationFrame(renderInner);
    } else if (labelType == 'outer') {
      if (labelInnerPosition == 'flex-start') {
        $label.css({'padding-left': 0, 'padding-right': labelPadding});
        $(self).prepend($label);
      } else {
        $label.css({'padding-left': labelPadding, 'padding-right': 0});
        $(self).append($label);
      }
    }
    if (writingMode) {
      $label.css('writingMode', 'vertical-lr');
    }
    $(self).find('.progress-comp-label').text(defaultValue + "%");
    $(self).find('.progress-comp-thumb').css("width", defaultValue + "%");

    if (window.spSocket) {
      // $(self).find('.progress-comp-thumb').css("width", "0%");
      // $(self).find('.progress-comp-label').text('');
      var eventName = `call-` + self.getAttribute('id');
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          let value = _data.data.in1;
          if (value) {
            $(self).find('.progress-comp-thumb').css("width", value + "%")
            $(self).find('.progress-comp-label').text(value + "%")
          }
          if (labelType == 'inner') {
            requestAnimationFrame(renderInner);
          }
        }
      });
    }
  },

  onViewInit() {
    const comps = this.model.get('components');
    if (!comps.length) {
      comps.reset();
      comps.add(`
        <div class="${Progress}-track">
          <div class="${Progress}-thumb">
          </div>
        </div>
        <span class="${Progress}-label"></span>
      `)
    }
    const evn = "change:border change:borderRadius change:progressColor change:labelType change:writing-mode change:labelPadding change:labelInnerPosition change:defaultValue"
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
  }
}
