<template>
  <div class="home">
    <div>
      <div v-if="show" style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px">
        <!-- 对齐方式 -->
        <zoom />
        <div>
          <save @fullImgBack="fullImgBack" />
          <el-button size="small" @click="closeDialog">关闭</el-button>
        </div>
      </div>
      <div style=" display: flex; height: calc(100vh - 120px);">
        <div style="width: 380px; height: 100%; background:#fff; display: flex">
          <el-tabs v-model="menuActive" tab-position="left" style="height: 200px;">
            <el-tab-pane label="元素" name="2" />
            <el-tab-pane label="背景" name="3" />
            <el-tab-pane label="画笔" name="4" />
          </el-tabs>
          <div class="content">
            <template v-if="show">
              <div v-show="menuActive === '2'" class="left-panel">
                <tools />
              </div>
              <!-- 背景设置 -->
              <div v-show="menuActive === '3'" class="left-panel">
                <set-size />
                <bg-bar ref="bgBar" :is-od-or-os="isOdOrOs" />
              </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="30" 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">
          <layer v-if="show" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 顶部组件
import save from '@/page-subspecialty/views/modules/imgEditorFabric/img-editor/save.vue'
import zoom from '@/page-subspecialty/views/modules/imgEditorFabric/img-editor/zoom.vue'

// 左侧组件
import tools from '@/page-subspecialty/views/modules/imgEditorFabric/img-editor/tools.vue'
import bgBar from '@/page-subspecialty/views/modules/imgEditorFabric/img-editor/bgBar.vue'
import setSize from '@/page-subspecialty/views/modules/imgEditorFabric/img-editor/setSize.vue'
import brush from '@/page-subspecialty/views/modules/imgEditorFabric/img-editor/brush.vue'

// 右侧组件
import layer from '@/page-subspecialty/views/modules/imgEditorFabric/img-editor/layer.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',
  components: {
    zoom,
    save,
    tools,
    bgBar,
    setSize,
    brush,
    layer
  },
  props: {
    isOdOrOs: {
      type: String
    }
  },
  provide: {
    canvas,
    fabric,
    event
  },
  data() {
    return {
      menuActive: '4',
      show: false,
      select: null
    }
  },
  mounted() {
    this.canvas = canvas.c = new fabric.Canvas('canvas', {
      isDrawingMode: true
    })
    // console.log(this.canvas)
    this.canvas.set('backgroundColor', '#fff')
    this.show = true
    event.init(canvas.c)
    initAligningGuidelines(canvas.c)
    initHotkeys(canvas.c)
    initControls(canvas.c)
    this.$nextTick(() => {
      this.setBrush()
    })
  },
  methods: {
    fullImgBack(value) {
      this.$emit('fullImgBack', value)
    },
    closeDialog() {
      this.$emit('closeDialog')
    },
    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 && 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="scss" scoped>

::v-deep .ivu-layout-header {
  padding: 0 10px;
}
.home,.ivu-layout{
  height: calc( 100vh - 70px );
}
.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>
