<template>
  <div class="home">
    <Layout>
      <Header v-if="show">
        <!-- 导入 -->
        <import-JSON />
        &nbsp;
        <import-svg />
        &nbsp;
        <import-img />
        &nbsp;
        <!-- 对齐方式 -->
        <align />
        &nbsp;
        <flip />
        &nbsp;
        <center-align />
        &nbsp;
        <group />
        &nbsp;
        <zoom />
        &nbsp;
        <lock />
        &nbsp;
        <dele />
        &nbsp;
        <clone />

        <div style="float:right">
          <save />
        </div>
      </Header>
      <Content style=" display: flex; height: calc(100vh - 64px);">
        <div style="width: 380px; height: 100%; background:#fff; display: flex">
          <Menu :active-name="menuActive" accordion width="80px" @on-select="activeIndex => menuActive = activeIndex">
            <MenuItem :name="1" style="padding:10px"><Icon type="md-book" />模板</MenuItem>
            <MenuItem :name="2" style="padding:10px"><Icon type="md-create" />元素</MenuItem>
            <MenuItem :name="3" style="padding:10px"><Icon type="ios-build" />背景</MenuItem>
            <MenuItem :name="4" style="padding:10px"><Icon type="ios-build" />画笔</MenuItem>
          </Menu>
          <div class="content">
            <template v-if="show">
              <!-- 生成模板 -->
              <div v-show="menuActive === 1" class="left-panel">
                <import-tmpl />
              </div>
              <!-- 常用元素 -->
              <div v-show="menuActive === 2" class="left-panel">
                <tools />
                <svgEl />
              </div>
              <!-- 背景设置 -->
              <div v-show="menuActive === 3" class="left-panel">
                <set-size />
                <bg-bar />
              </div>
            </template>
            <!-- 画笔设置 -->
            <div v-show="menuActive === 4">
              <div style="display: inline-block; margin-left: 10px">
                <button id="drawing-mode" class="btn btn-info">Cancel drawing mode</button><br>
                <button id="clear-canvas" class="btn btn-info">Clear</button><br>

                <div id="drawing-mode-options">
                  <label for="drawing-mode-selector">Mode:</label>
                  <select id="drawing-mode-selector">
                    <option>Pencil</option>
                    <option>Circle</option>
                    <option>Spray</option>
                    <option>Pattern</option>

                    <option>hline</option>
                    <option>vline</option>
                    <option>square</option>
                    <option>diamond</option>
                    <option>texture</option>
                  </select><br>

                  <label for="drawing-line-width">Line width:</label>
                  <span class="info">30</span><input id="drawing-line-width" type="range" value="30" min="0" max="150"><br>

                  <label for="drawing-color">Line color:</label>
                  <input id="drawing-color" type="color" value="#005E7A"><br>

                  <label for="drawing-shadow-color">Shadow color:</label>
                  <input id="drawing-shadow-color" type="color" value="#005E7A"><br>

                  <label for="drawing-shadow-width">Shadow width:</label>
                  <span class="info">0</span><input id="drawing-shadow-width" type="range" value="0" min="0" max="50"><br>

                  <label for="drawing-shadow-offset">Shadow offset:</label>
                  <span class="info">0</span><input id="drawing-shadow-offset" type="range" value="0" min="0" max="50"><br>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 画布区域 -->
        <div style="width: 100%;position: relative; background:#F1F1F1;">
          <div class="canvas-box">
            <canvas id="canvas" />
          </div>
        </div>
        <!-- 属性区域 -->
        <div style="width: 380px; height: 100%; padding:10px; overflow-y: auto; background:#fff">
          <history v-if="show" />
          <layer v-if="show" />
          <attribute v-if="show" />
        </div>
      </Content>
    </Layout>
  </div>
</template>

<script>

// 导入元素
import importJSON from '@/components/img-editor/importJSON.vue'
import importSvg from '@/components/img-editor/importSvg.vue'
import importImg from '@/components/img-editor/importImg.vue'

// 顶部组件
import align from '@/components/img-editor/align.vue'
import centerAlign from '@/components/img-editor/centerAlign.vue'
import flip from '@/components/img-editor/flip.vue'
import save from '@/components/img-editor/save.vue'
import clone from '@/components/img-editor/clone.vue'
import group from '@/components/img-editor/group.vue'
import zoom from '@/components/img-editor/zoom.vue'
import lock from '@/components/img-editor/lock.vue'
import dele from '@/components/img-editor/del.vue'

// 左侧组件
import importTmpl from '@/components/img-editor/importTmpl.vue'
import tools from '@/components/img-editor/tools.vue'
import svgEl from '@/components/img-editor/svgEl.vue'
import bgBar from '@/components/img-editor/bgBar.vue'
import setSize from '@/components/img-editor/setSize.vue'
import brush from '@/components/img-editor/brush'

