<template>
  <div ref="outContianer" style="width: 100%">
    <div :style="{ width: containerDimensions.width + 'px', height: containerDimensions.height + 'px' }">
      <vueCropper
        ref="cropper"
        :img="option.img"
        :canScale="option.canScale"
        :full="option.full"
        :outputSize="option.size"
        :centerBox="option.centerBox"
        :autoCrop="option.autoCrop"
        :autoCropWidth="option.autoCropWidth"
        :autoCropHeight="option.autoCropHeight"
        :fixedBox="option.fixedBox"
        :canMove="option.canMove"
        :mode="option.mode"
        :info="option.info"
        @cropMoving="debouncedCropMoving"></vueCropper>
    </div>
  </div>
  <div style="padding-top: 8px">
    <el-text class="mx-1">预览:</el-text>
    <img :src="previewImg" style="width: 30%;" />
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue'
import 'vue-cropper/dist/index.css'
import { VueCropper } from 'vue-cropper'
import emitter from '/@/utils/emitter'
import _ from 'lodash'

const cropper = ref()
const containerDimensions = ref({ width: 100, height: 100 })

const option = ref({
  img: '',
  size: 1,
  info: false,
  autoCrop: true,
  autoCropWidth: 600,
  autoCropHeight: 100,
  canScale: false,
  full: false,
  fixedBox: true,
  centerBox: true,
  canMove: false,
  enlarge: 1,
  mode: 'contain',
  original: false,
  outputType: 'png',
})

// 根据图片大小缩放设置容器大小以及裁剪框大小
const outContianer = ref()
let scale

emitter.on('img-src', (value) => {
  option.value.img = value
})

emitter.on('img-data', (value) => {
  option.value.autoCropWidth = 628
  option.value.autoCropHeight = 628

  scale = Math.min(outContianer.value.offsetWidth / value.width, 1) // 缩放图片宽度到最大不超过容器宽度

  // 计算缩放后的图片尺寸
  const scaledWidth = value.width * scale
  const scaledHeight = value.height * scale

  // 更新容器尺寸
  containerDimensions.value.width = scaledWidth
  containerDimensions.value.height = scaledHeight

  // 更新裁剪框尺寸
  option.value.autoCropWidth = option.value.autoCropWidth * scale
  option.value.autoCropHeight = option.value.autoCropHeight * scale
})

// 移动裁剪框后获取坐标 以及 渲染裁剪框图片
const previewImg = ref('')

function cropMoving(data) {
  const left = parseInt((data.axis.x1 / scale).toFixed(0)) // 结果保留整数
  const top = parseInt((data.axis.y1 / scale).toFixed(0))

  emitter.emit('send-img628-leftTop', { left: left, top: top, width: 628, height: 628 })
  
  cropper.value.getCropData((data) => {
    // 获取base64数据图片
    previewImg.value = data
  })
}

const debouncedCropMoving = _.debounce(cropMoving, 100)

onBeforeUnmount(() => {
  emitter.all.clear()
})
</script>
