//存放主站域名
// const BASE_URL = 'http://192.168.1.5:8081' // w
const BASE_URL = "http://192.168.1.9:8081"; // yx
// const BASE_URL = 'http://47.100.212.83:18088' // 正式环境接口
// const BASE_URL = 'http://192.168.1.9:8088' // 测试环境接口
// const BASE_URL = 'http://192.168.1.5:8088' // 测试环境接口
const BASE_URL_IMG = BASE_URL + "/img/upload"; // 上传图片
// 存储请求记录
let requestRecords = {};
// 重复请求拦截时间（毫秒）
const INTERCEPT_DURATION = 2000;
const request = (
  url,
  data = {},
  method = "GET",
  ContentType = "application/json",
) => {
  const requestObj = {
    data,
    url,
    time: Date.now(),
  };
  // if (method !== "GET") {
  //   if (Object.keys(requestRecords).length == 0) {
  //     requestRecords = requestObj;
  //   } else {
  //     const s_url = requestRecords.url; // 请求地址
  //     const s_data = requestRecords.data; // 请求数据
  //     const s_time = requestRecords.time; // 请求时间
  //     if (
  //       s_data === requestObj.data &&
  //       requestObj.time - s_time < INTERCEPT_DURATION &&
  //       s_url === requestObj.url
  //     ) {
  //       uni.showToast({
  //         title: "数据正在处理，请勿重复提交",
  //         icon: "none",
  //         duration: 2000,
  //       });
  //       return;
  //     }
  //     requestRecords = requestObj;
  //   }
  // }

  return new Promise(function (resolve, reject) {
    let header = {};
    if (uni.getStorageSync("app_token")) {
      header = {
        "Content-Type": ContentType,
        Authorization: uni.getStorageSync("app_token"),
      };
    } else {
      header = {
        "Content-Type": ContentType,
      };
    }
    if (Object.keys(data).length && !data.showLoading) {
      uni.showLoading({
        title: "加载中",
        mask: true,
      });
    }
    // console.log("请求参数", data, url);
    uni.request({
      url: BASE_URL + url,
      data,
      method,
      header,
      success: function (res) {
        console.log("res", res);
        if (res.data.code == 200) {
          resolve(res.data);
        } else if (res.data.code == 401) {
          const pages = getCurrentPages();
          if (pages[pages.length - 1].route !== "pages/login/login") {
            uni.navigateTo({
              url: "/pages/login/login",
            });
          }
        } else {
          if (Object.keys(res.data).length && !data.showLoading) {
            uni.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000,
            });
          }
          reject(res);
        }
      },
      fail: function (err) {
        console.log("err", err);
        uni.getNetworkType({
          success: function (res) {
            console.log("当前网络状态:", res.networkType);
            if (res.networkType === "none") {
              console.log("当前无网络");
              uni.showToast({
                title: "当前网络不可用，请检查网络连接",
                icon: "none",
              });
              return;
            } else {
              uni.showToast({
                title: "加载失败，请稍后重试！",
                icon: "none",
                duration: 2000,
              });
            }
          },
        });
        reject(err);
      },
      complete: function () {
        // console.log("结束");
        if (!data.showLoading) {
          uni.hideLoading();
        }
      },
    });
  });
};

// 图片
const Upload = (url, source, formData) => {
  console.log("进入上传方法", url, source, formData);
  const ContentType = "application/json";

  return new Promise(function (resolve, reject) {
    console.log(source);
    let header = {};
    if (uni.getStorageSync("app_token")) {
      header = {
        "Content-Type": ContentType,
        authorization: uni.getStorageSync("app_token"),
        // Accept: "application/json",
        // "Content-Type": "multipart/form-data",
      };
    }
    console.log(BASE_URL + url, source, formData, header);
    console.log(
      typeof source === "string" ? { filePath: source } : { files: source },
    );
    uni.uploadFile({
      url: BASE_URL + url,
      ...(typeof source === "string"
        ? { filePath: source } // 单文件：使用filePath
        : { files: source }), // 多文件：使用files
      name: "files",
      formData,
      // name,
      header,
      success: function (res) {
        console.log("成功返回res", res);
        let obj1 = JSON.parse(res.data);
        uni.hideLoading();
        if (obj1.code !== 200) {
          uni.showToast({
            title: obj1.message,
            icon: "none",
            duration: 2000,
          });
        } else {
          uni.showToast({
            title: "上传成功",
            icon: "success",
            duration: 1000,
          });
          resolve(obj1);
        }
      },
      fail: function (err) {
        console.log("失败返回err", err);
        console.log("失败999", JSON.stringify(err));
        uni.hideLoading();
        uni.showToast({
          title: "加载失败, 请稍后再试!",
          icon: "none",
          duration: 2000,
        });
      },
      complete: function () {},
    });
  });
};
// 文件上传
const UploadFile = (url, data = {}, source) => {
  return new Promise(function (resolve, reject) {
    // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
    data["name"] = "upload_resource";
    let time = Math.floor(new Date().getTime() / 1000);
    let sign = "";
    var params = Object.keys(data).sort();
    for (var ki in params) {
      sign +=
        (sign.indexOf("=") !== -1 ? "&" : "") +
        params[ki] +
        "=" +
        encodeURIComponent(data[params[ki]]);
    }
    data["sign"] = md5(md5(sign) + "e8aac119d38cee477e49d0155832b7f4" + time);
    data["time"] = time;

    uni.uploadFile({
      url: BASE_URL + url, //仅为示例，非真实的接口地址
      filePath: source.tempFiles[0].path,
      name: "upload_resource",
      formData: data,
      success: function (res) {
        res.data = JSON.parse(res.data);
        uni.hideLoading();
        // uni.showToast({
        //   title: '图片上传成功',
        //   icon: 'success',
        //   duration: 1000
        // })
        if (data.returnAll) {
          // 是否返回所有信息（成功或者失败都返回）
          return resolve(res.data);
        }
        if (res.data.state) {
          resolve(res.data);
        } else {
          uni.showToast({
            title: res.data.message,
            icon: "none",
          });
        }
      },
      fail: function (err) {
        uni.hideLoading();
        uni.showToast({
          title: "加载失败，请退出后重试！",
          icon: "none",
          duration: 2000,
        });
      },
      complete: function () {},
    });
  });
};

