<script setup>
import { REQUEST } from "~/utils/request";
import { resolveFileString } from "~/utils/helper";

const props = defineProps({
  // part: String,
  // full: String,
  limit: String,
  isDisabled: String,
  modelValue: String,
});

// let isDisabled =
// const emits = defineEmits(['update:part', 'update:full'])
const emits = defineEmits(["update:modelValue"]);
let fileList = $ref(
  resolveFileString(props?.modelValue).map((_) => ({ ..._, res: _ }))
);

// if (props.part) {
//   fileList = resolveFileString(props.part)
// }
// if (props.full) {
//   fileList = resolveFileString(props.full)
// }
let showUpload = $ref(true);
const handleAfterRead = (fileProxy) => {
  fileProxy.status = "uploading";
  fileProxy.message = "上传中...";
  const { file } = fileProxy;
  REQUEST["upload"]({
    timeout: 30 * 60 * 1000,
    url: "/upload/main/file",
    data: { filedata: file,token:'' },
  })
    .then((res) => {
      console.log("res :>> ", res);
      console.log("fileList :>> ", fileList);
      if (res.code === "1") {
        // fileList.value.push(res.data)
        fileProxy.url = window.GLOBAL_CONFIG.oss + "/" + res.data.url;
        fileProxy.res = {
          name: res.data.file_name,
          url: fileProxy.url,
          origin: res.data.url,
        };
        fileProxy.status = "done";
        fileProxy.message = "";
        showUpload = false;

        // emits('update:part', fileList.map((item) => item.res.name + ',' + item.res.url).join(';'))
        // emits('update:part', fileList.map((item) => item.res.name + ',' + item.res.url).join(';'))
        emits(
          "update:modelValue",
          fileList
            .map((item) => item.res.name + "," + item.res.origin)
            .join(";")
        );
      } else {
        fileProxy.status = "failed";
        fileProxy.message = "上传失败";
        showUpload = true;
      }
    })
    .catch((err) => {
      console.error(err);
    });
};
function beforeDelate(file, detail) {
  fileList.splice(detail.index, 1);
  showUpload = true;
  return true;
}
</script>

<template>
  <van-uploader
    v-model="fileList"
    :after-read="handleAfterRead"
    :before-delete="beforeDelate"
    :disabled="props.isDisabled"
    :max-count="props.limit"
    accept=".jpg,.png,.jpeg,.webp"
  >
    <img v-if="showUpload" src="@/assets/images/img_upload.png" alt="" />
  </van-uploader>
</template>
