<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    class="dialog-wrap"
    fullscreen
    :before-close="handleClose"
    center>
    <div class="editor-wrap">
      <!-- 图层显示控制 -->
      <Layers :custom-style="customStyle"></Layers>

      <!-- 画布 -->
      <div
        class="canvas-wrap"
        @click="cleanSelected"
        ref="canvasWrap">
        <div class="canvas-inner">
          <div
            class="canvas"
            ref="canvas"
            v-if="customStyle"
            :style="[customStyle.canvas,{transform:`scale(${scaleRate})`}]">
            <template>
              <ElWrap
                v-for="(el,index) in customStyle.elements"
                :key="index"
                :element="el"
                :style="el.style"
                @click.native.capture.stop="selectedElement(el)">
                <component
                  :canvas="customStyle.canvas"
                  :element="el"
                  :is="el.type"></component>
              </ElWrap>
            </template>
          </div>
        </div>
      </div>

      <!-- 属性面板 -->
      <div class="control-panel">
        <el-form
          ref="form"
          :model="form"
          label-width="80px">
          <el-form-item
            verify
            prop="name"
            label="模板名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>

          <el-form-item
            prop="name"
            label="备注文字">
            <el-input
              v-model="customStyle.canvas.remark"
              type="textarea"
              :rows="2"></el-input>
          </el-form-item>

          <el-form-item label="打印方向">
            <el-select
              style="width:100%"
              v-model="defaultTemplate"
              @change="handleTemplateChange">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <template v-if="customStyle">
            <el-form-item label="门票宽度">
              <el-input
                v-model="customStyle.canvas.width"
              ></el-input>
            </el-form-item>
            <el-form-item label="门票高度">
              <el-input
                v-model="customStyle.canvas.height"
              ></el-input>
            </el-form-item>
            <el-form-item label="翻转打印">
              <el-switch
                v-model="customStyle.canvas.reverse"
                active-text=""
                inactive-text="">
              </el-switch>
            </el-form-item>
          </template>

          <template v-if="editingElement">
            <el-form-item
              label="身份证"
              v-if="editingElement.type==='guestName'">
              <el-switch v-model="editingElement.style.showId">
              </el-switch>
            </el-form-item>
            <el-form-item label="自定义名">
              <el-input v-model="editingElement.style.format"></el-input>
            </el-form-item>
            <el-form-item
              label="显示数量"
              v-if="editingElement.type==='scenic'">
              <el-input v-model="editingElement.style.number"></el-input>
            </el-form-item>
            <el-form-item
              label="显示方式"
              v-if="editingElement.type==='scenic'">
              <el-select v-model="editingElement.style.direction">
                <el-option
                  label="一行显示"
                  value="inline">
                </el-option>
                <el-option
                  label="多行显示"
                  value="multiple">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="x坐标">
              <el-input v-model="editingElement.style.left"></el-input>
            </el-form-item>
            <el-form-item label="y坐标">
              <el-input v-model="editingElement.style.top"></el-input>
            </el-form-item>
            <el-form-item label="宽度">
              <el-input v-model="editingElement.style.width"></el-input>
            </el-form-item>
            <el-form-item label="高度">
              <el-input v-model="editingElement.style.height"></el-input>
            </el-form-item>
            <el-form-item label="字体大小">
              <el-input v-model="editingElement.style.fontSize"></el-input>
            </el-form-item>
            <el-form-item label="上边距">
              <el-input v-model="editingElement.style.marginTop"></el-input>
            </el-form-item>
            <el-form-item label="字体加粗">
              <el-select v-model="editingElement.style.fontWeight">
                <el-option
                  label="加粗"
                  value="bold">
                </el-option>
                <el-option
                  label="正常"
                  value="normal">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="对齐方式">
              <el-select v-model="editingElement.style.textAlign">
                <el-option
                  label="居左"
                  value="left">
                </el-option>
                <el-option
                  label="居右"
                  value="right">
                </el-option>
                <el-option
                  label="居中"
                  value="center">
                </el-option>
              </el-select>
            </el-form-item>
          </template>

          <el-form-item>
            <el-button
              @click="save"
              type="primary">
              保存
            </el-button>

            <el-button
              @click="handlePrint"
              type="primary">
              测试打印
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <PrintTemplate
        ref="printer"
        class="demo"
        :custom-style="customStyle"
        :current-ticket="ticket"
        :preview="true"></PrintTemplate>
    </div>
  </el-dialog>
