import React from "react";
import ReactDOM from "react-dom";
import moment from 'moment';
import { Popover, Input, Select, Button, Tooltip, Menu } from 'antd';
import {
  textRef, headline, groupText, buttonSwitch, uploadRef, mdcRadioGroup, mdcCheckboxGroup,
  select, mdcSlider, pageAdaptor
} from '../../../configuration/constants'
import 'antd/dist/antd.min.css'
import './index.less'

class ToolbarList extends React.Component {
  constructor(props) {
    super(props);
    this.editor = props.editor;
    this.state = {
      resizeVisible: false,
      staticDataSource: props.defaultData,
      multiSelector: this.editor.getModel().get("modules").filter(val => val.name === "MultiSelector")[0],
      initialZoom: null,
      collapseMenu: false,
      currentDrag: false,
      computeSizeInfo: this.computeSize()
    };
    this.textMenu = [
      { icon: 'icon-kuhei-wenben', label: '文本', id: textRef },
      { icon: 'icon-kuhei-biaoti', label: '标题', id: headline },
      { icon: 'icon-kuhei-duohangwenben', label: '多行文本', id: groupText },
    ];
    this.buttonMenu = [
      { icon: 'icon-kuhei-anniu', label: '按钮', id: 'button-comp' },
      { icon: 'icon-kuhei-kaiguan', label: '开关', id: buttonSwitch },
      { icon: 'icon-kuhei-Tab-heng', label: 'Tab列表-横', id: 'tabs' },
      // {icon: 'icon-Tab-shu', label: 'Tab列表-竖', id:},
      { icon: 'icon-kuhei-shangchuanwenjian', label: '上传文件', id: uploadRef },
    ];
    this.selectMenu = [
      { icon: 'icon-kuhei-danxuan', label: '单选', id: mdcRadioGroup },
      { icon: 'icon-kuhei-duoxuan', label: '多选', id: mdcCheckboxGroup },
      { icon: 'icon-kuhei-xialaxuanze', label: '下拉选择', id: select },
      // {icon: 'icon-xialaduoxuan', label: '下拉多选', id:},
    ];
    this.inputMenu = [
      { icon: 'icon-kuhei-shurukuang', label: '输入框', id: 'sp-control-input' },
      { icon: 'icon-kuhei-huakuai', label: '滑块', id: mdcSlider },
    ];
    this.alignmentMenu = [
      { icon: 'icon-kuhei-zuoduiqi', label: '左对齐', id: 'Left' },
      { icon: 'icon-kuhei-youduiqi', label: '右对齐', id: 'Right' },
      { icon: 'icon-kuhei-dingduiqi', label: '顶对齐', id: 'Top' },
      { icon: 'icon-kuhei-diduiqi', label: '底对齐', id: 'Bottom' },
      { icon: 'icon-kuhei-shuipingjuzhongduiqi', label: '左右居中对齐', id: 'Center' },
      { icon: 'icon-kuhei-chuizhijuzhongduiqi', label: '上下居中对齐', id: 'Middle' },
    ]
  }

  componentDidMount() {
    document.addEventListener("wheel", this.handleZoom);
    document.addEventListener("keydown", this.handleKeyDown);
    const updateToolbarStyle = (width) => {
      if (width < 500) {
        this.setState({ collapseMenu: true })
      } else {
        this.setState({ collapseMenu: false })
      }
    }
    const $editor = this.editor.Canvas.em.view.$el;
    const framesArea = $editor.find('[data-frames]').get(0);
    if (framesArea) {
      const MutationObserver = window.MutationObserver || window.webkitMutationObserver || window.MozMutationObserver;
      const mutationObserver = new MutationObserver((mutations) => {
        if (framesArea.offsetWidth && this.state.initialZoom == null) {
          this.setCanvasTransform();
        }
      });
      mutationObserver.observe(framesArea, {
        attributes: true, // 属性的变动
        attributeFilter: ['style'],
      });
    }
    setTimeout(() => {
      let element = document.querySelector('.frontpanel-toolbar-container')
      this.observer = new ResizeObserver((mutationList) => {
        updateToolbarStyle($('.frontpanel-toolbar-container').width())
      })
      this.observer.observe(element, { attributes: true, attributeFilter: ['style'], attributeOldValue: true });
    }, 0);
    // document.addEventListener('keydown', (event) => {
    //   const { currentDrag } = this.state;
    //   if (event.keyCode == 32 && currentDrag) {
    //     this.setState({currentDrag: false});
    //   }
    // });
  }

