<template>
  <div class="code-area">
    <div class="part-head">
      <h2>条码识别区域设置</h2>
    </div>
    <div class="code-area-main">
      <div class="code-area-cont">
        <img :src="imageUrl" ref="editImage" />
      </div>
      <div class="code-area-preview">
        <div class="code-area-spin">
          <div
            class="code-area-spin-img"
            :style="spinStyle"
            ref="CodeAreaSpinImg"
          ></div>
        </div>
        <div
          class="code-area-icon"
          title="顺时针旋转90度"
          @click="toRotateSpin"
        >
          <i class="icon icon-right-rotate"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Cropper from "cropperjs";

export default {
  name: "code-area",
  props: {
    imageUrl: {
      type: String,
      require: true
    },
    curSetting: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      cropper: "",
      codeRotate: 0,
      spinStyle: {}
    };
  },
  mounted() {
    this.initCropper();
  },
  methods: {
    initCropper() {
      const _this = this;
      const defCodeArea = (this.curSetting && this.curSetting.codeArea) || {};
      this.codeRotate = defCodeArea.codeRotate || 0;
      this.spinStyle = {
        transform: `translate(-50%, -50%) rotate(${this.codeRotate}deg)`
      };

      this.cropper = new Cropper(this.$refs.editImage, {
        viewMode: 1,
        checkCrossOrigin: false,
        zoomable: false,
        minCropBoxWidth: 10,
        minCropBoxHeight: 10,
        preview: _this.$refs.CodeAreaSpinImg,
        ready() {
          _this.cropper.setData(defCodeArea);
          _this.$emit("on-ready");
        }
      });
    },
    toRotateSpin() {
      this.codeRotate += 90;
      if (this.codeRotate === 360) this.codeRotate = 0;

      this.spinStyle = {
        transform: `translate(-50%, -50%) rotate(${this.codeRotate}deg)`
      };
    },
    checkValid() {
      const codeArea = {
        ...this.cropper.getData(),
        codeRotate: this.codeRotate
      };
      this.$emit("on-next", { codeArea });
    },
    pass() {
      this.$emit("on-next", { codeArea: {} });
    }
  },
  beforeDestroy() {
    if (this.cropper) {
      this.cropper.destroy();
      this.cropper = false;
    }
  }
};
</script>
