<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>

    <FaceModal
      ref="faceModal"
      @change="handleFace"></FaceModal>
  </div>
</template>

<script>
import FaceModal from './FaceModal'

export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  computed: {
    facePic () {
      return this.value ? `data:image/jpeg;base64,${this.value}` : ''
    }
  },
  components: {
    FaceModal
  },
  inject: ['skipCheck'],
  data () {
    return {
      showFace: true,
      currentImg: ''
    }
  },
  methods: {
    handleOpenCamera () {
      this.showFace = true
      this.$nextTick(() => {
        this.showFaceDetector()
      })
    },
    handleAvatarSuccess (res, list) {
      const isJPG = res.raw.type === 'image/jpeg' || res.raw.type === 'image/png'

      if (!isJPG) {
        this.$message.error('图片只能是 JPG或PNG 格式!')
        return
      }

      let reader = new FileReader()
      reader.readAsDataURL(res.raw)
      reader.onload = (e) => {
        // this.$refs.faceModal.show(e.target.result)

        this.showFaceDetector(e.target.result)
      }
    },

    showFaceDetector (msg = null) {
      const { ipcRenderer, remote } = require('electron')

      ipcRenderer.sendTo(remote.getGlobal('windows')['faceDetector'], 'showFaceDetector', msg, this.skipCheck)
      ipcRenderer.once('getDectectorResult', (event, data) => {
        if (data) {
          this.$emit('input', data.split && data.split(',')[1])
        }
      })
    },
    handleFace (e) {
      this.$emit('input', e.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>
