<template>
  <el-dialog
      :visible.sync=dialogVisible
      :width="'590px'"
      :title="'裁剪图片'"
      :close-on-click-modal="false"
  >
    <div class="cropper-content">
      <vueCropper
        ref="cropper"
        :mode="'contain'"
        :img="option.img"
        :autoCropWidth="140"
        :autoCropHeight="140"
        :canScale="false"
        :canMoveBox="false"
        :centerBox="true"
        :infoTrue="true"
        :autoCrop="true"
        :fixedBox="true"
      ></vueCropper>
    </div>
    <div class="cut-menu">
      <div class="slider-icon">
        <div><i class="el-icon-remove-bold icon-btn" @click="changeScale('remove')"></i></div>
        <div class="icon-slider">
          <el-slider v-model="value" :step="0.1" :min="0.8" :max="3"></el-slider>
        </div>
        <div><i class="el-icon-plus-bold icon-btn" @click="changeScale('add')"></i></div>
      </div>
      <div>
        <i class="el-icon-rotate-right icon-btn" @click="rotateRight"></i>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="secondary" @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="cutSave">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { VueCropper }  from 'vue-cropper'
import ElDialog from 'modesign-ui/packages/dialog';
import ElSlider from 'modesign-ui/packages/slider';
import ElButton from 'modesign-ui/packages/button';

export default {
  name: "CutDialog",
  components: {
    VueCropper,
    ElDialog,
    ElSlider,
    ElButton
  },
  data() {
    return{
      dialogVisible: false,
      show: false,
      option: {
        img: '',
      },
      value: 1,
      ev: {}
    }
  },
  watch:{
    value(newValue, oldValue) {
      let num = 170/this.$refs.cropper.trueHeight
      if (newValue > oldValue) {
        this.$refs.cropper.changeScale(num)
      } else {
        this.$refs.cropper.changeScale(-num)
      }
    }
  },
  methods:{
    getData(ev) {
      this.dialogVisible = true
      this.ev = ev.target.files[0]
      this.option.img = URL.createObjectURL(ev.target.files[0])
    },
    changeScale(type) {
      let num = 170/this.$refs.cropper.trueHeight
      if (type === 'add') {
        if (this.value < 3){
          this.value = this.value + 0.1
          this.$refs.cropper.changeScale(num)
        }
      } else {
        if (this.value > 0.8){
          this.value = this.value - 0.1
          this.$refs.cropper.changeScale(-num)
        }
      }
      this.value = Number(this.value.toFixed(1))
    },
    rotateRight() {
      this.$refs.cropper.rotateRight()
    },
    cutSave() {
      this.$refs.cropper.getCropBlob(data => {
        let fileList = []
        fileList.push(new File([data], this.ev.name, { type: data.type }))
        this.$parent.$children[0].uploadFiles(fileList)
        this.dialogVisible = false
      })
    }
  }
}
</script>
