<template>
  <div>
    <n-upload
      :default-file-list="fileList"
      v-bind="getImgOptions"
      :on-change="handleChange"
      :on-before-upload="handleBeforeUpload"
    >
      点击上传
    </n-upload>
    <n-modal
      preset="card"
      style="width: 600px"
    >
      <img :src="previewImageUrl" style="width: 100%">
    </n-modal>
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, computed, unref } from 'vue'
import { getToken } from '@/utils/token'
export default defineComponent({
  name: 'ImgUpload',
  props: {
    options: {
      type: Object,
      default: null
    },
    size: {
      type: Number,
      default: null
    }
  },
  setup(props, { emit }) {
    const data = reactive({
      fileList: []
    })
    const BaseURL = window.__APP__GLOB__CONF__?.VITE_APP_GLOB_BASE_API || import.meta.env.VITE_APP_GLOB_BASE_API
    const getImgOptions = computed(() => {
      return {
        ...unref(props.options),
        listType: 'image-card',
        defaultUpload: props.options.defaultUpload || false,
        action: `${BaseURL}${props.options.action}`,
        headers: {
          'Authorization': getToken(),
          ...props.options.headers
        }
      }
    })
    function handleChange(res) {
      console.log('已选择的文件：', res.file.file)
    }
    /**
     * @description: 上传前判断文件是否符合条件
     * @param {*} options
     * @return {*}
     */
    function handleBeforeUpload(options) {
      const { file, fileList } = options
      if (props.size) {
        const size = file.file.size
        if (size < props.size * 1024 * 1024) {
          fileList.splice(fileList.length - 1)
          $message.error('选择的文件大小不满足条件！')
        }
      }
    }
    return {
      ...toRefs(data),
      getImgOptions,
      handleChange,
      handleBeforeUpload
    }
  }
})

</script>
<style scoped lang='scss'>
</style>
