<script setup lang="ts">
import { useVModel } from '@vueuse/core';
import { Upload } from 'ant-design-vue';

import GalleryPickLink from '#/components/form/components/gallery-pick-link.vue';
import { uploadFile } from '#/api/core/upload';
import { uploadToOss } from '#/utils/oss-upload';
import {
  beforeImageUpload,
  resolveUploadFile,
} from '#/utils/use-image-upload-pending';
import { preferences } from '@vben/preferences';
import { Icon } from '#/components/icon';

defineOptions({
  inheritAttrs: false,
});
const props = defineProps({
  value: {
    type: String,
    default: '',
  },
});
const emits = defineEmits(['update:value']);
const mValue = useVModel(props, 'value', emits, {
  defaultValue: props.value,
  passive: true,
});

const customRequest = async (e: any) => {
  try {
    const actualFile = resolveUploadFile(e.file as File);
    const uploadMethod = preferences.app.uploadMethod || 'direct';

    let data: { url: string };

    if (uploadMethod === 'direct') {
      data = await uploadToOss({
        file: actualFile,
      });
    } else {
      data = await uploadFile({
        file: actualFile,
      });
    }

    mValue.value = data.url;
  } catch (error) {
    console.error('头像上传失败', error);
  }
};

function onGallerySelect(urls: string[]) {
  if (urls[0]) {
    mValue.value = urls[0];
  }
}

const handleRemove = (e: Event) => {
  e.stopPropagation();
  mValue.value = '';
};
</script>
<template>
  <div class="avatar-upload-wrap">
    <Upload
      :before-upload="beforeImageUpload"
      :custom-request="customRequest"
      :show-upload-list="false"
      list-type="picture-card"
    >
      <div v-if="mValue" class="m-avatar-wrap">
        <Icon
          class="m-avatar-icon-delete"
          icon="ant-design:delete-outlined"
          @click="handleRemove"
        />
        <img :src="mValue" width="100%" />
      </div>
      <Icon v-else icon="ant-design:plus-outlined" />
    </Upload>
    <GalleryPickLink :accept-types="[0]" @select="onGallerySelect" />
  </div>
</template>
<style lang="less" scoped>
.avatar-upload-wrap {
  display: inline-block;
}

.m-avatar-wrap {
  position: relative;
  height: 102px;
  overflow: hidden;

  .m-avatar-icon-delete {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    cursor: pointer;
  }
}
</style>
