<template>
  <div class="edit-cert-box">
    <!-- <div @click="toImage">111</div> -->
    <div class="tool-left">
      <div>
        <div class="tool-title">
          <div class="title">{{ certBoxEditStyle.title }}</div>
        </div>
        <editStyle @data="changeStyle" :data="certBoxEditStyle"></editStyle>
        <div v-for="(item, index) in certElement" :key="index" style="margin-top: 20px">
          <div class="tool-title" @click="domShow(item.id)">
            <div class="title">
              {{ item.title }}
            </div>
            <div class="icons">
              <i class="el-icon-delete-solid" @click="deleteEdit(item)"></i>
              <i class="el-icon-arrow-down" v-if="item.show"></i>
              <i class="el-icon-arrow-right" v-else></i>
            </div>
          </div>
          <div v-if="item.show">
            <editStyle @delete="deleteEdit" @imgUpload="imgUpload" @data="changeStyle" :data="item"></editStyle>
          </div>
        </div>
      </div>
      <div class="tool-btn" @click="dialogVisible = true">
        <i class="el-icon-plus"></i>
        <div class="txt">添加元素</div>
      </div>
    </div>
    <div class="tool-right">
      <div :style="certBoxEditStyle.style" :class="!isParamsShow && 'active'" id="edit-dom-1" ref="imageTofile">
        <template v-for="item in certElement">
          <div
            :style="item.style"
            v-if="item.type == 3 || item.type == 0"
            :key="item.id"
            :id="item.id"
            :class="item.show ? 'edit-img active' : 'edit-img'"
            @click="domShow(item.id)"
          >
            <div v-if="item.url" style="width: 100%; height: 100%">
              <div class="pop"></div>
              <img style="width: 100%; display: block; height: 100%" :src="item.url" />
            </div>
          </div>
          <div
            :style="item.style"
            v-if="item.type === 1"
            :class="item.show ? 'text active' : 'text'"
            :key="item.id"
            :id="item.id"
            @click="domShow(item.id)"
          >
            <div class="pop"></div>
            <div v-html="item.html"></div>
          </div>
          <div
            :style="item.style"
            v-if="item.type === 2 && isParamsShow"
            :class="item.show ? 'text2 active' : 'text2'"
            :key="item.id"
            :id="item.id"
            @click="domShow(item.id)"
          >
            <div class="pop"></div>
            <div>{{ item.value }}</div>
          </div>
        </template>
      </div>
      <div style="display: flex; justify-content: center; padding: 30px">
        <el-button type="primary" @click="submit()">提 交</el-button>
        <el-button type="primary" @click="$router.go(-1)">返 回</el-button>
      </div>
    </div>
    <el-dialog title="添加元素" :visible.sync="dialogVisible" width="30%" :destroy-on-close="true">
      <div style="display: flex; justify-content: center">
        <el-radio-group v-model="selectElement">
          <el-radio :label="0">图片</el-radio>
          <el-radio :label="1">文字</el-radio>
          <el-radio :label="2">动态变量</el-radio>
          <!-- <el-radio :label="3">背景图片</el-radio> -->
        </el-radio-group>
      </div>
      <div style="display: flex; justify-content: center; padding: 30px" v-if="selectElement === 2">
        <el-select v-model="paramValue" placeholder="请选择">
          <el-option v-for="item in paramOptions" :key="item.key" :label="item.key" :value="item.key"> </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addElement">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import editStyle from '@/components/base/EditStyle.vue'
