<!--  -->
<template>
  <div class="avatarsBox" @mouseover="showIcon = true" @mouseleave="showIcon = false">
    <div style="width: 130px; height: 130px;">
      <v-img :src="getUserAvatar(avatarResult, '1')" width="130" height="130" style="border-radius: 6px;"></v-img>
      <div v-show="showIcon" @click="openFileInput" class="mdi mdi-camera-outline camera">
        <input
          type="file"
          ref="fileInput"
          accept="image/png, image/jpg, image/jpeg"
          style="display: none;"
          @change="handleUploadFile"
        />
      </div>
    </div>
  </div>
  <!-- <Loading :visible="overlay"></Loading> -->
  <!-- 图片裁剪 -->
  <ImgCropper :visible="isShowCopper" :image="selectPic" :cropBoxResizable="true" @submit="handleHideCopper" :aspectRatio="1 / 1" @close="isShowCopper = false, selectPic = ''"></ImgCropper>
</template>

<script setup>
defineOptions({ name: 'resumeAnalysis-avatar'})
import { getUserAvatar } from '@/utils/avatar'
// import { blobToJson } from '@/utils'
import { ref } from 'vue'
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  data: {
    type: String,
    default: ''
  }
})

const showIcon = ref(false)

// 选择文件
const fileInput = ref()
const clicked = ref(false)
const openFileInput = () => {
  if (clicked.value) return
  clicked.value = true
  fileInput.value.click()
  clicked.value = false
}

// 上传头像
const selectPic = ref('')
const isShowCopper = ref(false)
const accept = ['jpg', 'png', 'jpeg']
const handleUploadFile = async (e) => {
  const file = e.target.files[0]
  const fileType = file.name.split('.')[1]
  if (!accept.includes(fileType)) return Snackbar.warning('请上传图片格式')
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    selectPic.value = String(reader.result)
    isShowCopper.value = true
  }
}

const avatarResult = ref(props.data)

// 图片裁剪
const handleHideCopper = async (res) => {
  isShowCopper.value = false
  avatarResult.value = res?.result.dataURL || ''
  // avatarResult.value = res?.result ? Reflect.get(res.result, 'dataURL') : ''
}

const submit = async () => {
  return { id: props.id, data: avatarResult.value}
}

defineExpose({
  id: props.id,
  submit
})
</script>
<style lang="scss" scoped>
.avatarsBox {
  height: 150px;
  width: 120px;
  position: relative;
  cursor: pointer;
  margin: 0 32px;
  .camera {
    color: #fff;
    font-size: 42px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