// 右侧组件
import history from '@/components/img-editor/history.vue'
import layer from '@/components/img-editor/layer.vue'
import attribute from '@/components/img-editor/attribute.vue'

// 功能组件
import EventHandle from '@/utils/eventHandler'

import { fabric } from 'fabric'

// 对齐辅助线
import initAligningGuidelines from '@/core/initAligningGuidelines'
import initHotkeys from '@/core/initHotKeys'
import initControls from '@/core/initControls'

const event = new EventHandle()
const canvas = {}
export default {
  name: 'HomeView',
  provide: {
    canvas,
    fabric,
    event
  },
  components: {
    setSize, tools, bgBar, lock, layer, align, attribute, dele, importSvg, save, importJSON, clone, flip, importImg, importTmpl, centerAlign, group, zoom, svgEl, history
  },
  data() {
    return {
      menuActive: 4,
      show: false,
      select: null
    }
  },
  created() {
    // this.$Spin.show()
  },
  mounted() {
    this.canvas = canvas.c = new fabric.Canvas('canvas', {
      isDrawingMode: true
    })
    // console.log(this.canvas)
    this.canvas.set('backgroundColor', '#fff')
    this.show = true
    this.$Spin.hide()
    event.init(canvas.c)
    initAligningGuidelines(canvas.c)
    initHotkeys(canvas.c)
    initControls(canvas.c)
    this.setBrush()
  },
  methods: {
    setBrush() {
      var $ = function(id) { return document.getElementById(id) }
      var canvas = this.canvas
      fabric.Object.prototype.transparentCorners = false

      var drawingModeEl = $('drawing-mode')
      var drawingOptionsEl = $('drawing-mode-options')
      var drawingColorEl = $('drawing-color')
      var drawingShadowColorEl = $('drawing-shadow-color')
      var drawingLineWidthEl = $('drawing-line-width')
      var drawingShadowWidth = $('drawing-shadow-width')
      var drawingShadowOffset = $('drawing-shadow-offset')
      var clearEl = $('clear-canvas')

      clearEl.onclick = function() { canvas.clear() }

      drawingModeEl.onclick = function() {
        canvas.isDrawingMode = !canvas.isDrawingMode
        if (canvas.isDrawingMode) {
          drawingModeEl.innerHTML = 'Cancel drawing mode'
          drawingOptionsEl.style.display = ''
        } else {
          drawingModeEl.innerHTML = 'Enter drawing mode'
          drawingOptionsEl.style.display = 'none'
        }
      }

      if (fabric.PatternBrush) {
        var vLinePatternBrush = new fabric.PatternBrush(canvas)
        vLinePatternBrush.getPatternSrc = function() {
          var patternCanvas = fabric.document.createElement('canvas')
          patternCanvas.width = patternCanvas.height = 10
          var ctx = patternCanvas.getContext('2d')

          ctx.strokeStyle = this.color
          ctx.lineWidth = 5
          ctx.beginPath()
          ctx.moveTo(0, 5)
          ctx.lineTo(10, 5)
          ctx.closePath()
          ctx.stroke()

          return patternCanvas
        }

        var hLinePatternBrush = new fabric.PatternBrush(canvas)
        hLinePatternBrush.getPatternSrc = function() {
          var patternCanvas = fabric.document.createElement('canvas')
          patternCanvas.width = patternCanvas.height = 10
          var ctx = patternCanvas.getContext('2d')

          ctx.strokeStyle = this.color
          ctx.lineWidth = 5
          ctx.beginPath()
          ctx.moveTo(5, 0)
          ctx.lineTo(5, 10)
          ctx.closePath()
          ctx.stroke()

          return patternCanvas
        }

        var squarePatternBrush = new fabric.PatternBrush(canvas)
        squarePatternBrush.getPatternSrc = function() {
          var squareWidth = 10; var squareDistance = 2

          var patternCanvas = fabric.document.createElement('canvas')
          patternCanvas.width = patternCanvas.height = squareWidth + squareDistance
          var ctx = patternCanvas.getContext('2d')

          ctx.fillStyle = this.color
          ctx.fillRect(0, 0, squareWidth, squareWidth)

          return patternCanvas
        }

        var diamondPatternBrush = new fabric.PatternBrush(canvas)
        diamondPatternBrush.getPatternSrc = function() {
          var squareWidth = 10; var squareDistance = 5
          var patternCanvas = fabric.document.createElement('canvas')
          var rect = new fabric.Rect({
            width: squareWidth,
            height: squareWidth,
            angle: 45,
            fill: this.color
          })

          var canvasWidth = rect.getBoundingRect().width

          patternCanvas.width = patternCanvas.height = canvasWidth + squareDistance
          rect.set({ left: canvasWidth / 2, top: canvasWidth / 2 })

          var ctx = patternCanvas.getContext('2d')
          rect.render(ctx)

          return patternCanvas
        }

        var img = new Image()
        img.src = '../assets/honey_im_subtle.png'

        var texturePatternBrush = new fabric.PatternBrush(canvas)
        texturePatternBrush.source = img
      }

      $('drawing-mode-selector').onchange = function() {
        if (this.value === 'hline') {
          canvas.freeDrawingBrush = vLinePatternBrush
        } else if (this.value === 'vline') {
          canvas.freeDrawingBrush = hLinePatternBrush
        } else if (this.value === 'square') {
          canvas.freeDrawingBrush = squarePatternBrush
        } else if (this.value === 'diamond') {
          canvas.freeDrawingBrush = diamondPatternBrush
        } else if (this.value === 'texture') {
          canvas.freeDrawingBrush = texturePatternBrush
        } else {
          canvas.freeDrawingBrush = new fabric[this.value + 'Brush'](canvas)
        }

        if (canvas.freeDrawingBrush) {
          var brush = canvas.freeDrawingBrush
          brush.color = drawingColorEl.value
          if (brush.getPatternSrc) {
            brush.source = brush.getPatternSrc.call(brush)
          }
          brush.width = parseInt(drawingLineWidthEl.value, 10) || 1
          brush.shadow = new fabric.Shadow({
            blur: parseInt(drawingShadowWidth.value, 10) || 0,
            offsetX: 0,
            offsetY: 0,
            affectStroke: true,
            color: drawingShadowColorEl.value
          })
        }
      }

      drawingColorEl.onchange = function() {
        var brush = canvas.freeDrawingBrush
        brush.color = this.value
        if (brush.getPatternSrc) {
          brush.source = brush.getPatternSrc.call(brush)
        }
      }
      drawingShadowColorEl.onchange = function() {
        canvas.freeDrawingBrush.shadow.color = this.value
      }
      drawingLineWidthEl.onchange = function() {
        canvas.freeDrawingBrush.width = parseInt(this.value, 10) || 1
        this.previousSibling.innerHTML = this.value
      }
      drawingShadowWidth.onchange = function() {
        canvas.freeDrawingBrush.shadow.blur = parseInt(this.value, 10) || 0
        this.previousSibling.innerHTML = this.value
      }
      drawingShadowOffset.onchange = function() {
        canvas.freeDrawingBrush.shadow.offsetX = parseInt(this.value, 10) || 0
        canvas.freeDrawingBrush.shadow.offsetY = parseInt(this.value, 10) || 0
        this.previousSibling.innerHTML = this.value
      }

      if (canvas.freeDrawingBrush) {
        canvas.freeDrawingBrush.color = drawingColorEl.value
        canvas.freeDrawingBrush.source = canvas.freeDrawingBrush.getPatternSrc.call(this)
        canvas.freeDrawingBrush.width = parseInt(drawingLineWidthEl.value, 10) || 1
        canvas.freeDrawingBrush.shadow = new fabric.Shadow({
          blur: parseInt(drawingShadowWidth.value, 10) || 0,
          offsetX: 0,
          offsetY: 0,
          affectStroke: true,
          color: drawingShadowColorEl.value
        })
      }
      var mainScriptEl = document.getElementById('main')
      if (!mainScriptEl) return
      var preEl = document.createElement('pre')
      var codeEl = document.createElement('code')
      codeEl.innerHTML = mainScriptEl.innerHTML
      codeEl.className = 'language-javascript'
      preEl.appendChild(codeEl)
      document.getElementById('bd-wrapper').appendChild(preEl)

      window.addEventListener('load', function() {
        var canvas = this.canvas
        var canvases = this.__canvases || this.canvases

        canvas && canvas.calcOffset && canvas.calcOffset()

        if (canvases && canvases.length) {
          for (var i = 0, len = canvases.length; i < len; i++) {
            canvases[i].calcOffset()
          }
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>

/deep/ .ivu-layout-header {
  padding: 0 10px;
}
.home,.ivu-layout{
  height: 100vh;
}
.icon{
  display: block;
}
.canvas-box{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
#canvas{
  width: 300px;
  height: 300px;
  margin: 0 auto;
  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAHUlEQVQ4jWNgYGAQIYAJglEDhoUBg9+FowbQ2gAARjwKARjtnN8AAAAASUVORK5CYII=");
  background-size: 30px 30px;
}
.content{
  flex: 1;
  width: 200px;
  padding:10px;
  padding-top: 0;
  height: 100%;
  overflow-y: auto;
}
</style>