  componentWillUnmount() {
    document.removeEventListener("wheel", this.handleZoom);
    document.removeEventListener("keydown", this.handleKeyDown);
  }

  handleZoom = event => {
    if (event.altKey || event.metaKey) {
      const { editor } = this;
      const delta = Math.max(
        -1,
        Math.min(1, event.wheelDelta || -event.detail)
      );
      const zoom = editor.Canvas.getZoom("zoom");
      let _zoom = zoom + delta * 2;
      if (_zoom < 1) {
        _zoom = 1;
      }
      if (_zoom !== zoom) {
        editor.Canvas.setZoom(_zoom);
        this.setState({
          initialZoom: _zoom + '%'
        });
      }
    }
  }

  handleKeyDown = (event) => {
    const { currentDrag } = this.state;
    if (event.keyCode == 32 && currentDrag) {
      this.setState({currentDrag: false});
    } else if (event.altKey) {
      // alt
      if (event.keyCode == 187) {
        // +
        this.plusControl();
      } else if (event.keyCode == 189){
        // -
        this.minusControl();
      }
    }
  }

  updateProps(defaultData, editor) {
    this.editor = editor;
    this.setCanvasTransform();
    this.setState({
      staticDataSource: defaultData,
      multiSelector: editor.getModel().get("modules").filter(val => val.name === "MultiSelector")[0],
    });
  }

  handleDrag = event => {
    event.stopPropagation();
    const { currentDrag } = this.state;
    if (currentDrag) {
      this.editor.stopCommand('core:canvas-move');
    } else {
      this.editor.runCommand('core:canvas-move');
    }
    this.setState({
      currentDrag: !currentDrag
    });
  }

  handleEditSize = event => {

  }

  handleSizeEditorVisibleChange = visible => {
    this.setState({ resizeVisible: visible });
  }

  getUnit(str) {
    switch (true) {
      case str.indexOf('px') > 0:
        return 'px';
      case str.indexOf('%') > 0:
        return '%';
      case str.indexOf('vw') > 0:
        return 'vw';
      case str.indexOf('vh') > 0:
        return 'vh';
    }
  }

  setCanvasTransform() {
    const $editor = this.editor.Canvas.em.view.$el;
    const framesArea = $editor.find('[data-frames]').get(0);
    if (framesArea && framesArea.offsetWidth) {
      const width = framesArea.offsetWidth;
      const height = framesArea.offsetHeight;
      const p_width = $editor.innerWidth();
      const p_height = $editor.innerHeight();
      const zoom = Math.floor((Math.min(p_width / width, p_height / height)) * 100);
      const x = Math.round((p_width - width) / 2);
      const y = Math.round((p_height - height) / 2);
      // this.editor.Canvas.setZoom(zoom);
      this.editor.Canvas.getCanvasView().model.set('zoom', zoom);
      this.setState({
        initialZoom: zoom + '%'
      });
      this.editor.Canvas.getCanvasView().model.set('x', x);
      this.editor.Canvas.getCanvasView().model.set('y', y);
    }
  }

  handleResizeCanvas = () => {
    const width = $('.width-value')[0].value;
    const widthUnit = $('.width-unit .ant-select-selection-item')[0].title;
    const height = $('.height-value')[0].value;
    const heightUnit = $('.height-unit .ant-select-selection-item')[0].title;
    this.onResizeCanvas(width, widthUnit, height, heightUnit);
    this.handleCancelResize();
  }

