import $ from "jquery";
import _ from "underscore";

import editSVG from "../assets/edit.svg";
import checkSVG from "../assets/check.svg";
import { destroy } from "autosize";

export default class CanvasResizer {
  constructor(editor) {
    _.bindAll(this, [
      "createDOM",
      "createLabel",
      "createInput",
      "hide",
      "showEdit",
      "render",
      "setCanvasTransform"
    ]);

    this.name = "CanvasResizer";

    this.editor = editor;

    editor.on("component:selected", (comp) => {
      if (comp.get('type') === 'wrapper' && !this.rendered) {
        this.render();
      }
    });

    // 源码中的onZoomChange将zoom小于1的值重置为1，所以此处将该函数设置为null
    editor.on('load', () => {
      editor.Canvas.getCanvasView().model.onZoomChange = null;
    });

    // 窗口大小改变时重新计算
    // window.addEventListener('resize', this.setCanvasTransform);
  }

  destroy() {
    // window.removeEventListener('resize', this.setCanvasTransform);
  }

  createDOM(container) {
    const $resizerToolbar = $(`<div></div>`);
    $resizerToolbar.css({
      position: "absolute",
      top: "-40px",
      right: "10px",
      height: "20px",
      "text-align": "right",
      "font-size": "14px",
      color: "#90a0af",
      "font-style": "italic",
      "z-index": 99,
    });

    $resizerToolbar.append(this.createLabel());
    $resizerToolbar.append(this.createInput());

    $(container).parent().prepend($resizerToolbar);
  }

  createLabel() {
    this.$labelContainer = $(`
      <div>
        <span class="resize-edit">${editSVG}</span>
        <label class="resize-label">
          <span class="width-label">${parseInt(this.width)}${this.widthUnit}</span> x <span class="height-label">${parseInt(this.height)}${this.heightUnit}</span>
        </label>
      </div>`);

    this.$widthLabel = this.$labelContainer.find(".width-label");
    this.$heightLabel = this.$labelContainer.find(".height-label");

    this.$labelContainer.on("click", ".resize-edit", () => {
      this.showEdit();
    });

    return this.$labelContainer;
  }

  createInput() {
    this.$inputContainer = $(`
      <div class="resize-wrapper">
        <div class="resize-item">
          <input class="resize-input resize-input-width" data-prop="width" value=${this.width}></input>
          <select class="resize-unit resize-unit-width">
            <option value="px" selected>px</option>
            <option value="%">%</option>
            <option value="vw">vw</option>
          </select>
        </div> x
        <div class="resize-item">
          <input class="resize-input resize-input-height" data-prop="height" value=${this.height}></input>
          <select class="resize-unit resize-unit-height">
            <option value="px" selected>px</option>
            <option value="%">%</option>
            <option value="vh">vh</option>
          </select>
        </div>
        <span style="width: 20px; height: 20px; display: inline-block; vertical-align: middle;" class="resize-check">${checkSVG}</span>
      </div>
    `);

    this.$widthInput = this.$inputContainer.find(".resize-input-width");
    this.$heightInput = this.$inputContainer.find(".resize-input-height");
    this.$widthUnit = this.$inputContainer.find(".resize-unit-width");
    this.$heightUnit = this.$inputContainer.find(".resize-unit-height");

    // const inputCss = {
    //   "text-align": "right",
    //   width: "50px",
    //   border: "none",
    //   outline: "none",
    //   "padding": "2px 6px",
    //   "background-color": 'rgba(0, 0, 0, 0.2)'
    // };

    // this.$widthInput.css(inputCss);

    // this.$heightInput.css(inputCss);

    this.$inputContainer.on("click", ".resize-check", (ev) => {
      this.width = this.$widthInput.val();
      this.height = this.$heightInput.val();
      this.widthUnit = this.$widthUnit.val();
      this.heightUnit = this.$heightUnit.val();

      const { editor, width, height, widthUnit, heightUnit } = this;
      if (width !== 0 && height !== 0) {
        this.$iframe.style.width = `${width}${widthUnit}`;
        this.$iframe.style.height = `${height}${heightUnit}`;
        editor
          .getWrapper()
          .addStyle({ width: `${width}${widthUnit}!important`, height: `${height}${heightUnit}!important` });
      }

      editor.store();

      this.render();
    });

    return this.$inputContainer;
  }

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

  computeSize() {
    const { width, height } = this.editor.getWrapper().getStyle();
    if (!width || !height) {
      // const frameSize = this.$iframe.getBoundingClientRect();
      // this.width = frameSize.width;
      // this.height = frameSize.height;
      this.width = 1920;
      this.height = 1080;
      this.widthUnit = 'px';
      this.heightUnit = 'px';
    } else {
      this.widthUnit = this.getUnit(width);
      this.heightUnit = this.getUnit(height);
      this.width = parseInt(width);
      this.height = parseInt(height);
    }

    if (this.width === 0 || isNaN(this.width) || this.height === 0 || isNaN(this.height)) {
      // let parentNode = this.$iframe.parentNode;
      // let parentSize = parentNode.getBoundingClientRect();

      // while (parentNode && parentSize.width === 0) {
      //   parentNode = parentNode.parentNode;
      //   if (parentNode) {
      //     parentSize = parentNode.getBoundingClientRect();
      //   }
      // }

      // this.width = parentSize.width;
      // this.height = parentSize.height;
      this.width = 1920;
      this.height = 1080;
      this.widthUnit = 'px';
      this.heightUnit = 'px';
    }

    this.width = this.width.toFixed(2);
    this.height = this.height.toFixed(2);
  }

  hide() {
    if (this.$labelContainer) {
      this.$labelContainer.hide();
      this.$inputContainer.hide();
    }
  }

  showEdit() {
    this.$labelContainer.hide();
    this.$inputContainer.show();
  }

  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.editor.Canvas.getCanvasView().model.set('x', x);
      this.editor.Canvas.getCanvasView().model.set('y', y);
    }
  }

  doRender() {
    const $editor = _.get(this.editor, 'Canvas.em.view.$el'.split('.'), null);
    
    if ($editor) {
      if (!this.$body) {
        this.$iframe = this.editor.Canvas.getFrameEl();
        this.$body = this.editor.Canvas.getBody();
        // this.createDOM(this.editor.getContainer());
      }
      this.computeSize();
      const { width, height, widthUnit, heightUnit } = this;
      const framesArea = $editor.find('[data-frames]').get(0);

      if (!this.$iframe || !framesArea) {
        setTimeout(() => { this.render() }, 500);
        return;
      }

      if (this.$iframe) {
        this.$iframe.style.width = `${width}${widthUnit}`;
        this.$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.$inputContainer.hide();
  
      // this.$widthInput.val(width);
      // this.$heightInput.val(height);
      // this.$widthUnit.val(widthUnit);
      // this.$heightUnit.val(heightUnit);
      // this.$widthLabel.text(`${width}${widthUnit}`);
      // this.$heightLabel.text(`${height}${heightUnit}`);
      // this.$labelContainer.show();
    }
  }

  render() {
    const $editorContainer = document.getElementById('editor-container');

    let resizerTimer = setTimeout(() => {
      clearTimeout(resizerTimer);
      resizerTimer = null;
      if ($editorContainer.offsetWidth) {
        this.doRender();
      } else {
        this.render();
      }
    }, 150);
  }
}
