<template>
  <sunui-upimg 
    ref="upload"
    title="上传图片"
    :url="upPicUrl"
    :before-upload="onBeforeUpload" 
    :header="headers"
    @change="handleChange"
    v-bind="$attrs"
  />
</template>

<script setup lang="ts">
import SunuiUpimg from '@/common/components/sunui-upimg/sunui-upimg.vue';
import { toast } from '@imengyu/imengyu-utils/dist/uniapp/DialogAction';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { useAuthStore } from '@/store/auth';
import { RequestApiConfig } from '@imengyu/imengyu-utils/dist/request';

const props = defineProps({
  modelValue: {
    type: Array,
    default: null
  },
})

const authStore = useAuthStore();
const headers = computed(() => ({
  token: authStore.token,
}));
const upPicUrl = RequestApiConfig.getConfig().BaseUrl + '/common/upload';
const upload = ref();
const emit = defineEmits(['update:modelValue'])

function onBeforeUpload(file: any, index: number) {
  let fileType = ['image/png', 'image/jpeg'];

  if (file.size / 1000 > 51.2) {
    toast('图片大小不能大于50K');
    return false;
  }
  if (fileType.indexOf(file.type) === -1) {
    toast(`仅支持${fileType.join('、').replace(/image\//g, '')}图片格式`);
    return false;
  }
}
function handleChange(e: any) {
  emit('update:modelValue', props.modelValue instanceof Array ? e : (e[0] || ''));
}

watch(() => props.modelValue, (v) => {
  nextTick(() => {
    upload.value.setItems(props.modelValue instanceof Array ? props.modelValue : [ props.modelValue ]);
  })
})

onMounted(() => {
  if (props.modelValue)
    setTimeout(() => {
      upload.value?.setItems(props.modelValue instanceof Array ? props.modelValue : [ props.modelValue ]);
    }, 1000);
})
</script>