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

export const ocrAction = async (tempFilePath: string, type: string) => {
  if (type === "idcard") {
    return await ocrIdCard(tempFilePath);
  }
  if (type === "bankcard") {
    return await ocrBankCard(tempFilePath);
  }
};

const ocrIdCard = async (tempFilePath: string) => {
  return await ocr(tempFilePath, `/operation/ocrIdCard`);
};

const ocrBankCard = async (tempFilePath: string) => {
  return await ocr(tempFilePath, `/operation/ocrBankCard`);
};

async function ocr(tempFilePath: string, path: string) {
  const res = await Taro.uploadFile({
    url: process.env.TARO_API_DOMAIN + path,
    // @ts-ignore
    filePath: tempFilePath,
    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: "超时请重试",
      });
    } else {
      return data?.data;
    }
  } else {
    Toast.show("toast", {
      icon: "fail",
      title: "",
      content: "识别失败",
    });
    return Promise.reject();
  }
}