</template>

<script>
import { addTicketPrintModel, updateTicketPrintModel, addReceiptPrintModel, updateReceiptPrintModel } from '@/api/printModal'
import checkPermission from '@/utils/checkPermission'
import printOption from './index.js'
import elements from './components'

import PrintTemplate from '@/components/PrintTemplate'
import ElWrap from './elementWrap'
import Layers from './Layers'
import merge from 'lodash/merge'
import UnitConversion from '@/utils'
// 静态票数据
import ticket from './ticket'

let mm2px = new UnitConversion().mmConversionPx

export default {
  props: {
    type: {
      type: String,
      default: 'ticket'
    }
  },
  components: {
    ...elements,
    ElWrap,
    Layers,
    PrintTemplate
  },
  computed: {
    editingElement () {
      return this.$store.state.app.editorElement
    },
    ticketTypeList () {
      return this.$store.state.app.ticketTypeList
    },
    scaleRate () {
      return this.$store.state.app.scaleRate
    },
    canvasSize () {
      let canvasEl = this.customStyle.canvas

      return {
        width: mm2px(parseInt(canvasEl.width)),
        height: mm2px(parseInt(canvasEl.height))
      }
    }
  },
  data () {
    return {
      ticket,
      name: '',
      title: '',
      visible: false,
      currentEle: null,
      submitType: '',
      defaultTemplate: 'vertical',
      currentTemplate: null,
      oldTicketTypeOptions: [[]],
      customStyle: {
        canvas: {}
      },
      form: {
        name: '',
        content: ''
      },
      options: [
        {
          value: 'vertical',
          label: '纵向'
        },
        {
          value: 'horizen',
          label: '横向'
        }
      ]
    }
  },
  methods: {
    checkPermission,
    handleClose () {
      this.visible = false
      this.customStyle = { canvas: {} }
      this.$refs.form.resetFields()
      this.$store.dispatch('setEditorElement', null)
    },
    scenicName () {
      return this.$localStore.get('scenicName') || this.$store.state.user.scenicName
    },
    deleteElementByName (name, HorV) {
      const index = HorV.elements.findIndex(element => element.name === name)
      if (index !== -1) {
        HorV.elements.splice(index, 1)
      }
      return { ...HorV }
    },
    show (type, data) {
      this.visible = true
      this.$nextTick(() => {
        this.setCanvas()
      })
      this.submitType = type
      switch (type) {
        case 'new':
          this.title = '新增模板'
          this.customStyle = JSON.parse(JSON.stringify(printOption[this.defaultTemplate]))
          this.form.name = ''
          console.log(JSON.stringify(printOption[this.defaultTemplate]), '11212')
          break
        case 'edit':
          this.title = '编辑模板'
          this.currentTemplate = data
          this.customStyle = JSON.parse(data.content.replace(/\\/g, ''))
          this.defaultTemplate = this.customStyle.canvas.direction
          this.form.name = data.name
          let defaultStyle = JSON.parse(JSON.stringify(printOption[this.defaultTemplate]))
          let newElements = []
          defaultStyle.elements.forEach(item => {
            let target = this.customStyle.elements.find(i => i.type === item.type)
            if (target) {
              // console.log(merge(item, target))
              newElements.push(merge(item, target))
            } else {
              newElements.push(item)
            }
          })
          this.customStyle.elements = newElements
          // 非大陈岛景区，编辑模板时，不需要在模板中展示"序列号"
          if (this.scenicName() !== '大陈岛景区') {
            this.customStyle = this.deleteElementByName('序列号', this.customStyle)
          }
      }
    },
    setCanvas () {
      this.$nextTick(() => {
        this.scaleCanvas()
      })
    },
    scaleCanvas () {
      if (!this.$refs.canvasWrap) return

      let scaleRate
      let canvas = this.canvasSize

      let canvasWrap = this.$refs.canvasWrap
      let wrapObj = canvasWrap && canvasWrap.getBoundingClientRect()
      // console.log(canvas, wrapObj)
      let wrapWidth = wrapObj.width - 140 // 减去140边距
      let wrapHeight = wrapObj.height - 100 // 减去50边距

      if (wrapWidth / wrapHeight > canvas.width / canvas.height) {
        scaleRate = wrapHeight / canvas.height
      } else {
        scaleRate = wrapWidth / canvas.width
      }

      this.$store.dispatch('scaleCanvas', scaleRate)

      if (window.onresize) return
      window.onresize = () => {
        this.timer && clearTimeout(this.timer)

        this.timer = setTimeout(() => {
          this.scaleCanvas(canvas)
        }, 100)
      }
    },
    selectedElement (element) {
      this.$store.dispatch('setEditorElement', element)
    },
    cleanSelected () {
      this.$store.dispatch('setEditorElement', null)
      // console.log(document.querySelector('#finally').innerHTML)
    },
    // 保存样式
    save () {
      this.$refs.form.validate(valid => {
        if (valid) {
          switch (this.submitType) {
            case 'new':
              this.handleAdd()
              break
            case 'edit':
              this.handleEdit()
              break
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleAdd () {
      const opt = this.type === 'ticket' ? addTicketPrintModel : addReceiptPrintModel
      opt({
        name: this.form.name,
        content: JSON.stringify(this.customStyle)
      }).then(res => {
        this.$message.success('添加成功')
        this.$emit('update')
        this.visible = false
      })
    },
    handleEdit () {
      const opt = this.type === 'ticket' ? updateTicketPrintModel : updateReceiptPrintModel
      opt({
        id: this.currentTemplate.id,
        name: this.form.name,
        content: JSON.stringify(this.customStyle),
        isDefault: this.currentTemplate.isDefault
      }).then(res => {
        this.$message.success('编辑成功')
        this.$emit('update')
        this.visible = false
      })
    },
    // 打印测试
    handlePrint () {
      this.$refs.printer.sendPrinter({
        theme: this.defaultTemplate,
        ...this.customStyle
      })
    },
    handleTemplateChange (val) {
      this.customStyle = printOption[val]
      this.setCanvas()
    }
  },
  watch: {
    canvasSize: {
      handler (val) {
        this.setCanvas()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.demo {
  display: none;
  position: absolute; top: 0;left: 0;width: 100%; height: 100%; pointer-events: none;
}
.el {
  position: absolute;
}
.control-panel {
  position: relative;  width: 360px; box-sizing: border-box; padding: 20px; overflow: auto;
}
.editor-wrap {
  display: flex; height: 100%; overflow: hidden; user-select: none; width: 100%;
}
.canvas-wrap {
  position: relative;  background: #fefefe url('~imgs/img_grid.png'); border: 1px solid #ddd; flex: 1; overflow: hidden;
}
.canvas-inner {
  position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);
}
.canvas {
  position: relative; box-sizing: border-box;  background: #fff; box-shadow: 0 0 10px rgba(0,0,0,.2);transition: all 0.5s;
  &.bg {
    background: url('~imgs/ticket.jpg') no-repeat center center / cover;
  }
  .disable-area {display: flex;
    width: 20mm;  height: 100%; background: $blue1; justify-content: center; align-items: center;
    span {
      display: inline-block; width: 14px; color: $blue;
    }
  }
  .inner {
    position: absolute; top: 0; right: 0; left: 20mm; height: 100%;
  }
}

.btn-wrap {
  text-align: center;
}
.dialog-wrap {
  ::v-deep .el-dialog .el-form-item {
    display: block;
    .el-form-item__label{
      float: left;
    }
  }
}

</style>

<style lang="scss">
.el-dialog.is-fullscreen {
  display: flex; height: 100%; margin-top: 0; flex-direction: column;
  .el-dialog__body {
    width: 100%; flex: 1; color:#000;
  }
}

</style>