  onResizeCanvas = (width, widthUnit, height, heightUnit) => {
    const $iframe = this.editor.Canvas.getFrameEl();
    const $editor = this.editor.Canvas.em.view.$el;
    const framesArea = $editor.find('[data-frames]').get(0);
    if (width !== 0 && height !== 0) {
      if ($iframe) {
        $iframe.style.width = `${width}${widthUnit}`;
        $iframe.style.height = `${height}${heightUnit}`;
      }
      if (framesArea) {
        framesArea.style.width = `${width}${widthUnit}`;
        framesArea.style.height = `${height}${heightUnit}`;
        if (framesArea.offsetWidth) {
          this.rendered = true;
          this.setCanvasTransform();
        }
      }
      this.editor.getWrapper()
        .addStyle({ width: `${width}${widthUnit}!important`, height: `${height}${heightUnit}!important` });
    }
    this.editor.store();
  }

  handleCancelResize = () => {
    this.setState({
      resizeVisible: false
    });
  }

  computeSize() {
    let _width, _widthUnit, _height, _heightUnit;
    const { width, height } = this.editor.getWrapper().getStyle();
    if (!width || !height) {
      _width = 1920;
      _height = 1080;
      _widthUnit = 'px';
      _heightUnit = 'px';
    } else {
      _widthUnit = this.getUnit(width);
      _heightUnit = this.getUnit(height);
      _width = parseInt(width);
      _height = parseInt(height);
    }

    if (_width === 0 || isNaN(_width) || _height === 0 || isNaN(_height)) {
      _width = 1920;
      _height = 1080;
      _widthUnit = 'px';
      _heightUnit = 'px';
    }

    _width = _width.toFixed(2);
    _height = _height.toFixed(2);
    return { _width, _widthUnit, _height, _heightUnit };
  }

  handleChangeUnit = value => {
    const { _width, _height } = this.state.computeSizeInfo
    this.setState({
      computeSizeInfo: {
        _width,
        _height,
        _widthUnit: value,
        _heightUnit: value
      }
    });
  }
  renderSizeEditor = () => {
    const { _width, _widthUnit, _height, _heightUnit } = this.state.computeSizeInfo;
    return (
      <div className="resize-form">
        <div className="resize-filed">
          <span>宽度：</span>
          <Input className="width-value" defaultValue={_width} />
          <Select className="width-unit" value={_widthUnit} onChange={this.handleChangeUnit} dropdownClassName="toolbar-dark-dropdown">
            <Select.Option value="px">px</Select.Option>
            <Select.Option value="%">%</Select.Option>
            <Select.Option value="vw">vw</Select.Option>
            <Select.Option value="vh">vh</Select.Option>
          </Select>
        </div>
        <div className="resize-filed height-filed">
          <span>高度：</span>
          <Input className="height-value" defaultValue={_height} />
          <Select className="height-unit" value={_heightUnit} onChange={this.handleChangeUnit} dropdownClassName="toolbar-dark-dropdown">
            <Select.Option value="px">px</Select.Option>
            <Select.Option value="%">%</Select.Option>
            <Select.Option value="vw">vw</Select.Option>
            <Select.Option value="vh">vh</Select.Option>
          </Select>
        </div>
        <div className="resize-button">
          <Button size="small" onClick={this.handleCancelResize}>取消</Button>
          <Button type="primary" size="small" onClick={this.handleResizeCanvas}>确定</Button>
        </div>
      </div>
    )
  }

  handleInsertComToCanvas = event => {
    const { key } = event;
    const blockInfo = this.editor.BlockManager.get(key);
    if (blockInfo) {
      const content = blockInfo.attributes.content;
      const components = this.editor.addComponents(content);
      components[0].setStyle({ position: 'absolute', top: '50px', left: '50px' });
    }
  }
  handleAlign = event => {
    const { key } = event;
    this.state.multiSelector.handleAlign(key)
  }

  renderComponentMenu = (menuList, clickEvent) => {
    const iconSuffix = Boolean(window.appConfig.appReadOnly) ? '-jinyong' : '';
    return (
      <Menu className="component-menu" onClick={clickEvent} selectedKeys={[]}>
        {menuList.map(val => (
          <Menu.Item value={val.id} key={val.id} disabled={Boolean(window.appConfig.appReadOnly)}>
            <svg className="svg-icon" aria-hidden="true"><use xlinkHref={`#${val.icon}${iconSuffix}`}></use></svg>
            <span>{val.label}</span>
          </Menu.Item>
        ))}
      </Menu>
    )
  }

