<template>
  <el-dialog
    title="图片采集"
    fullscreen
    :visible.sync="visible"
    width="30%"
    @close="handleClose"
    :append-to-body="true">
    <PictureDetector
      v-if="visible"
      ref="picture"
      v-model="resultImage"
      :default-image="imageUrl"></PictureDetector>

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

<script>
import PictureDetector from './PictureDetector'
import http from '@/utils/request'

export default {
  components: {
    PictureDetector
  },
  props: {
    uploadUrl: {
      type: String,
      default: () => ''
    }
  },
  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.picture.fnOpen()
        }
      })
    },
    handleClose () {
      this.visible = false
    },
    dataURLtoFile (dataurl, filename) { // 将base64转换为文件
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename + '.png', { type: mime })
    },
    handleSave (data) {
      const file = this.dataURLtoFile(data, 'pictrue')
      const formdata = new FormData()
      formdata.append('file', file)
      http.post(this.uploadUrl, formdata, { headers: {
        'Content-Type': 'multipart/form-data' // 之前说的以表单传数据的格式来传递fromdata
      } }).then((res) => {
        this.$emit('change', res.upload_path)
      }).finally(() => {
      })
    },
    handleSubmit () {
      if (this.resultImage && this.resultImage.url) {
        this.handleSave(this.resultImage.url)
        this.handleClose()
      } else {
        this.$message.error('未获取到图片信息，请先拍照')
      }
    }
  },
  watch: {
    visible (val) {
      if (!val) {
        this.$refs.picture.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>
