<template>
  <div class="getFace">
    <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      :auto-upload="false"
      :on-change="handleAvatarSuccess">
      <div
        v-if="facePic"
        :style="{backgroundImage:`url(${facePic})`}"
        class="avatar"></div>
      <i
        v-else
        class="el-icon-plus avatar-uploader-icon"
      ></i>
    </el-upload>

    <el-button
      style="margin-left:10px"
      type="primary"
      icon="el-icon-camera-solid"
      @click="handleOpenCamera">
      拍照
    </el-button>

    <Face
      v-if="showFace"
      ref="face"
      @close="showFace=false"
      @change="handleFace"></Face>

    <StaticFace
      ref="staticFace"
      :current-img="currentImg"
      @change="handleFace"></StaticFace>
  </div>
</template>

<script>
import Face from './Face'
import StaticFace from './StaticFace'
import compressImg from '@/assets/compress'

export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  computed: {
    facePic () {
      return this.value ? `data:image/jpeg;base64,${this.value}` : ''
    }
  },
  components: {
    Face,
    StaticFace
  },
  data () {
    return {
      showFace: true,
      currentImg: ''
    }
  },
  methods: {
    handleOpenCamera () {
      this.showFace = true
      this.$nextTick(() => {
        this.$refs.face.show()
      })
    },
    handleAvatarSuccess (res, list) {
      const isJPG = res.raw.type === 'image/jpeg' || res.raw.type === 'image/png'
      const isLt2M = res.raw.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('图片只能是 JPG或PNG 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return
      }
      let reader = new FileReader()
      reader.readAsDataURL(res.raw)
      reader.onload = (e) => {
        this.currentImg = e.target.result
        this.$refs.staticFace.show()
      }
    },
    async handleFace (e) {
      var url = await compressImg(e, 400)
      this.$emit('input', url.split(',')[1])
    }
  }
}
</script>

<style lang="scss" scoped>
.getFace {
  display: inline-block;
  ::v-deep .el-icon-camera-solid {
    font-size: 1.2em;
  }
}
.avatar-uploader {
  display: inline-block; vertical-align: top;
}

</style>