  handleCombination = action => {
    this.state.multiSelector.groupHandler[`${action}Group`]();
  }

  minusControl() {
    const step = 10;
    let value = parseInt(this.state.initialZoom);
    const surplus = value % step;
    if (surplus) {
      value -= step - surplus;
    } else {
      value -= step;
    }
    if (value <= 0) {
      value = 1;
    }
    this.setState({
      initialZoom: value + '%'
    });
    this.editor.Canvas.setZoom(value);
  }

  plusControl() {
    const step = 10;
    let value = parseInt(this.state.initialZoom);
    const surplus = value % step;
    if (surplus) {
      value += step - surplus;
    } else {
      value += step;
    }
    this.setState({
      initialZoom: value + '%'
    });
    this.editor.Canvas.setZoom(value);
  }

  handleSetZoom = zoom => {
    if (zoom == 'auto') {
      this.setCanvasTransform();
      this.setState({
        initialZoom: this.editor.Canvas.getZoom() + '%'
      });
    } else if (zoom == '100') {
      this.setState({
        initialZoom: '100%',
      });
      this.editor.Canvas.setZoom(zoom);
    } else if (zoom == 'add') {
      this.plusControl();
    } else {
      this.minusControl();
    }
  }

  handleChangeZoom = event => {
    this.setState({
      initialZoom: event.target.value
    });
  }

  handlePressEnter = event => {
    const value = event.target.value.split('%');
    try {
      if (value.length > 0 && Number(value[0]) && Number(value[0]) > 0) {
        this.setState({
          initialZoom: value[0] + '%'
        });
        this.editor.Canvas.setZoom(value[0]);
      } else {
        this.setState({
          initialZoom: '100%'
        });
        this.editor.Canvas.setZoom('100');
      }
    } catch(error) {
      this.setState({
        initialZoom: '100%'
      });
      this.editor.Canvas.setZoom('100');
    }
  }

  renderScalcMenu() {
    const { initialZoom } = this.state;
    const isMac = /macintosh|mac os x/i.test(navigator.userAgent);
    const keyMap = isMac ? '⌥' : 'Alt';
    return (
      <Menu className="component-menu scalc-menu" onClick={event => this.handleSetZoom(event.key)} selectedKeys={[initialZoom]}>
        <Menu.Item value="auto" key="auto">自动合适大小</Menu.Item>
        <Menu.Item value="100" key="100">实际尺寸</Menu.Item>
        <Menu.Item className="separator-line" key="separator-line" disabled></Menu.Item>
        <Menu.Item value="add" key="add">
          <span className="menu-item-info">放大</span>
          <span className="menu-item-tooltip">{keyMap}++</span>
        </Menu.Item>
        <Menu.Item value="minus" key="minus" disabled={initialZoom == '1%'}>
          <span className="menu-item-info">缩小</span>
          <span className="menu-item-tooltip">{keyMap}+-</span>
        </Menu.Item>
        <Menu.Item value="tooltip" key="tooltip" disabled><span className="menu-item-tooltip">使用“{keyMap}+鼠标滚轮”可快速缩放</span></Menu.Item>
      </Menu>
    )
  }

