import Taro from "@tarojs/taro";
import { Toast } from "@nutui/nutui-react-taro";

export const uploadFile = async (file: File | string) => {
  console.log("file", file);
  const res = await Taro.uploadFile({
    url: process.env.TARO_API_DOMAIN + `/auth/upload`,
    // @ts-ignore
    filePath: file.tempFilePath || file,
    name: "file",
    header: {
      saToken: Taro.getStorageSync("saToken"),
      // "Content-Type": "multipart/form-data",
    },
  });

  if (res.errMsg == "uploadFile:ok") {
    const data = JSON.parse(res.data);

    if (data.errCode == "401") {
      Taro.removeStorageSync("user");
      Toast.show("toast", {
        icon: "warn",
        title: "",
        content: "超时请重试",
      });
      return Promise.reject();
    } else {
      return {
        url: data?.data,
      };
    }
  } else {
    Toast.show("toast", {
      icon: "fail",
      title: "",
      content: "上传失败",
    });
    return Promise.reject();
  }
};
