<template>
  <div class="layout">
    <div
      ref="main"
      :style="styles"
      class="div-content"
      @click="handler().clickCanvas()">
      <template v-for="(item, index) in data.child" >
        <Card
          v-model="data.child[index]"
          :key="index"
          :id="index"
          :show-options="activeIndex === index"
          :canvas-width="data.w"
          :canvas-height="data.h"
          @test="(point) => handler().test(point)"
          @on-change="() => handler().onChangeCard()"
          @click="(data) => handler().clickCard(data)"
        />
      </template>
      <!-- 测试div -->
      <div :style="testStyle" class="testPoint"/>
    </div>
    <!-- <Canvas ref="canvas" :value="data" class="canvas" /> -->
  </div>
</template>

<script>
import Canvas from './canvas'
import Card from './card'
import html2canvas from 'html2canvas'
export default {
  name: 'CyCanvas',
  components: {
    Canvas,
    Card,
  },
  props: {
    value: {
      type: Object,
      default: () => {
        return {}
      },
    },
    // 是否显示组件
    show: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      data: {
        // 画布参数
        w: 1024, // 画布大小，宽度，单位px
        h: 1920, // 画布大小，高度，单位px
        bc: '', // 画布背景颜色
        bg: '', // 画布背景图片，如果设置了图片，颜色属性（bc）无效
        // 卡片信息
        child: [],
      },
      activeIndex: '', // 选中的图层索引
      testPoint: {
        x: 0,
        y: 0,
      },
    }
  },
  computed: {
    styles() {
      const { data } = this
      const { bg, w, h, bc, } = data
      const styles = {}
      styles.backgroundColor = bc || 'transparent'
      bg && (styles.backgroundImage = `url(${bg})`)
      styles.width = `${w}px` || '500px'
      styles.height = `${h}px` || '500px'
      return styles
    },
    testStyle() {
      const { testPoint } = this
      const { x, y } = testPoint
      const styles = {}
      styles.top = `${y}px` || '0px'
      styles.left = `${x}px` || '500px'
      return styles
    },
  },
  watch: {
    value(value) {
      const data = this.initData(value)
      console.log('watch value', value)
      if (JSON.stringify(data) !== JSON.stringify(this.data)) {
        this.data = data
      }
    },
    data() {
      const { activeIndex, data } = this
      this.$emit('on-change', { data, index: activeIndex }) // 选中的索引切换的时候，触发回调
      console.log('watch data', data)
    },
    activeIndex(index) {
      const { data } = this
      this.$emit('on-change', { data, index }) // 选中的索引切换的时候，触发回调
    },
  },
  created() {
    this.data = this.initData(this.value)
  },
  methods: {
    // 重新渲染
    init() {},
    // 初始化数据
    initData(value) {
      const data = {
        w: 1024, // 单位px
        h: 1920, // 单位px
        child: [],
        ...value
      }
      return data
    },
    setCanvasData(data) {
      const { bg } = data
      bg && (this.data.bg = bg)
    },
    // 设置卡片的数据
    // data的数据结构
    // data = {
    //   t: '', // type，(i：图片, p：手机, sp：侧面手机, va：可视区域)
    //   w: 100, // 单位px
    //   h: 100, // 单位px
    //   x: 0, // 坐标
    //   y: 0, // 坐标
    //   z: 1, // 层级
    //   o: 1, // 透明度
    //   bg: '', // 背景图
    //   deg: 0, // 旋转角度
    //   mbg: '', // 遮罩图片
    //   bbg: '', // 顶部图片
    // }
    // index：传值则是编辑，传空字符串则是添加新的板块
    setCardData(data, index) {
      if (index === '') {
        this.data.child.push(data) // 新增一个
      } else {
        this.data.child.splice(index, 1, { ...this.data.child[index], ...data }) // 需要改、替换
      }
      this.$emit('on-change', { data: this.data, index })
      this.$nextTick(() => {
        this.$refs.canvas?.draw()
      })
    },
    deleteCard(index) {
      this.data.child.splice(index, 1)
      this.$emit('on-change', { data: this.data, index: '' })
      this.$refs.canvas?.draw()
    },
    // 导出图片
    downImage() {
      // this.$Screenshot(document.querySelector('#wrapper')).then(canvas => {
      //   this.downFile(canvas.toDataURL('image/jpeg', 0.8), new Date().getTime())
      //   this.$message.success('图片导出成功')
      // })
      // this.$refs.canvas?.getImage()

      // #capture 就是我们要获取截图对应的 DOM 元素选择器
      html2canvas(this.$refs.main, {
        useCORS: true, // 【重要】开启跨域配置
        scale: window.devicePixelRatio < 3 ? window.devicePixelRatio : 2,
        allowTaint: true, // 允许跨域图片
      }).then((canvas) => {
        const imgData = canvas.toDataURL('image/jpeg', 1.0)
        const elink = document.createElement('a')
        elink.download = '图片'
        elink.style.display = 'none'
        elink.href = imgData
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL对象
      })
    },
    getImage() {
      return new Promise((resolve, reject) => {
        html2canvas(this.$refs.main, {
          useCORS: true, // 【重要】开启跨域配置
          scale: window.devicePixelRatio < 3 ? window.devicePixelRatio : 2,
          allowTaint: true, // 允许跨域图片
        }).then((canvas) => {
          const imgData = canvas.toDataURL('image/jpeg', 1.0)
          resolve(imgData)
        })
      })
    },
    // 定位到某个图层
    selectIndex(index) {
      this.activeIndex = (Number)(index)
    },
    handler() {
      return {
        // 点击了卡片
        clickCard: ({ id, data, }) => {
          this.activeIndex = id // 选中图层
        },
        clickCanvas: () => {
          this.activeIndex = '' // 取消图层选中
        },
        onChangeCard: () => {
          const { activeIndex, data } = this
          this.$emit('on-change', { data, index: activeIndex }) // 选中的索引切换的时候，触发回调
          this.$refs.canvas?.draw()
        },
        test: (point) => {
          this.testPoint = point
        },
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.layout {
  position: relative;
}
.div-content {
  position: relative;
  background-size: 100%;
  background-repeat: no-repeat;
  z-index: 1;
  /* overflow: hidden; */
}
.canvas {
  position: absolute;
  top: 0;
  left: 0;
}
.testPoint {
  display: none;
  background: red;
  width: 4px;
  height: 4px;
  position: absolute;
}
</style>
