<template>
  <Uploader
    ref="uploaderRef"
    v-bind="props"
    :modelValue="[]"
    :maxUploadCount="single ? 1 : maxUploadCount"
    @updateList="handleListChange"
  />
</template>

<script setup lang="ts">
import { onMounted, ref, toRef, watch } from 'vue';
import { useFieldChildValueInjector } from './FormContext';
import type { UploaderInstance, UploaderProps } from './Uploader.vue';
import { stringUrlToUploaderItem, type UploaderItem } from './Uploader';
import Uploader from './Uploader.vue';

export interface UploaderFieldProps extends Omit<UploaderProps, 'value'> {
  modelValue?: string[]|string;
  /**
   * 是否为单文件上传
   * @default false
   */
  single?: boolean;
  /**
   * 是否根据modelValue自动更新已上传列表，当modelValue变化时，会自动更新已上传列表。
   * @default true
   */
  autoUpdateUploadList?: boolean;
}

const uploaderRef = ref<UploaderInstance>();
const emit = defineEmits([ 'update:modelValue' ]);
const props = withDefaults(defineProps<UploaderFieldProps>(), {
  modelValue: undefined,
  showDelete: true,
  showUpload: true,
  uploadWhenAdded: true,
  formMessage: true,
  autoUpdateUploadList: true,
});

const {
  value,
  updateValue,
} = useFieldChildValueInjector(
  toRef(props, 'modelValue'), 
  (v) => emit('update:modelValue', v),
  undefined,
  //() => { /*uploaderRef.value?.pick()*/ },
);

let nextNoChangeList = false;

watch(() => props.modelValue, (newVal) => {
  if (props.autoUpdateUploadList) {
    if (nextNoChangeList) {
      nextNoChangeList = false;
      return;
    }
    setUploaderList();
  }
})

function handleListChange(list: UploaderItem[]) {
  nextNoChangeList = true;
  const res = list.map((item) => item.uploadedPath).filter((item) => item) as string[];
  updateValue(props.single ? res[0] : res);
}
function setUploaderList() {
  uploaderRef.value?.setList(props.single || typeof value.value === 'string' 
    ? (value.value ? [ stringUrlToUploaderItem(value.value as any as string) ] : [])
    : value.value?.map((item) => stringUrlToUploaderItem(item)) ?? []
  );
}

onMounted(() => {
  setTimeout(() => setUploaderList(), 200);
});

defineExpose({
  getUploaderRef: () => {
    return uploaderRef.value
  },
})

export interface UploaderFieldInstance {
  getUploaderRef: () => UploaderInstance;
}

defineOptions({
  options: {
    styleIsolation: "shared",
    virtualHost: true,
  }
})
</script>