/**
 * 多文件上传（支持并行/串行）
 * @param {Array} files - 要上传的文件数组
 * @param {Boolean} sequential - 是否串行上传（默认 false = 并行）
 * @returns {Promise<Array>} - 所有文件的上传结果（含成功/失败信息）
 */
const uploadMultipleFiles = async (
  url,
  files,
  formData,
  sequential = false,
) => {
  let header = {};
  if (uni.getStorageSync("app_token")) {
    header = {
      authorization: uni.getStorageSync("app_token"),
    };
  }
  // 2. 并行上传逻辑
  if (!sequential) {
    // 循环生成每个文件的上传 Promise
    const uploadPromises = files.map((file, index) => {
      return new Promise((resolve) => {
        uni.uploadFile({
          url: BASE_URL + url,
          filePath: file,
          name: "file",
          header,
          formData,
          // 上传成功处理
          success: (res) => {
            try {
              const result = JSON.parse(res.data);
              console.log("成功,", result, res);
              if (result.code === 200 && result.data?.fileUrlList[0].url) {
                resolve({
                  index, // 保留原文件在数组中的索引（方便对应）
                  // file, // 原始文件信息
                  url: result.data.fileUrlList[0].url,
                  name: result.data.fileUrlList[0].name,
                  success: true,
                  error: null,
                });
              } else {
                // 后端返回失败（如文件格式不允许）
                resolve({
                  index,
                  file,
                  url: null,
                  success: false,
                  error: new Error(result.msg || "文件上传失败"),
                });
              }
            } catch (e) {
              resolve({
                index,
                file,
                url: null,
                success: false,
                error: new Error("上传结果解析失败：" + e.message),
              });
            }
          },
          fail: (err) => {
            resolve({
              index,
              file,
              url: null,
              success: false,
              error: new Error("上传请求失败：" + err.errMsg),
            });
          },
        });
      });
    });
    console.log(uploadPromises, "uploadPromises1111");

    // 等待所有请求完成，返回统一结果
    return Promise.allSettled(uploadPromises).then((results) => {
      // 提取实际结果（allSettled 返回的是 {status, value} 结构）
      return results.map((res) => res.value);
    });
  } // 接上文的 if (!sequential) 之后
  else {
    const uploadResults = []; // 存储所有结果
    // 递归函数：上传第 index 个文件
    const uploadNext = (index) => {
      // 终止条件：所有文件处理完，返回结果
      if (index >= files.length) {
        return Promise.resolve(uploadResults);
      }

      const currentFile = files[index];
      return new Promise((resolve) => {
        uni.uploadFile({
          url: BASE_URL + url,
          filePath: currentFile,
          name: "file",
          formData,
          header,
          success: (res) => {
            const result = JSON.parse(res.data);
            console.log("成功1,", result, res);
            try {
              if (result.code === 200 && result.data?.fileUrlList[0].url) {
                uploadResults.push({
                  index,
                  // file: currentFile,
                  url: result.data.fileUrlList[0].url,
                  name: result.data.fileUrlList[0].name,
                  success: true,
                  error: null,
                });
              } else {
                uploadResults.push({
                  index,
                  file: currentFile,
                  url: null,
                  success: false,
                  error: new Error(result.msg || "文件上传失败"),
                });
              }
              // 上传下一个文件（递归）
              resolve(uploadNext(index + 1));
            } catch (e) {
              uploadResults.push({
                index,
                file: currentFile,
                url: null,
                success: false,
                error: new Error("解析失败：" + e.message),
              });
              resolve(uploadNext(index + 1));
            }
          },
          fail: (err) => {
            uploadResults.push({
              index,
              file: currentFile,
              url: null,
              success: false,
              error: new Error("请求失败：" + err.errMsg),
            });
            resolve(uploadNext(index + 1)); // 即使失败，也继续传下一个（可按需修改）
          },
        });
      });
    };

    // 从第 0 个文件开始上传
    return uploadNext(0);
  }
};

// form表单
export {
  BASE_URL,
  BASE_URL_IMG,
  request,
  Upload,
  UploadFile,
  uploadMultipleFiles,
};
