import { useMemberStore } from "@/store/modules/member";
import ENV_CONFIG from "../config/env";
import pinia from "@/store";

// 基础地址
let baseUrl = "";
// #ifdef H5
(process.env as any).config = ENV_CONFIG;
// #endif

const store = useMemberStore(pinia);
baseUrl = (process.env as any).config[(process.env as any).NODE_ENV]
  .VITE_APP_BASE_URL;

const obj = {
  // 拦截前触发
  invoke(options: UniApp.RequestOptions) {
    // 超时时间
    options.timeout = 10000;
    // 拼接完整路径
    if (!options.url.startsWith("http")) {
      if (options.url.indexOf("/prod/gateway/api/db/getDbInfo") === -1) {
        options.url = baseUrl + store.profile.childPath + options.url;
      } else {
        options.url = baseUrl + options.url;
      }
    }
    // 请求头标识
    // 1.小程序唯一标识
    // 'source-client': 'miniapp'
    options.header = { ...options.header };
    options.header["source-client"] = "miniapp";
    // 2.注入token
    // 2.1 获取token
    const token = store.profile?.token;
    if (token) {
      options.header["x-userToken"] = token;
    }
  },
};
// 请求拦截器
uni.addInterceptor("request", obj);
uni.addInterceptor("uploadFile", obj);

interface Data<T> {
  code: string | number;
  data: T;
  msg: string;
  result: T;
  message: string;
}
// 响应拦截器
/***
 * 1001: 未登录
 * 1002: 登陆过期
 */
export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    if ((options as any).header?.type === "UPLOAD") {
      // 压缩图片
      uni.compressImage({
        src: (options as any).data.path,
        quality: 80, // 压缩质量
        success: (compressRes) => {
          const compressedTempFilePath = compressRes.tempFilePath;
          uni.uploadFile({
            header: {
              "x-userToken": store.profile?.token,
              // #ifdef H5
              "Content-Type": "multipart/form-data",
              // #endif
            },
            timeout: 1800000,
            url: baseUrl + store.profile.childPath + options.url,//仅为示例,非真实的接口地址
            fileType: "image",
            // #ifdef H5
            files: (options as any).data.files,
            // #endif
            // #ifdef MP-WEIXIN
            filePath: compressedTempFilePath,
            // #endif
            name: "file",
            formData: {
              file: (options as any).data.files,
            }, // HTTP 请求中其他额外的 form data
            success: (res) => {
              resolve(JSON.parse(res.data) as Data<T>);
            },
            fail(err) {
              console.log("上传失败了", err);
              resolve(err as any);
            },
          });

          // 上传图片
          // uni.uploadFile({
          //   url: 'https://your-api-upload-endpoint.com/upload', // 你的上传接口
          //   filePath: compressedTempFilePath,
          //   name: 'file',
          //   formData: {
          //     'user': 'test'
          //   },
          //   success: (uploadFileRes) => {
          //     console.log('upload success:', uploadFileRes);
          //   },
          //   fail: (uploadFileErr) => {
          //     console.error('upload fail:', uploadFileErr);
          //   }
          // });
        },
        fail: (compressErr) => {
          console.error("compress fail:", compressErr);
        },
      });

      // uni.uploadFile({
      //   header: {
      //     "x-userToken": store.profile?.token,
      //     // #ifdef H5
      //     "Content-Type": "multipart/form-data",
      //     // #endif
      //   },
      //   timeout: 1800000,
      //   url: baseUrl + store.profile.childPath + options.url,//仅为示例,非真实的接口地址
      //   fileType: "image",
      //   // #ifdef H5
      //   files: (options as any).data.files,
      //   // #endif
      //   // #ifdef MP-WEIXIN
      //   filePath: (options as any).data.path,
      //   // #endif
      //   name: "file",
      //   formData: {
      //     file: (options as any).data.files,
      //   }, // HTTP 请求中其他额外的 form data
      //   success: (res) => {
      //     resolve(JSON.parse(res.data) as Data<T>);
      //   },
      //   fail(err) {
      //     console.log("上传失败了", err);
      //     resolve(err as any);
      //   },
      // });
    } else {
      uni.request({
        ...options,
        dataType: "string", //1.先将dataType设置为string
        success(res) {
          var json = (res.data as any).replace(
            /:s*([0-9]{15,})s*(,?)/g,
            ': "$1" $2'
          );
          //2.根据后端返回的数据调用一次或者两次replace替换
          var json1 = json.replace(/:s*([0-9]{15,})s*(,?)/g, ': "$1" $2');
          //3.手动转换回json数据即可
          let res1: any = JSON.parse(json1);
          console.log(res1);
          if (res.statusCode >= 200 && res.statusCode < 300) {
            if (
              [1001,1002,1003,1004].indexOf(res1.code) > -1
            ) {
              uni.showToast({
                icon: "none",
                title: (res1 as Data<T>).message || "请求失败",
              });
              store.clearProfile();
              uni.reLaunch({
                url: "/pagesLogin/login/index",
              });
              return;
            } else if ([500,5001,10001].indexOf(res1.code) > -1) {
              uni.showToast({
                icon: "none",
                title: (res1 as Data<T>).message || "请求失败",
              });
              return;
            }
            resolve(res1 as Data<T>);
          } else {
            uni.showToast({
              icon: "none",
              title: (res1 as any).msg || "请求失败",
            });
            reject(res1);
          }
        },
        fail(err) {
          uni.showToast({
            icon: "none",
            // title: JSON.stringify(err),
            title: "网络错误,请检查网络",
          });
          reject(err);
        },
      });
    }
  });
};