  renderOtherToolbar(direction) {
    const { multiSelector, initialZoom } = this.state;
    const multiSelected = multiSelector ? multiSelector.multiSelected : false;
    const popoverPlacement = direction === 'horizontal' ? 'bottom' : 'right';
    const iconSuffix = Boolean(window.appConfig.appReadOnly) || !multiSelected ? '-jinyong' : '';
    return (
      <div className={`other-menu ${direction}`}>
        <ul className="frontpanel-toolbar component-toolbar">
          <Popover
            overlayClassName="toolbar-dark-dropdown"
            content={this.renderComponentMenu(this.textMenu, this.handleInsertComToCanvas)}
            title={null}
            placement={popoverPlacement}
          >
            <li className="frontpanel-toolbar-item dropdown-item frontpanel-toolbar-text">
              <svg className="svg-icon" aria-hidden="true"><use xlinkHref="#icon-kuhei-wenben"></use></svg>
              { direction === 'horizontal' ?
                <svg className="svg-icon dropdown-icon" aria-hidden="true"><use xlinkHref='#icon-kuhei-jiantou-xia'></use></svg> :
                <div className="vertical-content">
                  <span>文本</span>
                  <i className='spicon icon-jiantou-you1'></i>
                </div>
              }
            </li>
          </Popover>
          <Popover
            overlayClassName="toolbar-dark-dropdown"
            content={this.renderComponentMenu(this.buttonMenu, this.handleInsertComToCanvas)}
            title={null}
            placement={popoverPlacement}
          >
            <li className="frontpanel-toolbar-item dropdown-item frontpanel-toolbar-button">
              <svg className="svg-icon" aria-hidden="true"><use xlinkHref="#icon-kuhei-anniu"></use></svg>
              { direction === 'horizontal' ?
                <svg className="svg-icon dropdown-icon" aria-hidden="true"><use xlinkHref='#icon-kuhei-jiantou-xia'></use></svg> :
                <div className="vertical-content">
                  <span>按钮</span>
                  <i className='spicon icon-jiantou-you1'></i>
                </div>
              }
            </li>
          </Popover>
          <Popover
            overlayClassName="toolbar-dark-dropdown"
            content={this.renderComponentMenu(this.selectMenu, this.handleInsertComToCanvas)}
            title={null}
            placement={popoverPlacement}
          >
            <li className="frontpanel-toolbar-item dropdown-item frontpanel-toolbar-select">
              <svg className="svg-icon" aria-hidden="true"><use xlinkHref="#icon-kuhei-duoxuan"></use></svg>
              { direction === 'horizontal' ?
                <svg className="svg-icon dropdown-icon" aria-hidden="true"><use xlinkHref='#icon-kuhei-jiantou-xia'></use></svg> :
                <div className="vertical-content">
                  <span>选择</span>
                  <i className='spicon icon-jiantou-you1'></i>
                </div>
              }
            </li>
          </Popover>
          <Popover
            overlayClassName="toolbar-dark-dropdown"
            content={this.renderComponentMenu(this.inputMenu, this.handleInsertComToCanvas)}
            title={null}
            placement={popoverPlacement}
          >
            <li className="frontpanel-toolbar-item dropdown-item frontpanel-toolbar-input">
              <svg className="svg-icon" aria-hidden="true"><use xlinkHref="#icon-kuhei-shurukuang"></use></svg>
              { direction === 'horizontal' ?
                <svg className="svg-icon dropdown-icon" aria-hidden="true"><use xlinkHref='#icon-kuhei-jiantou-xia'></use></svg> :
                <div className="vertical-content">
                  <span>输入</span>
                  <i className='spicon icon-jiantou-you1'></i>
                </div>
              }
            </li>
          </Popover>
        </ul>
        {direction !== 'horizontal' && <div className="separator"></div>}
        {/* <ul className="frontpanel-toolbar">
          <li className="frontpanel-toolbar-item frontpanel-toolbar-bottom">
            <svg className="svg-icon" aria-hidden="true"><use xlinkHref="#icon-kuhei-zhidi"></use></svg>
            { direction === 'vertical' && <div className="vertical-content"><span>置底</span></div>}
          </li>
          <li className="frontpanel-toolbar-item frontpanel-toolbar-top">
            <svg className="svg-icon" aria-hidden="true"><use xlinkHref="#icon-kuhei-zhiding"></use></svg>
            { direction === 'vertical' && <div className="vertical-content"><span>置顶</span></div>}
          </li>
        </ul> */}
        <ul className="frontpanel-toolbar">
          <Tooltip placement={direction === 'horizontal' && 'bottom'} title="组合">
            <li className={`frontpanel-toolbar-item frontpanel-toolbar-compose ${multiSelected ? "" : "disabled"}`}>
              <div>
                <svg className="svg-icon" aria-hidden="true"><use xlinkHref={"#icon-kuhei-zuhe" + iconSuffix} onClick={e => this.handleCombination('create')}></use></svg>
                { direction === 'vertical' && <div className="vertical-content"><span>组合</span></div>}
              </div>
            </li>
          </Tooltip>
          <Tooltip placement={direction === 'horizontal' && 'bottom'} title="取消组合">
            <li className={`frontpanel-toolbar-item frontpanel-toolbar-split ${multiSelected ? "" : "disabled"}`}>
              <div>
                <svg className="svg-icon" aria-hidden="true"><use xlinkHref={'#icon-kuhei-quxiaozuhe' + iconSuffix} onClick={e => this.handleCombination('delete')}></use></svg>
                { direction === 'vertical' && <div className="vertical-content"><span>取消组合</span></div>}
              </div>
            </li>
          </Tooltip>
        </ul>
        {direction !== 'horizontal' && <div className="separator"></div>}
        <ul className="frontpanel-toolbar">
          <Popover
            overlayClassName="toolbar-dark-dropdown"
            content={this.renderComponentMenu(this.alignmentMenu, this.handleAlign)}
            title={null}
            placement={popoverPlacement}
          >
            <li className="frontpanel-toolbar-item dropdown-item frontpanel-toolbar-alignment">
              <svg className="svg-icon" aria-hidden="true"><use xlinkHref="#icon-kuhei-chuizhifenbu"></use></svg>
              { direction === 'horizontal' ?
                <svg className="svg-icon dropdown-icon" aria-hidden="true"><use xlinkHref='#icon-kuhei-jiantou-xia'></use></svg> :
                <div className="vertical-content">
                  <span>对齐</span>
                  <i className='spicon icon-jiantou-you1'></i>
                </div>
              }
            </li>
          </Popover>
        </ul>
        {direction !== 'horizontal' && <div className="separator"></div>}
        <ul className="frontpanel-toolbar">
          <Popover
          overlayClassName="toolbar-dark-dropdown"
          content={this.renderScalcMenu()}
          title={null}
          placement={popoverPlacement}
          >
            { direction === 'horizontal' ?
              <li className="frontpanel-toolbar-item dropdown-item frontpanel-toolbar-scalc">
                {/* <span className="zoom-value">{initialZoom}%</span> */}
                <Input value={initialZoom} onChange={this.handleChangeZoom} onPressEnter={this.handlePressEnter} onBlur={this.handlePressEnter}
                  suffix={
                    <svg className="svg-icon dropdown-icon" aria-hidden="true"><use xlinkHref='#icon-kuhei-jiantou-xia'></use></svg>
                  } />
              </li> :
              <li className="frontpanel-toolbar-item dropdown-item frontpanel-toolbar-scalc vertical-scalc">
                <svg className="svg-icon" aria-hidden="true"><use xlinkHref="#icon-kuhei-suofang"></use></svg>
                <div className="vertical-content">
                  <span>缩放</span>
                  <i className='spicon icon-jiantou-you1'></i>
                </div>
              </li>
            }
          </Popover>
        </ul>
      </div>
    )
  }

