import { Request } from "@/service/request/index.js";
import { Storage } from "@/service/storage";
const storage = new Storage();

const _baseUrl = import.meta.env.VITE_APP_API_BASEURL;
const subdomain = "/yylm";
// const subdomain = "";

export function downloadFile(url, data = {}) {
  const baseUrl = data.baseUrl || _baseUrl;
  // const baseUrl = _baseUrl
  uni.downloadFile({
    url: baseUrl + subdomain + url, //添加三九分配的子域名
    data,
    success: (res) => {
      console.log(`${data?.path}，${baseUrl + subdomain + url}，请求头`, data);
      console.log(`${data?.path}，${baseUrl + subdomain + url}，数据`, res);
      if (res.statusCode === 200) {
        uni.saveFile({
          tempFilePath: res.tempFilePath,
          success: (r) => {
            uni.showToast({
              title: "下载成功",
              icon: "success",
            });
            console.log(
              `${data?.path}，${baseUrl + subdomain + url}，uni.saveFile请求头`,
              res.tempFilePath,
            );
            console.log(
              `${data?.path}，${baseUrl + subdomain + url}，uni.saveFile数据`,
              r,
            );
          },
          fail: (err) => {
            uni.showToast({
              title: "保存失败",
              icon: "error",
            });
            console.log(
              `${data?.path}，${baseUrl + subdomain + url}，uni.saveFile请求头`,
              res.tempFilePath,
            );
            console.log(
              `${data?.path}，${baseUrl + subdomain + url}，uni.saveFile数据`,
              err,
            );
          },
        });
      } else {
        uni.showToast({
          title: "下载失败",
          icon: "error",
        });
      }
    },
    fail: (err) => {
      console.log(`${data?.path}，${baseUrl + subdomain + url}，请求头`, data);
      console.log(`${data?.path}，${baseUrl + subdomain + url}，数据`, err);
      uni.showToast({
        title: "下载失败",
        icon: "error",
      });
    },
  });
}

export default function request(url, data = {}, method = "post") {
  const uid = (storage.getStorageSync("userInfo") || { ldap: "" }).ldap;
  const d = { ...data, uid };
  const baseUrl = data.baseUrl || _baseUrl;
  // const baseUrl = _baseUrl
  return Request({
    url: subdomain + url, //添加三九分配的子域名
    method,
    data: JSON.stringify(d),
    baseUrl,
  }).then((res) => {
    console.log(`${data?.path}，${baseUrl + subdomain + url}，请求头`, d);
    console.log(`${data?.path}，${baseUrl + subdomain + url}，数据`, res);
    return res;
  });
}
