<template>
  <div class="getPicture">
    <el-upload
      class="avatar-uploader"
      :action="uploadUrl"
      :show-file-list="false"
      :auto-upload="true"
      :on-change="handleAvatarSuccess"
      :on-success="handleSuccess">
      <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>
    <PictureModal
      ref="pictureModal"
      :upload-url="uploadUrl"
      @change="handlePicture"></PictureModal>
  </div>
</template>

<script>
import PictureModal from './PictureModal'

export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  computed: {
    facePic () {
      return this.value
    },
    uploadUrl () {
      return this.$store.state.app.systemConfig.find(i => i.configKey === 'export_file_upload_url').configValue
    }
  },
  components: {
    PictureModal
  },
  data () {
    return {
      currentImg: ''
    }
  },
  methods: {
    handleOpenCamera () {
      this.$refs.pictureModal.show()
    },
    handlePicture (e) {
      this.$emit('input', e)
    },
    handleSuccess (response, file, fileList) {
      this.$emit('input', response.upload_path)
    },
    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) => {
      }
    }
  }
}
</script>

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

</style>
