import BASE_URL from "@/api/env.js"; //引入接口共用地址
import RequestManager from "@/utils/requestManager.js";
import {
  toast,
  clearStorageSync,
  getStorageSync,
  useRouter,
} from "@/utils/utils.js";
import systemConfig from "@/config/config.js";
const manager = new RequestManager();

// 先写死调接口
// uni.setStorageSync('token', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zaWQiOiI1YmJiYTBhMi04YmJmLTcxMmUtMjMxMy1kYTc0N2E1MGUxYzEiLCJ1bmlxdWVfbmFtZSI6Iua1i-ivlSIsInJvbGUiOiJBZG1pbiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL21vYmlsZXBob25lIjoiMTgxNzQwMTA1NjEiLCJncm91cHNpZCI6IjRiMmQ5NjYyLWE3NjgtMDhmMi1hMGM4LTc2MmI4Yzc2ZGEyYSIsIm5iZiI6MTc0NDE3OTY2NiwiZXhwIjoxNzQ0MTgzMjY2LCJpYXQiOjE3NDQxNzk2NjZ9.TTLt3vwefdrd8rx3zNN4rr0OI4yp14m781N3PC3lIHw')

const baseRequest = async (url, method, data = {}, loading = true) => {
  let requestId = manager.generateId(method, url, data);
  if (!requestId) {
    console.log("重复请求");
  }
  if (!requestId) return false;

  const header = {};
  header.Authorization = getStorageSync(systemConfig.token) || "";
  return new Promise((reslove, reject) => {
    loading && uni.showLoading({ title: "loading" });
    uni.request({
      url: BASE_URL + url,
      method: method || "GET",
      header: header,
      timeout: 10000,
      data: data || {},
      complete: () => {
        uni.hideLoading();
        manager.deleteById(requestId);
      },
      success: (successData) => {
        //console.log(successData)
        const res = successData.data;
        if (successData.statusCode == 200) {
          // 业务逻辑，自行修改，401是服务器上返回该token过期，过期后跳转到登陆页面
          if (res.code > 400) {
            clearStorageSync("token");
            useRouter(systemConfig.login_page, "reLaunch");
          } else {
            reslove(res);
          }
        } else {
          if ([401,403].includes(successData.statusCode)) {
            console.log(successData, "successData--");
            console.log("%c%s", "color:red", "登录过期");
            uni.showModal({
              title: "提示",
              content: "登陆过期,请重新登陆",
              showCancel: false,
              success: function (res) {
                let u = navigator.userAgent;
                let isAndroid =
                  u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android
                // let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios
                try {
                  if (isAndroid && AndroidJs) {
                    console.log("%c%s", "color:red", "安卓--调用返回方法");
                    const reqRow = {
                      name: "logout",
                      data: "",
                    };
                    AndroidJs.func(JSON.stringify(reqRow)); // 给安卓传参
                  } else {
                    console.log("%c%s", "color:red", "苹果--调用返回方法");
                    const reqRow = {
                      name: "back-iphone",
                      data: "",
                    };
                    window.webkit.messageHandlers.func.postMessage(
                      JSON.stringify(reqRow)
                    ); // 给ios 传参
                  }
                } catch (e) {
                  console.log(e, "e-----判断安卓苹果类型出错");
                }
              },
            });
            reject(res);
            return;
          }
          console.log("网络连接失败，请稍后重试", url);
          toast("网络连接失败，请稍后重试");
          reject(res);
        }
      },
      fail: (msg) => {
        console.log("请求：" + BASE_URL + url + "，发生错误：", err);
        toast("网络连接失败，请稍后重试");
        reject(msg);
      },
    });
  });
};

// 修改基础上传方法以支持多文件
const baseUpload = async (api, fileList, formData = {}, loading = true) => {
  if (loading) {
    uni.showLoading({
      title: "上传中...",
      mask: true,
    });
  }

  const header = {};
  header.Authorization = getStorageSync(systemConfig.token) || "";

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: BASE_URL + api,
      files: fileList.map((filePath) => ({
        name: "Files",
        uri: filePath,
      })),
      formData: formData, // 额外的表单数据
      header: header,
      success: (res) => {
        if (loading) uni.hideLoading();
        if (res.statusCode === 200) {
          const data = JSON.parse(res.data);
          if (data.succeed) {
            resolve(data);
          } else {
            uni.showToast({
              title: data.msg || "上传失败",
              icon: "none",
            });
            reject(data);
          }
        } else {
          reject(res);
        }
      },
      fail: (err) => {
        if (loading) uni.hideLoading();
        uni.showToast({
          title: "上传失败",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};

const request = {};

// 将 upload 方法添加到 request 对象中
request.upload = (api, fileList, formData, loading) =>
  baseUpload(api, fileList, formData, loading);

["options", "get", "post", "put", "head", "delete", "trace", "connect"].forEach(
  (method) => {
    request[method] = (api, data, loading) =>
      baseRequest(api, method, data, loading);
  }
);

export default request;
