<template>
  <div
    class="vue-crop-layout"
    :style="{ height: fixed[1] + 40 + 'px', width: fixed[0] + 40 + 'px' }"
  >
    <VueCropper
      ref="cropperRef"
      :img="url"
      :outputSize="1"
      canScale
      autoCrop
      :autoCropWidth="fixed[0]"
      :autoCropHeight="fixed[1]"
      centerBox
      :fixed="!!fixed"
      :fixedNumber="fixed"
      fixedBox
      :canMoveBox="false"
      @realTime="realTimeHandler"
    />
  </div>
</template>

<script setup lang="ts">
import "vue-cropper/dist/index.css";
import { ref, computed } from "vue";
import { VueCropper } from "vue-cropper";
import { QuiskExpose } from "@/helper/mount";

type CropperProps = {
  img: Blob | string;
  fixed: [number, number];
};
const props = defineProps<CropperProps>();

const url = computed(() =>
  typeof props.img === "string" ? props.img : URL.createObjectURL(props.img)
);
const scale = ref(1);
const cropperRef = ref<any>();
const realTimeHandler = (data: any) => {
  const transform = data.img.transform as string;
  if (transform) {
    const result = transform.match(/scale\((\d+(\.\d+)?)\)/);
    if (result) {
      scale.value = Number(result[1]);
    }
  }
};

defineExpose<QuiskExpose>({
  submit: () => new Promise((resolve) => cropperRef.value.getCropBlob(resolve)),
});
</script>

<style lang="scss" scoped>
.vue-crop-layout {
  height: 300px;
}
</style>

<style>
.vue-crop-layout .cropper-view-box {
  outline-color: var(--el-color-primary);
}
</style>