  render() {
    const { resizeVisible, staticDataSource, collapseMenu, currentDrag } = this.state;
    const iconSuffix = Boolean(window.appConfig.appReadOnly) ? '-jinyong' : '';
    return (
      <div className="toolbar">
        <div className="storage-manager-store-time">
          <span>最近一次保存于 </span>
          <label className="time-label">{staticDataSource ? staticDataSource.timeLabel : ''}</label>
        </div>
        <div className={`frontpanel-toolbar-container ${collapseMenu ? 'collapsed-toolbar' : ''} `}>
          <ul className="frontpanel-toolbar">
            <Tooltip placement="bottom" title="拖拽画布">
              <li className={`frontpanel-toolbar-item frontpanel-toolbar-drag ${currentDrag ? 'selected' : ''} ${iconSuffix ? 'disabled' : ''}`}>
                <div onClick={this.handleDrag}>
                  <svg className="svg-icon" aria-hidden="true"><use xlinkHref={"#icon-kuhei-tuodonghuabu" + iconSuffix}></use></svg>
                </div>
              </li>
            </Tooltip>
            <Popover
              overlayClassName="resize-modal"
              content={this.renderSizeEditor}
              title="编辑画布尺寸"
              trigger="click"
              placement="bottom"
              visible={resizeVisible}
              onVisibleChange={this.handleSizeEditorVisibleChange}
            >
              <Tooltip placement="bottom" title="编辑画布尺寸">
                <li className={`frontpanel-toolbar-item frontpanel-toolbar-edit-size ${iconSuffix ? 'disabled' : ''}`}>
                  <div onClick={this.handleEditSize}>
                    <svg className="svg-icon" aria-hidden="true"><use xlinkHref={"#icon-kuhei-bianjihuabuchicun" + iconSuffix}></use></svg>
                  </div>
                </li>
              </Tooltip>
            </Popover>
          </ul>
          {collapseMenu ?
            <ul className="frontpanel-toolbar">
              <Popover
                overlayClassName="toolbar-dark-dropdown"
                content={this.renderOtherToolbar('vertical')}
                title={null}
                placement="bottom"
                trigger="click"
              >
                <li className="frontpanel-toolbar-item vertical-dropdown">
                  <i className="spicon icon-shuangjiantou-you"></i>
                </li>
              </Popover>
            </ul> :
            this.renderOtherToolbar('horizontal')
          }
        </div>
      </div>
    )
  }
}
export default class Toolbar {
  constructor(editor, opts) {
    _.bindAll(this, [
      "destroy",
      "render",
    ]);
    this.name = "Toolbar";
    this.editor = editor;
    this.em = editor.getModel();

    const self = this;
    editor.on('load', function (component) {
      editor.Canvas.getCanvasView().model.onZoomChange = null;
      self.render();
    });
    editor.on('storage:end:store', () => {
      const timeLabel = moment().format('YYYY-MM-DD hh:mm:ss');
      self.render({ timeLabel })
    });
  }

