<template>
  <div class='container' :class='{hide: !show}'>
    <mpvue-cropper
      ref='cropper'
      :option='cropperOpt'
      @ready='cropperReady'
      @beforeDraw='cropperBeforeDraw'
      @beforeImageLoad='cropperBeforeImageLoad'
      @beforeLoad='cropperLoad'
      ></mpvue-cropper>
    <div class='cropper-buttons'>
      <button v-if='!readyToConfirm' :disabled='waiting' @tap='exit' type='warn'>退出</button>
      <button v-if='readyToConfirm' :disabled='waiting' @tap='back' type='primary'>返回</button>
      <button v-else @tap='uploadTap' :disabled='waiting' type='primary'>重新上传</button>
      <button v-if='readyToConfirm' :disabled='waiting' @tap='confirm' type='warn'>上传头像</button>
      <button v-else :disabled='waiting' @tap='preview' type='primary'>确认</button>
    </div>
  </div>
</template>

<script>
import MpvueCropper from 'mpvue-cropper'

let wecropper

const device = wx.getSystemInfoSync();
const width = device.windowWidth;
let height = 0;
let mbbc;
try{
  mbbc = wx.getMenuButtonBoundingClientRect()?wx.getMenuButtonBoundingClientRect():null;
  if(!mbbc){
    throw new Error('getMenuButtonBoundingClientRect error');
  }else{
    height = device.windowHeight - 10 - (mbbc.bottom + mbbc.top - device.statusBarHeight);
  }
}catch (e) {
  height = device.windowHeight - 10 - 44;
}
let originSrc = ''
let currentSrc = ''

export default {
  props: { show: { default: false } },
  data () {
    return {
      cropperOpt: {
        id: 'cropper',
        targetId: 'targetCropper',
        pixelRatio: device.pixelRatio,
        width,
        height,
        scale: 2.5,
        zoom: 8,
        cut: {
          x: (width - 300) / 2,
          y: (height - 300) / 2,
          width: 300,
          height: 300
        },
        boundStyle: {
          color: '#04b00f',
          mask: 'rgba(0,0,0,.8)',
          lineWidth: 1
        }
      },
      readyToConfirm: false,
      waiting: false
    }
  },

  components: {
    MpvueCropper
  },

  methods: {
    cropperBeforeImageLoad (...args) {
      console.log('before image load')
      wx.hideLoading()
    },
    cropperLoad (...args) {
      console.log('image loaded')
    },
    setInitialImg(src){
      originSrc = src
      wecropper.pushOrigin(src)
    },
    uploadTap () {
      this.waiting = true
      wx.showLoading({ title:'正在加载' })
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: res => {
          originSrc = res.tempFilePaths[0]
          wecropper.pushOrigin(originSrc)
          this.waiting = false
          wx.hideLoading()
        },
        fail: err => {
          this.waiting = false
          wx.hideLoading()
        }
      })
    },
    back(){
      wecropper.pushOrigin(originSrc)
      this.readyToConfirm = false
      this.waiting = false
      wecropper.allowTouchmove()
    },
    preview () {
      this.waiting = true
      wx.showLoading({title:'正在生成'})
      wecropper.getCropperImage((tempFilePath) => {
        console.log(tempFilePath)
        // tempFilePath 为裁剪后的图片临时路径
        if (tempFilePath) {
          // wx.previewImage({
          //   current: '',
          //   urls: [tempFilePath]
          // })
          wecropper.pushOrigin(tempFilePath)
          this.readyToConfirm = true
          currentSrc = tempFilePath
          this.waiting = false
        } else {
          console.log('获取图片地址失败，请稍后重试')
        }
      })
    },
    confirm(){
      this.$emit('confirm', currentSrc)
    },
    exit() {
      this.$emit('exit')
      this.clear()
    },
    startWaiting(){
      this.waiting = true
    },
    stopWaiting(){
      this.waiting = false
    },
    clear(){
      originSrc = ''
      currentSrc = ''
      this.readyToConfirm = false
      this.waiting = false
      wecropper.allowTouchmove()
    }
  },
  mounted () {
    wecropper = this.$refs.cropper
  }
}
</script>

<style lang='stylus' scoped>
.container
  position fixed
  top 0
  left 0
  Height_Width(100%)
  display flex
  flex-direction column
  z-index 1
.cropper-buttons
  Flex(flex,space-between,center)
  // position fixed
  // bottom 0
  // left 0
  flex auto
  width 100%
  padding 0 20rpx
  box-sizing border-box
  // background white
  z-index 99999
  button
    height 30px
    line-height 30px
    margin 0
</style>