import { getParamsList } from '../api'
import drag from '@/utils/drag.js'
import { uploadBlob } from '@/utils/blob'
export default {
  props: {
    data: { type: Object }
  },
  components: {
    editStyle
  },
  data() {
    return {
      htmlUrl: '',
      // 动态id
      dynamicId: 1,
      // 动态变量
      paramValue: '',
      // 动态变量选项
      paramOptions: [],
      // 添加dom弹窗
      dialogVisible: false,
      // 选择添加那个类型的dom
      selectElement: 0,
      // 证书大小设置
      certBoxEditStyle: {
        type: '-1',
        title: '证书设置',
        tool: [
          { name: 'width', value: 860 },
          { name: 'height', value: 400 }
        ],
        style: ''
      },
      // 所有添加的dom元素
      certElement: [],
      isShowFlag: true,
      isParamsShow: true,
      toCanvasImg: ''
    }
  },
  computed: {},
  mounted() {
    if (this.$route.query.id) {
      this.certElement = this.data.certElement
      this.$nextTick(() => {
        this.certElement.forEach(item => {
          this.dragInit(item.id, item)
        })
      })
      this.dynamicId = this.certElement.length + 1
      this.certBoxEditStyle = this.data.certBoxEditStyle
    }
    this.setCertBox()
    this.getParamOptions()
    // document.onclick = () => {
    //   if (this.certElement.length && this.isShowFlag) {
    //     this.certElement.map(item => {
    //       item.show = false
    //       return item
    //     })
    //   }
    // }
  },
  methods: {
    // 提交
    submit() {
      // 获取dom颜色
      const getRgb = (dom, name) => {
        const getColor = getComputedStyle(dom)[name]
        return getColor
          .substring(getColor.indexOf('(') + 1, getColor.indexOf(')'))
          .replace(/\s*/g, '')
          .split(',')
      }
      // 获取画板信息
      const bgDom = document.getElementById('edit-dom-1')
      const bgDomRgb = getRgb(bgDom, 'backgroundColor')
      // 提交的参数
      const params = {
        elements: [],
        bg_width: bgDom.offsetWidth,
        bg_height: bgDom.offsetHeight,
        info: JSON.stringify({ certElement: this.certElement, certBoxEditStyle: this.certBoxEditStyle }),
        bg_color: JSON.stringify({ r: bgDomRgb[0], g: bgDomRgb[1], b: bgDomRgb[2] })
      }
      // 让动态变量隐藏，为了html2canvas截图
      this.isParamsShow = false
      // 寻找工具对应的值
      const findTool = (data, name) => {
        return data.find(item => item.name === name)
      }
      this.certElement.map(item => {
        if (item.type === 2) {
          const domRgb = getRgb(document.getElementById(item.id), 'color')
          const fontF = {
            songti: 'RuiZiChaoPaiYanWeiSongJian-Shan-ZhunCu(REEJI-SwallowGB-Flash-Medium)-2.ttf',
            heiti: 'No.164-ShangShouJianZhengTi-2.ttf',
            kaiti: 'AaBanRuoKaiShu-2.ttf',
            hangkai: 'JiZiJingDianFangSongJianFan-Shan(GEETYPE-FangSongGBT-Flash)-2.ttf'
          }
          params.elements.push({
            type: 'dynamic_text',
            index: findTool(item.tool, 'zIndex').value + '',
            key: item.value,
            width: findTool(item.tool, 'width').value + '',
            height: findTool(item.tool, 'height').value + '',
            dst_x: item.left + '',
            dst_y: item.top + '',
            font: fontF[findTool(item.tool, 'fontFamily').value],
            size: findTool(item.tool, 'fontSize').value + '',
            color: { r: domRgb[0], g: domRgb[1], b: domRgb[2] },
            line_height: findTool(item.tool, 'fontLineH').value + '',
            font_weight: findTool(item.tool, 'fontWeight').value,
            underline: !!(findTool(item.tool, 'fontUnderline').value !== 'none'),
            angle: '0',
            align: findTool(item.tool, 'align').value + ''
          })
        }
        item.show = false
        return item
      })
      setTimeout(() => {
        this.toImage(res => {
          const dom = document.getElementById('edit-dom-1')
          const index = params.elements.findIndex(item => item.type === 'image')
          const findItem = this.certElement.find(item => item.type === 0)
          const paramElements = {
            type: 'image',
            key: res,
            width: dom.offsetWidth,
            height: dom.offsetHeight,
            dst_x: 0,
            dst_y: 0,
            index: findItem ? findTool(findItem.tool, 'zIndex').value + '' : 1
          }
          if (index !== -1) {
            params.elements[index] = paramElements
          } else {
            params.elements.push(paramElements)
          }
          params.elements = JSON.stringify(params.elements)
          this.$emit('submit', params)
        })
      }, 500)
    },
    // 删除工具
    deleteEdit(data) {
      const index = this.certElement.findIndex(item => item.id === data.id)
      this.certElement.splice(index, 1)
    },
    // html生成图片
    toImage(callback) {
      html2canvas(this.$refs.imageTofile, {
        width: document.getElementById('edit-dom-1').offsetWidth,
        backgroundColor: null,
        useCORS: true
      }).then(canvas => {
        canvas.toBlob(blob => {
          uploadBlob(blob).then(res => {
            this.toCanvasImg = res
            callback(res)
          })
        })
      })
    },
    domShow(id) {
      setTimeout(() => {
        this.certElement.map(item => {
          if (this.isShowFlag) {
            item.id === id ? (item.show = !item.show) : (item.show = false)
          }
          return item
        })
        this.isShowFlag = true
      }, 100)
    },
    // 图片上传后
    imgUpload(data) {
      // 图片上传后开启拖拽
      this.dragInit(data.id)
    },
    // 添加元素
    addElement() {
      this.certElement.map(item => {
        item.show = false
        return item
      })
      setTimeout(() => {
        this.dynamicId++
        const certBox = document.getElementById('edit-dom-1')
        // 添加图片
        if (this.selectElement === 0) {
          this.certElement.push({
            type: this.selectElement,
            title: '图片',
            tool: [
              { name: 'width', value: certBox.offsetWidth },
              { name: 'height', value: '' },
              { name: 'zIndex', value: this.certElement.length + 1 + '' }
            ],
            url: '',
            show: true,
            id: `edit-dom-${this.dynamicId}`
          })
          this.dialogVisible = false
        } else if (this.selectElement === 1) {
          this.certElement.push({
            title: '文字',
            type: this.selectElement,
            tool: [
              { name: 'zIndex', value: this.certElement.length + 1 + '' },
              {
                name: 'fontFamily',
                value: 'songti',
                optionDiv: [
                  { label: '宋体', value: 'songti' },
                  { label: '黑体', value: 'heiti' },
                  { label: '楷体', value: 'kaiti' },
                  { label: '行楷', value: 'hangkai' }
                ]
              },
              { name: 'fontColor', value: '#000000' }
            ],
            html: '请输入内容',
            show: true,
            id: `edit-dom-${this.dynamicId}`
          })
          // 添加成功后添加拖拽
          setTimeout(() => {
            this.dragInit(`edit-dom-${this.dynamicId}`)
          }, 1000)
          this.dialogVisible = false
        } else {
          this.certElement.push({
            top: '0',
            left: '0',
            title: '动态变量',
            value: this.paramValue,
            type: this.selectElement,
            tool: [
              {
                name: 'fontFamily',
                value: 'songti',
                optionDiv: [
                  { label: '宋体', value: 'songti' },
                  { label: '黑体', value: 'heiti' },
                  { label: '楷体', value: 'kaiti' },
                  { label: '行楷', value: 'hangkai' }
                ]
              },
              { name: 'fontSize', value: '16' },
              { name: 'fontColor', value: '#000000' },
              { name: 'fontLineH', value: '20' },
              {
                name: 'fontWeight',
                value: 'normal',
                optionDiv: [
                  { label: 'normal', value: 'normal' },
                  { label: 'bold', value: 'bold' }
                ]
              },
              {
                name: 'fontUnderline',
                value: 'none',
                optionDiv: [
                  { label: 'underline', value: 'underline' },
                  { label: 'none', value: 'none' }
                ]
              },
              {
                name: 'align',
                value: '1',
                optionDiv: [
                  { label: '左上', value: '1' },
                  { label: '中上', value: '2' },
                  { label: '右上', value: '3' },
                  { label: '左中', value: '4' },
                  { label: '中中', value: '5' },
                  { label: '右中', value: '6' },
                  { label: '左下', value: '7' },
                  { label: '中下', value: '8' },
                  { label: '右下', value: '9' }
                ]
              },
              { name: 'width', value: '100' },
              { name: 'height', value: '100' },
              { name: 'zIndex', value: this.certElement.length + 1 + '' }
            ],
            show: true,
            id: `edit-dom-${this.dynamicId}`
          })
          // 添加成功后添加拖拽
          setTimeout(() => {
            this.dragInit(`edit-dom-${this.dynamicId}`)
          }, 1000)
          this.dialogVisible = false
        }
      }, 100)
    },
    // 动态变量获取
    getParamOptions() {
      getParamsList().then(res => {
        this.paramOptions = res.data.list
      })
    },
    // 设置证书模型
    setCertBox() {
      const certBox = document.getElementById('edit-dom-1')
      const [propWidth, propHeight] = this.certBoxEditStyle.tool
      certBox.style.height = (propHeight.value / propWidth.value) * certBox.offsetWidth + 'px'
    },
    // 样式改变
    changeStyle(data) {
      this.$forceUpdate()
    },
    // 初始化拖拽
    dragInit(id, item) {
      const dom = document.getElementById(id)
      if (item) {
        dom.style.top = item.top + 'px' || 0
        dom.style.left = item.left + 'px' || 0
      }
      this.$nextTick(() => {
        drag(dom, document.getElementById('#edit-dom-1'), res => {
          console.log(id, '123')
          const d = this.certElement.find(i => i.id === id).show
          if (d) {
            this.isShowFlag = false
          }
          dom.style.top = res.top
          dom.style.left = res.left
          const index = this.certElement.findIndex(item => item.id === id)
          this.certElement[index].top = res.top
          this.certElement[index].left = res.left
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tool-title {
  width: 320px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  .title {
    font-size: 14px;
    color: #000000;
    span {
      color: #777484;
      font-size: 14px;
    }
  }
  .icons {
    display: flex;
    i {
      color: #2c2c2c;
      margin-left: 13px;
    }
  }
}
.edit-cert-box {
  width: 1200px;
  margin: 30px auto;
  display: flex;
}
.tool-left {
  min-width: 340px;
  // margin-right: 20px;
  .tool-btn {
    display: flex;
    justify-content: center;
  }
}
.tool-right {
  flex: 1;
  #edit-dom-1 {
    position: relative;
    border: 1px solid rgb(227, 227, 227);
    overflow: hidden;
    // background: #ffffff;
    box-sizing: border-box;
    &.active {
      border: none;
    }
    .text {
      position: absolute;
      top: 0;
      left: 0;
      font-family: 'songti';
      z-index: 1;
      &.active {
        .pop {
          &::after {
            content: '';
            width: 100%;
            height: 100%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            border: 3px dashed #004992;
            box-sizing: border-box;
          }
        }
      }
      .pop {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
      }
    }
    .text2 {
      position: absolute;
      top: 0;
      left: 0;
      font-family: 'songti';
      width: 100px;
      height: 100px;
      font-size: 16px;
      color: #000;
      line-height: 20px;
      z-index: 1;
      &.active {
        .pop {
          &::after {
            content: '';
            width: 100%;
            height: 100%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            border: 1px dashed #004992;
            box-sizing: border-box;
          }
        }
      }
      .pop {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
      }
    }
  }
}
.edit-img {
  position: absolute;
  top: 0;
  left: 0;
  &.active {
    .pop {
      &::after {
        content: '';
        width: 100%;
        height: 100%;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        border: 1px dashed #004992;
        box-sizing: border-box;
      }
    }
  }
  .pop {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
  }
}
@font-face {
  font-family: 'kaiti';
  src: url('@/assets/font/AaBanRuoKaiShu-2.ttf');
}
@font-face {
  font-family: 'songti';
  src: url('@/assets/font/RuiZiChaoPaiYanWeiSongJian-Shan-ZhunCu(REEJI-SwallowGB-Flash-Medium)-2.ttf');
}
@font-face {
  font-family: 'hangkai';
  src: url('@/assets/font/JiZiJingDianFangSongJianFan-Shan(GEETYPE-FangSongGBT-Flash)-2.ttf');
}
@font-face {
  font-family: 'heiti';
  src: url('@/assets/font/No.164-ShangShouJianZhengTi-2.ttf');
}
.tool-btn {
  display: flex;
  width: 112px;
  height: 32px;
  border: 1px solid #124ca2;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  margin-top: 20px;
  i {
    font-size: 14px;
    color: #124ca2;
    margin-right: 5px;
  }
  .txt {
    font-size: 14px;
    color: #124ca2;
  }
}
</style>
