<template>
  <a-modal
    :visible="visible"
    @cancel="handleCancel"
    width="1000px"
    title="图片裁切"
  >
    <vue-cropper
      v-if="cropperVisible"
      class="cropper-wrapper"
      ref="cropper"
      :outputSize="0.6"
      :img="options.img"
      :info="true"
      :original="false"
      :fixed="true"
      :full="true"
      :infoTrue="true"
      :centerBox="true"
      :canMoveBox="false"
      :fixedNumber="options.fixedNumber"
      :maxImgSize="options.maxImgSize"
      :autoCrop="options.autoCrop"
      :autoCropWidth="width"
      :autoCropHeight="height"
    >
    </vue-cropper>
    <template slot="footer">
      <a-button
        key="back"
        @click="handleCancel"
      >
        取消
      </a-button>
      <a-button
        key="submit"
        type="primary"
        :loading="confirmLoading"
        @click="handleSave"
      >
        保存
      </a-button>
    </template>
  </a-modal>
</template>

<script>
import http from '@/utils/request'

export default {
  props: {
    info: {
      type: Object,
      default: () => {}
    },
    width: {
      type: Number,
      default: 1920
    },
    height: {
      type: Number,
      default: 1080
    }
  },
  data () {
    return {
      visible: false,
      cropperVisible: false,
      confirmLoading: false,
      options: {
        img: '',
        maxImgSize: 1200,
        fixedBox: true,
        autoCrop: true,
        fixedNumber: [16, 9]
      }
    }
  },
  methods: {
    show (info) {
      this.visible = true
      this.options = Object.assign({}, this.options, info)
      this.cropperVisible = false
      this.$nextTick(() => {
        this.cropperVisible = true
      })
    },
    handleCancel () {
      this.visible = false
    },
    dataURLtoFile (dataurl, filename) { // 将base64转换为文件
      var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?);/)[1]

      var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
    handleSave () {
      this.$refs.cropper.getCropData((data) => {
        const file = this.dataURLtoFile(data, '截图')
        const formdata = new FormData()

        formdata.append('file', file)
        this.confirmLoading = true
        http.post(this.uploadUrl, formdata, { headers: {
          'Content-Type': 'multipart/form-data' // 之前说的以表单传数据的格式来传递fromdata
        } }).then((res) => {
          this.$emit('success', res)
          this.handleCancel()
        }).finally(() => {
          this.confirmLoading = false
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.cropper-wrapper{
    width: 100%;
    height: 400px;
  }

</style>
