<template>
  <view class="single-image-uploader">
    <popOver placement="bottom-end" :options="optionsList" key-name="text" isArrow ref="popoverRef"
      @select="selectItem">
      <i class="icon-font icon-camera"></i>
    </popOver>
  </view>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import popOver from './popover.vue'
import { uploadChooseImage, $upload, Toast } from '@/utils';
import { t } from "@/locale"

const props = defineProps({

});

const emit = defineEmits(['upload-success', 'change']);
const optionsList = ref([{
  type: 'camera',
  text: '拍照'
}, {
  type: 'album',
  text: '相册'
}])

const actionSheet = ref(null);
const imageUrl = ref('');

const selectItem = async (item) => {
  try {
    let file = await uploadChooseImage(item.type);
    file.image = file.tempFile
    const res = await $upload('image', file);
    nextTick(() => {
      imageUrl.value = res.data.url
      emit('upload-success', imageUrl.value);
      emit('change', imageUrl.value)
    })
  } catch (error) {
    // Toast(t('上传失败'))
  }
}

// 暴露方法给父组件
defineExpose({
  getImageUrl: () => imageUrl.value,
  setImageUrl: (url) => {
    imageUrl.value = url;
    emit('change', url);
  }
});
</script>

<style scoped>
.icon-camera {
  color: #adb8cc;
  font-size: 56rpx;
}
</style>