<template>
  <div>
    <choose class="uploadHeadImg" @file-is-ready="fileIsReady" :style="styles">
      <img :src="headPicSrc">
    </choose>
    <crop img-format="png" :width="cropWidth" :height="cropHeight" :source="sourceImgUrl" v-show="showCrop" @crop-success-save="cropSuccessSave" @crop-success="cropSuccess" @off="offCrop"></crop>
    <upload :url="url" img-format="png" @crop-upload-success="cropUploadSuccess" @crop-upload-fail="cropUploadFail" field="file" ki="0" :headers="headers" :params="otherParams" v-show="showUpload" :source="uploadSource" @off="offUpload" @up-step="upStepUpload"></upload>
  </div>
</template>
<script>
import Choose from "../../choose/src/choose.vue"
import Crop from "../../crop/src/crop.vue"
import Upload from "../../upload/src/upload.vue"

export default {
  name: 'UploadHeadPic',
  components: {
    Choose,
    Crop,
    Upload
  },
  props: {
    width: Number,
    height: Number,
    cropWidth: {
      type: Number,
      required: true
    },
    cropHeight: {
      type: Number,
      required: true
    },
    src: {
      type: String,
      required: true
    },
    otherParams: {
      type: Object
    },
    url: {
      type: String,
      required: true
    },
    hackOtherParams: {
      type: Function
    }
  },
  data() {
    return {
      showCrop: false,
      showUpload: false,
      sourceImgUrl: {},
      headers: {},
      uploadSource: '',
      headPicSrc: this.src,
      isSave:false
    }
  },
  methods: {
    fileIsReady(source) {
      this.showCrop = true
      this.sourceImgUrl = source
    },
    offCrop() {
      this.showCrop = false
    },
    offUpload() {
      this.showUpload = false
      if(this.isSave){
        this.$emit('go-save-header')
      }
    },
    cropSuccess(data) {
      this.showUpload = true
      this.isSave = false
      this.uploadSource = data
    },
    cropSuccessSave(data) {
      if(typeof this.hackOtherParams === 'function'){
        this.hackOtherParams().then(result =>{
          this.showUpload = true
          this.isSave = true
          this.uploadSource = data
        }).catch(error =>{

        })
      } else {
        this.showUpload = true
        this.isSave = true
        this.uploadSource = data
      }
    },
    cropUploadSuccess(data, field, key) {
      this.$emit('crop-upload-success', data,field,key)
    },
    cropUploadFail(data, field, key) {
      this.$emit('crop-upload-fail', data,field,key)
    },
    upStepUpload() {
      this.showCrop = true
    }
  },
  computed: {
    styles() {
      return `width:${this.width}px;height:${this.height}px`
    }
  },
  watch: {
    src(val) {
      this.headPicSrc = val
    }
  }
}
</script>
