import { ref } from "vue";
import { HTTP_REQUEST_URL, TOKENNAME } from "@/config/app.js";
import { toLogin, checkLogin } from "@/libs/login";
import { useAppStore } from "@/stores/app";
import { useToast } from "@/hooks/useToast";

export function useImageUpload(formData) {
  const imageList = ref([]);
  const appStore = useAppStore();
  const uploadLoading = ref(false);
  const { Toast } = useToast();

  // 上传单个文件
  const uploadFilePromise = (url) => {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: `${HTTP_REQUEST_URL}/api/front/user/upload/image`,
        filePath: url,
        name: "multipart",
        header: {
          [TOKENNAME]: appStore.tokenComputed,
        },
        formData,
        success: (res) => {
          // 兼容后端返回格式
          let data = res.data;
          if (typeof data === "string") {
            try {
              data = JSON.parse(data);
            } catch (e) {}
          }
          console.log("data", data);
          if (data?.code === 200) {
            resolve(data.data);
          } else {
            reject(data.data);
          }
        },
        fail: reject,
      });
    });
  };

  // 处理上传
  const afterRead = async (event) => {
    if (!appStore.tokenComputed && !checkLogin()) {
      toLogin();
      return Promise.reject({ msg: "未登录" });
    }
    uploadLoading.value = true;
    let lists = [].concat(event.file);
    let fileListLen = imageList.value.length;
    lists.forEach((item) => {
      imageList.value.push({
        ...item,
        status: "uploading",
        message: "上传中",
      });
    });

    // 逐个上传，每个都 try-catch，保证每个图片都能更新状态
    for (let i = 0; i < lists.length; i++) {
      const curIndex = fileListLen + i;
      try {
        const result = await uploadFilePromise(lists[i].url);
        imageList.value.splice(curIndex, 1, {
          ...imageList.value[curIndex],
          status: "success",
          message: "",
          info: result,
        });
      } catch (error) {
        imageList.value.splice(curIndex, 1, {
          ...imageList.value[curIndex],
          status: "failed",
          message: "上传失败",
        });
      }
    }
    uploadLoading.value = false;
  };

  // 删除图片
  const deletePic = (event) => {
    imageList.value.splice(event.index, 1);
  };

  return {
    uploadLoading,
    imageList,
    afterRead,
    deletePic,
  };
}
