<template>
  <div class="layout">
    <div :style="styles">
      <canvas ref="canvas"/>
    </div>
    <!-- <div class="testbox">test</div> -->
    <!-- <canvas ref="canvas2" style="background: #ccc;"/> -->
  </div>
</template>

<script>

export default {
  props: {
    value: {
      type: Object,
      default: () => {
        return {}
      },
    }
  },
  data() {
    return {
      canvas: '',
      data: {
        // 画布参数
        w: 1024, // 单位px
        h: 1920, // 单位px
        bc: '',
        bg: '',
        // 卡片信息
        child: [],
      },
    }
  },
  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) {
      console.log('watch canvas value', value)
      const data = this.initData(value)
      if (JSON.stringify(data) !== JSON.stringify(this.data)) {
        this.data = data
      }
    },
    data() {
      console.log('watch data', this.data)

      const { activeIndex, data } = this
      this.$emit('on-change', { data, index: activeIndex }) // 选中的索引切换的时候，触发回调
      this.draw()
    },
    activeIndex(index) {
      const { data } = this
      this.$emit('on-change', { data, index }) // 选中的索引切换的时候，触发回调
    },
  },
  created() {
    console.log('created', this.value)
    this.data = this.initData(this.value)
  },
  mounted() {
    this.draw()
    // this.init2()
  },
  methods: {
    draw() {
      const { data } = this
      const { w, h } = data
      const canvas = this.$refs.canvas
      const { child } = data
      canvas.width = w
      canvas.height = h
      const ctx = canvas.getContext('2d')

      const handle = (property) => {
        return function(a, b) {
          const val1 = a[property]
          const val2 = b[property]
          return val1 - val2
        }
      }

      if (data.bg) {
        const card = new Card({
          x: 0,
          y: 0,
          width: data.w,
          height: data.h,
          bgImg: data.bg,
        })
        card.draw(ctx)
      }

      if (child) {
        const drawList = [...child]
        drawList.sort(handle('z'))
        drawList.forEach(item => {
          const { x, y, w, h, bg, deg, t } = item
          const card = new Card({
            x,
            y,
            width: w,
            height: h,
            bgImg: bg,
            deg,
            type: t,
          })
          card.draw(ctx)
        })
      }
    },
    // 初始化数据
    initData(value) {
      const data = {
        w: 1024, // 单位px
        h: 1920, // 单位px
        child: [],
        ...value
      }
      return data
    },
    // 导出图片
    getImage() {
      const canvas = this.$refs.canvas
      const imageData = canvas.toDataURL('image/png') // 返回base64的URL
      const elink = document.createElement('a')
      elink.download = '图片'
      elink.style.display = 'none'
      elink.href = imageData
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL对象

      // this.$Screenshot(document.querySelector('#wrapper')).then(canvas => {
      //   this.downFile(canvas.toDataURL('image/jpeg', 0.8), new Date().getTime())
      //   this.$message.success('图片导出成功')
      // })
    },
  },
}

function Card(params) {
  const { x, y, width, height, bgImg, deg, type } = params
  this.x = x // x 坐标
  this.y = y // y 坐标
  this.width = width // 宽度
  this.height = height // 高度
  this.bgImg = bgImg // 图片路径
  this.type = type // 类型，i：图片, p：手机, sp：侧面手机, va：可视区域

  // this.draw = function(ctx) {
  //   ctx.fillStyle = 'red'

  //   // 计算矩形的中心
  //   const centerX = x + width / 2
  //   const centerY = y + height / 2

  //   // ctx.translate(-centerX, -centerY)
  //   ctx.fillRect(this.x, this.y, this.width, this.height)
  //   // ctx.translate(centerX, centerY)
  // }

  this.draw = function(ctx) {
    const img = new Image()
    // img.setAttribute('crossOrigin', 'anonymous') // 设置跨域属性
    img.crossOrigin = 'anonymous'
    img.src = this.bgImg

    img.onload = () => {
      // 计算图片缩放比例
      const imgWidth = img.width
      const imgHeight = img.height
      const scaleX = width / imgWidth
      const scaleY = height / imgHeight

      // 创建图案
      var pattern = ctx.createPattern(img, 'no-repeat')
      // ctx.scale(scaleX, scaleY)
      ctx.fillStyle = pattern

      // 计算矩形的中心
      const centerX = x + width / 2
      const centerY = y + height / 2
      ctx.translate(centerX, centerY)
      ctx.rotate(Math.PI * (deg / 180))
      ctx.translate(-centerX, -centerY)
      if (this.type === 'va') {
        // ctx.globalCompositeOperation = 'destination-in'
      } else {
        ctx.globalCompositeOperation = 'source-over'
      }

      ctx.drawImage(img, 0, 0, img.width, img.height, x, y, width, height)
      ctx.translate(centerX, centerY)
      ctx.rotate(Math.PI * (-deg / 180))
      ctx.translate(-centerX, -centerY)
      console.log('渲染图片', params)
    }
  }
}

// 绘制矩形
function drawRect() {

}
</script>

<style lang="scss" scoped>
.layout{
  position: relative;
}
.testbox {
  position: absolute;
  top: 100px;
  left: 400px;
  background: red;
  height: 100px;
  width: 100px;
}
.test {
  position: absolute;
  left: 0;
  top: 0;
}
</style>
