<template>
  <el-dialog
    title="人脸识别"
    fullscreen
    :visible.sync="visible"
    width="30%"
    @close="handleClose">
    <FaceDetector
      v-if="visible"
      ref="face"
      v-model="resultImage"
      :default-image="imageUrl"></FaceDetector>

    <span slot="footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        type="primary"
        @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

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

export default {
  components: {
    FaceDetector
  },
  data () {
    return {
      visible: false,
      imageUrl: '',
      resultImage: null
    }
  },
  methods: {
    show (imageUrl) {
      this.resultImage = null
      this.imageUrl = imageUrl || ''
      this.visible = true

      this.$nextTick(() => {
        // 打开摄像头
        if (!imageUrl) {
          this.$refs.face.fnOpen()
        }
      })
    },
    handleClose () {
      this.visible = false
    },
    handleSubmit () {
      if (!this.resultImage) {
        this.$message.error('未获取到人脸图像，请重新选择图片或拍照')
        return
      }

      if (this.resultImage.width * this.resultImage.height < 250 * 250) {
        this.$message.error('人脸图太小，请重新选择图片或拍照')
        return
      }

      if (this.resultImage.width * this.resultImage.height > 400 * 400) {
        compressImg(this.resultImage.url, 400).then(res => {
          this.$emit('change', res)
          this.handleClose()
        })
      } else {
        this.$emit('change', this.resultImage.url)
        this.handleClose()
      }
    }
  },
  watch: {
    visible (val) {
      if (!val) {
        this.$refs.face.fnClose()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog.is-fullscreen {
  display: flex; height: 100%; margin-top: 0; flex-direction: column;
  .el-dialog__body {
    width: 100%; flex: 1; color:#000; display: flex;
  }
}
</style>