  render(defaultData) {
    const $container = $(this.editor.getContainer());
    const $toolbarContainer = $(`
      <div id="frontpanel-toolbar">
      </div>
    `);
    if (this.toolbarRef) {
      this.toolbarRef.updateProps(defaultData, this.editor);
    } else {
      ReactDOM.render(<ToolbarList ref={ref => this.toolbarRef = ref} defaultData={defaultData} editor={this.editor} />, $toolbarContainer[0]);
      const { _width, _widthUnit, _height, _heightUnit } = this.toolbarRef.state.computeSizeInfo;
      this.toolbarRef.onResizeCanvas(_width, _widthUnit, _height, _heightUnit);
      this.toolbarRef.updateProps(defaultData, this.editor);
      $container.parent().prepend($toolbarContainer);
    }
  }
  destroy() { }
};

 // const zoomer = new CanvasZoomer(editor, editor.getContainer());

    // <li class="frontpanel-toolbar-item">
    //   <i class="spicon icon-save js-save"></i>
    // </li>

    // const $timeText = $('.storage-manager-store-time').find('.time-label');

    // editor.Keymaps.add('storage:store', 'ctrl+s', () => {
    //   editor.store();
    // })

    // const $toolbar = $toolbarContainer.find('.frontpanel-toolbar');

    // $toolbar.find('.js-save').on('click', e => {
    //   e.stopPropagation();

    //   editor.store();
    // });

    // const $canvasInitBtn = $('<li class="frontpanel-toolbar-item frontpanel-toolbar-init"><a class="btn-init">' + reset + '</a></li>');
    // $toolbar.append($canvasInitBtn);

    //滑动条
    // const $zoomerListItem = $('<li class="frontpanel-toolbar-item"></li>');

    // $zoomerListItem.append($(zoomer.getDOM()));
    // $toolbar.append($zoomerListItem);
    // $canvasInitBtn.on('click', function() {
    //   const resizer = editor.getModel().get("modules").find(({ name }) => name === "CanvasResizer");
    //   resizer && resizer.setCanvasTransform();
    // });
