import apiMapper from "../apiMapper/index.js";
// AMMS--正式环境
// const ipConfig = 'https://amms.hnatechnic.com/'
// const ipPrefix = 'https://amms.hnatechnic.com'
// AMMS--灾备环境
// const ipConfig = 'http://10.52.28.110:80/'
// const ipPrefix = 'http://10.52.28.110:80'
// const urlPrefix = ''

// AMMS--本地代理测试环境
const ipConfig = "http://10.127.12.11:8080/";
const ipPrefix = "http://10.127.12.11:8080";
// 北数新地址测试
// const ipConfig = 'http://10.70.74.191:80/'
// const ipPrefix = 'http://10.70.74.191:80'

let urlPrefix = "";
// #ifdef H5
urlPrefix =
  location.href.indexOf("localhost") > -1
    ? ""
    : uni.getStorageSync("urlPrefix");
// #endif
// #ifdef APP-PLUS
urlPrefix = uni.getStorageSync("urlPrefix")
  ? uni.getStorageSync("urlPrefix")
  : ipPrefix;
// #endif

// 网上考试--测试环境
const unlapi = "http://10.122.16.153/backend";
// 网上考试--生产环境
// const unlapi = 'http://train.hnatechnic.com/backend'

// 工卡电签--测试环境
const mesUrlPrefix = "http://10.52.21.60:10066/papi";
// 工卡电签--正式环境
// const mesUrlPrefix = 'http://mes.hnatechnic.com/papi'

// 参数说明：pathAlias-接口的映射集合的key，data-发送的参数数据
// 处理参数挂url中请求的情况
let handleParam = (path, param) => {
  let pathArr = path.split("/");
  let newPath = pathArr.map((ele) => {
    if (ele.indexOf("{") !== -1 || ele.indexOf("}") !== -1) {
      let str = ele.split("{")[1].split("}")[0];
      return param[str];
    } else {
      return ele;
    }
  });
  return {
    url: newPath.join("/"),
    data: {},
  };
};
// token刷新重登陆
let refreshToken = async (resolve, reject, method, url, data) => {
  // return
  let postData = {
    grant_type: "refresh_token",
    scope: "server",
    refresh_token: uni.getStorageSync("refresh_token"),
  };
  loginRequest({
    method: "GET",
    url: "auth-login",
    data: postData,
  })
    .then((res) => {
      uni.setStorageSync("access_token", res.data.access_token);
      uni.setStorageSync("refresh_token", res.data.refresh_token);
      uni.setStorageSync("license", res.data.license);
      uni.getStorageSync("loginDate", new Date().getTime());
      request({
        method: method,
        url: url,
        data: data,
      })
        .then((res2) => {
          resolve(res2);
        })
        .catch((err) => {
          reject(err);
        });
    })
    .catch((err) => {
      reject(err);
      uni.redirectTo({
        url: "/pages/login/index",
      });
    });
};

let request = (options, isHandleParm, isQueryString) => {
  // let request = (options, isQueryString, isHandleParm) => {
  return new Promise(function (resolve, reject) {
    // 配置header信息
    let headerObj = {};

    if (isQueryString) {
      // 对于 POST 方法且 header['content-type'] 为 application/x-www-form-urlencoded 的数据，会将数据转换为 query string。
      headerObj = {
        "content-type": "application/x-www-form-urlencoded",
      };
    }
    let pathObj = null;
    if (isHandleParm) {
      pathObj = handleParam(apiMapper[options.url], options.data);
    }
    if (options.url === "cas-login") {
      headerObj["TENANT-ID"] = "1";
      headerObj["Authorization"] = "Basic YXBwOmVraW5n";
    } else if (options.url === "auth-login") {
      headerObj["Authorization"] = "Basic YXBwOmVraW5n";
    } else if (uni.getStorageSync("access_token")) {
      headerObj["Authorization"] =
        "Bearer" + uni.getStorageSync("access_token");
    }

    if (
      !uni.getStorageSync("access_token") &&
      ["cas-login", "auth-login"].indexOf(options.url) === -1
    ) {
      // 若存在window对象，则可以判断当前为使用H5的方式打开，记录下跳转前的页面地址
      if (typeof window != "undefined") {
        let _redirectUrl = location.hash.split("#")[1];
        if (_redirectUrl.indexOf("/login") == -1) {
          uni.setStorageSync("preUrl", _redirectUrl);
        }
      }
      setTimeout(() => {
        uni.navigateTo(
          {
            url: "/pages/login/index",
          },
          200
        );
      });
    } else {
      uni.request({
        timeout: 25000,
        header: headerObj,
        method: options.method,
        sslVerify: false,
        url:
          pathObj === null
            ? `${urlPrefix}${apiMapper[options.url]}`
            : `${urlPrefix}${pathObj.url}`,
        data: pathObj === null ? options.data : pathObj.data,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else if (res.statusCode == 401) {
            let url =
              pathObj === null
                ? `${urlPrefix}${apiMapper[options.url]}`
                : `${urlPrefix}${pathObj.url}`;
            let data = pathObj === null ? options.data : pathObj.data;
            refreshToken(resolve, reject, options.method, url, data);
          } else {
            uni.showToast({
              title:
                typeof res.data.msg == "undefined"
                  ? "系统繁忙，请稍后重试"
                  : res.data.msg,
              icon: "none",
            });
            reject(res);
          }
        },
        fail: (err) => {
          uni.showToast({
            title: err.errMsg || "系统繁忙，请稍后重试",
            icon: "none",
          });
          uni.hideLoading();
          // token过期时则用refresh_token自动刷新
          if (
            typeof err.response !== "undefined" &&
            err.response.status === 401
          ) {
            let url =
              pathObj === null
                ? `${urlPrefix}${apiMapper[options.url]}`
                : `${urlPrefix}${pathObj.url}`;
            let data = pathObj === null ? options.data : pathObj.data;
            refreshToken(resolve, reject, options.method, url, data);
          } else if (typeof err.response == "undefined") {
            uni.showToast({
              title: "服务超时，请稍后重试",
              icon: "none",
            });
            reject(err);
          } else {
            uni.showToast({
              title: "系统繁忙，请稍后重试",
              icon: "none",
            });
            reject(err);
          }
        },
      });
    }
  });
};

let requestWithFile = (options, isHandleParm, isQueryString) => {
  return new Promise(function (resolve, reject) {
    // 配置header信息
    let headerObj = {};
    if (isQueryString) {
      // 对于 POST 方法且 header['content-type'] 为 application/x-www-form-urlencoded 的数据，会将数据转换为 query string。
      headerObj = {
        "content-type": "multipart/form-data",
      };
    }
    let pathObj = null;
    if (isHandleParm) {
      pathObj = handleParam(apiMapper[options.url], options.data);
    }
    if (options.url === "cas-login") {
      headerObj["TENANT-ID"] = "1";
      headerObj["Authorization"] = "Basic YXBwOmVraW5n";
    } else if (options.url === "auth-login") {
      headerObj["Authorization"] = "Basic YXBwOmVraW5n";
    } else if (uni.getStorageSync("access_token")) {
      headerObj["Authorization"] =
        "Bearer" + uni.getStorageSync("access_token");
    }
    // let loginDate = uni.getStorageSync('loginDate') || 0
    // let refreshTime = new Date().getTime()
    if (
      !uni.getStorageSync("access_token") &&
      ["cas-login", "auth-login"].indexOf(options.url) === -1
    ) {
      // 若存在window对象，则可以判断当前为使用H5的方式打开，记录下跳转前的页面地址
      if (typeof window != "undefined") {
        let _redirectUrl = location.hash.split("#")[1];
        if (_redirectUrl.indexOf("/login") == -1) {
          uni.setStorageSync("preUrl", _redirectUrl);
        }
      }
      setTimeout(() => {
        uni.navigateTo(
          {
            url: "/pages/login/index",
          },
          200
        );
      });
      // } else if ((refreshTime - Number(loginDate)) > (12 * 60 * 60 * 1000)) {
      //     // refresh-token刷新
      //     let url = pathObj === null ? `${urlPrefix}${apiMapper[options.url]}` : `${urlPrefix}${pathObj.url}`
      //     let data = pathObj === null ? options.data : pathObj.data
      //     refreshToken(resolve, reject, options.method, url, data)
    } else {
      uni.uploadFile({
        timeout: 20000,
        header: headerObj,
        method: options.method,
        sslVerify: false,
        url:
          pathObj === null
            ? `${urlPrefix}${apiMapper[options.url]}`
            : `${urlPrefix}${pathObj.url}`,
        // url: 'https://amms.hnatechnic.com/test.jpg',
        formData: pathObj === null ? options.data : pathObj.data,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else if (res.statusCode == 401) {
            let url =
              pathObj === null
                ? `${urlPrefix}${apiMapper[options.url]}`
                : `${urlPrefix}${pathObj.url}`;
            let data = pathObj === null ? options.data : pathObj.data;
            refreshToken(resolve, reject, options.method, url, data);
          } else {
            reject(res);
          }
        },
        fail: (err) => {
          uni.showToast({
            title: err.errMsg,
            icon: "none",
          });
          uni.hideLoading();
          // token过期时则用refresh_token自动刷新
          if (
            typeof err.response !== "undefined" &&
            err.response.status === 401
          ) {
            let url =
              pathObj === null
                ? `${urlPrefix}${apiMapper[options.url]}`
                : `${urlPrefix}${pathObj.url}`;
            let data = pathObj === null ? options.data : pathObj.data;
            refreshToken(resolve, reject, options.method, url, data);
          } else if (typeof err.response == "undefined") {
            uni.showToast({
              title: "服务超时，请稍后重试",
              icon: "none",
            });
            reject(err);
          } else {
            uni.showToast({
              title: "系统繁忙，请稍后重试",
              icon: "none",
            });
            reject(err);
          }
        },
      });
    }
  });
};

let loginRequest = (options, isHandleParm, isQueryString) => {
  return new Promise(function (resolve, reject) {
    // 配置header信息
    let headerObj = {};
    if (isQueryString) {
      // 对于 POST 方法且 header['content-type'] 为 application/x-www-form-urlencoded 的数据，会将数据转换为 query string。
      headerObj = {
        "content-type": "application/x-www-form-urlencoded",
      };
    }
    // uni.setStorageSync('access_token', '84a619af-d110-4948-a657-a3439f51f216')
    if (options.url === "cas-login") {
      headerObj["TENANT-ID"] = "1";
      headerObj["Authorization"] = "Basic YXBwOmVraW5n";
    } else if (options.url === "auth-login") {
      headerObj["Authorization"] = "Basic YXBwOmVraW5n";
    } else if (uni.getStorageSync("access_token")) {
      headerObj["Authorization"] =
        "Bearer" + uni.getStorageSync("access_token");
    }
    let pathObj = null;
    if (isHandleParm) {
      pathObj = handleParam(apiMapper[options.url], options.data);
    }

    uni.request({
      timeout: 20000,
      header: headerObj,
      method: options.method,
      sslVerify: false,
      url:
        pathObj === null
          ? `${urlPrefix}${apiMapper[options.url]}`
          : `${urlPrefix}${pathObj.url}`,
      // url: 'https://amms.hnatechnic.com/test.jpg',
      data: pathObj === null ? options.data : pathObj.data,
      success: (res) => {
        // console.log(res)
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode == 401) {
          let url =
            pathObj === null
              ? `${urlPrefix}${apiMapper[options.url]}`
              : `${urlPrefix}${pathObj.url}`;
          let data = pathObj === null ? options.data : pathObj.data;
          refreshToken(resolve, reject, options.method, url, data);
        } else {
          reject(res);
        }
      },
      fail: (err) => {
        console.log(err);
        uni.showToast({
          title: err.errMsg,
          icon: "none",
        });
        // token过期时则用refresh_token自动刷新
        if (
          typeof err.response !== "undefined" &&
          err.response.status === 401
        ) {
          let url =
            pathObj === null
              ? `${urlPrefix}${apiMapper[options.url]}`
              : `${urlPrefix}${pathObj.url}`;
          let data = pathObj === null ? options.data : pathObj.data;
          refreshToken(resolve, reject, options.method, url, data);
        } else {
          reject(err);
        }
      },
    });
  });
};

let requestUploadFile = (options) => {
  return new Promise(function (resolve, reject) {
    // 配置header信息
    let headerObj = {};
    if (options.url === "auth-login") {
      headerObj["TENANT-ID"] = "1";
      headerObj["Authorization"] = "Basic YXBwOmVraW5n";
    } else if (options.url === "cas-login") {
      headerObj["Authorization"] = "Basic YXBwOmVraW5n";
    } else if (uni.getStorageSync("access_token")) {
      headerObj["Authorization"] =
        "Bearer" + uni.getStorageSync("access_token");
    }
    // let loginDate = uni.getStorageSync('loginDate') || 0
    // let refreshTime = new Date().getTime()
    let _url = apiMapper[options.url](options.path);
    let url = `${urlPrefix}${_url}`;
    if (
      !uni.getStorageSync("access_token") &&
      ["cas-login", "auth-login"].indexOf(options.url) === -1
    ) {
      // 若存在window对象，则可以判断当前为使用H5的方式打开，记录下跳转前的页面地址
      if (typeof window != "undefined") {
        let _redirectUrl = location.hash.split("#")[1];
        if (_redirectUrl.indexOf("/login") == -1) {
          uni.setStorageSync("preUrl", _redirectUrl);
        }
      }
      setTimeout(() => {
        uni.navigateTo(
          {
            url: "/pages/login/index",
          },
          200
        );
      });
      // } else if ((refreshTime - Number(loginDate)) > (12 * 60 * 60 * 1000)) {
      //     let url = pathObj === null ? `${urlPrefix}${apiMapper[options.url]}` : `${urlPrefix}${pathObj.url}`
      //     let data = pathObj === null ? options.data : pathObj.data
      //     refreshToken(resolve, reject, options.method, url, data)
    } else {
      uni.uploadFile({
        url: url,
        filePath: options.src,
        timeout: 20000,
        name: "file",
        header: headerObj,
        // formData: {
        // 	appId: 'test1',
        // 	bucketName: 'test1'
        // },
        success: (res) => {
          // console.log(res)
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            uni.showToast({
              title: "系统繁忙，请稍后重试",
              icon: "none",
            });
            uni.hideLoading();
            reject(res);
          }
        },
        fail: function (res) {
          console.log("fail to upload image:" + res);
          reject("fail to upload image:" + remoteUrlIndex);
        },
      });
    }
  });
};

/**
 * 获取下载图片地址
 * @param {Object} options 传参
 */
function getDownPicUrl(filePath) {
  const tempUrl = "diskDownload";
  // ?appId=test1&bucketName=test1&ids=a31b3569b5f8c9c36adf5ac00df9ee99'
  let url = `${urlPrefix}${apiMapper[tempUrl]}?filePath=${filePath}`;
  return url;
}

const requestahm = ({ url, data = {}, method, isShowLoading = false }) => {
  const dataObj = {
    ...data,
  };
  return new Promise((resolve, reject) => {
    //获取最新sessid
    //uni.setStorageSync('ahmjsessionid', '89898')

    // 配置header信息
    let headerObj = {};
    headerObj["Authorization"] = "Bearer" + uni.getStorageSync("access_token");
    let ahmjsessionid = uni.getStorageSync("ahmjsessionid");
    dataObj.ahmjsessionid = ahmjsessionid;
    let Strurl = "/mroapi/ahm";
    //let Strurl = ''
    //获取登录用户名
    let userName = uni.getStorageSync("username");
    uni.request({
      timeout: 300000,
      header: headerObj,
      url: urlPrefix + Strurl + url,
      //url: Strurl+ url, //本地测试
      data: dataObj,

      method: method,
      success(res) {
        //请求返回1000重新登录接口
        if (res.data.code == 1000) {
          //console.log('dataObj---3---',url)
          //获取登录用户目前先用这个测试
          const userData = {
            userName: userName,
          };
          uni.request({
            timeout: 300000,
            header: headerObj,
            url: urlPrefix + Strurl + "/rbac/rbacUser/app/login",
            //url: Strurl+'/rbac/rbacUser/app/login',
            data: userData,
            method: "GET",
            success(res) {
              if (res.data.code == 200) {
                let ahmjsessionids = res.data.data.JSESSIONID;
                uni.setStorageSync("ahmjsessionid", ahmjsessionids);
                dataObj.ahmjsessionid = ahmjsessionids;
                uni.request({
                  timeout: 300000,
                  header: headerObj,
                  url: urlPrefix + Strurl + url,
                  //url: Strurl+url,
                  data: dataObj,
                  method: method,
                  success(res) {
                    if (res.data.code == 200) {
                      if (res.data === -1) return reject(res.data);
                      resolve(res.data);
                    } else {
                      uni.showToast({
                        title: "ahm系统异常联系管理员2",
                        icon: "none",
                      });
                    }
                  },
                });
              } else {
                uni.showToast({
                  title: "ahm系统异常联系管理员1",
                  icon: "none",
                });
              }
            },
          });
        } else {
          if (res.data === -1) return reject(res.data);

          resolve(res.data);
        }
      },
      fail(res) {
        uni.showToast({
          title: "ahm系统维护中",
          icon: "none",
        });
        reject(res.data);
      },
    });
  });
};

const requestahmlogin = ({ url, data = {}, method, isShowLoading = false }) => {
  const dataObj = {
    ...data,
  };
  return new Promise((resolve, reject) => {
    // 配置header信息
    let headerObj = {};
    headerObj["Authorization"] = "Bearer" + uni.getStorageSync("access_token");
    // let ahmjsessionid = uni.getStorageSync('ahmjsessionid')
    // dataObj.ahmjsessionid = ahmjsessionid
    let Strurl = "/mroapi/ahm";
    //let Strurl = ''
    uni.request({
      timeout: 300000,
      header: headerObj,
      url: urlPrefix + Strurl + url,
      //url: Strurl+ url, //本地测试
      data: dataObj,

      method: method,
      success(res) {
        //请求返回1000重新登录接口
        if (res.data.code == 200) {
          let ahmjsessionids = res.data.data.JSESSIONID;
          uni.setStorageSync("ahmjsessionid", ahmjsessionids);
          if (res.data === -1) return reject(res.data);
          resolve(res.data);
        } else {
          if (res.data === -1) return reject(res.data);
          resolve(res.data);
        }
      },
      fail(res) {
        uni.showToast({
          title: "ahmlogin系统维护中",
          icon: "none",
        });
        reject(res.data);
      },
    });
  });
};
// 外链请求方法
let requestOutUrl = (options, isHandleParm, isQueryString) => {
  // let request = (options, isQueryString, isHandleParm) => {
  return new Promise(function (resolve, reject) {
    // 配置header信息
    let headerObj = {};

    if (isQueryString) {
      // 对于 POST 方法且 header['content-type'] 为 application/x-www-form-urlencoded 的数据，会将数据转换为 query string。
      headerObj = {
        "content-type": "application/x-www-form-urlencoded",
      };
    }

    uni.request({
      timeout: 30000,
      header: headerObj,
      method: options.method,
      sslVerify: false,
      url: apiMapper[options.url],
      // url: 'https://amms.hnatechnic.com/test.jpg',
      data: options.data,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          uni.showToast({
            title: res.data.msg || "系统繁忙，请稍后重试",
            icon: "none",
          });
          reject(res);
        }
      },
      fail: (err) => {
        uni.showToast({
          title: err.errMsg,
          icon: "none",
        });
        uni.hideLoading();
        // token过期时则用refresh_token自动刷新
        if (typeof err.response == "undefined") {
          uni.showToast({
            title: "服务超时，请稍后重试",
            icon: "none",
          });
          reject(err);
        } else {
          uni.showToast({
            title: "系统繁忙，请稍后重试",
            icon: "none",
          });
          reject(err);
        }
      },
    });
  });
};
let request123 = ({ url, data = {}, method, isShowLoading = false }) => {
  const dataObj = {
    ...data,
  };
  return new Promise((resolve, reject) => {
    let apptoken = uni.getStorageSync("apptoken");
    // let apptoken='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODU2MjQzMjYsInVzZXJuYW1lIjoieW9uZ3NoZW5nX3poYW8ifQ.qw16G2uQ338XtXXe9ZEEnLDMRYclc6bcJKY6wa6lLiM'
    let lasturl = unlapi + url;
    uni.request({
      url: lasturl,
      data: dataObj,
      header: {
        "X-Access-Token": apptoken,
      },
      //
      method: method,
      success(res) {
        if (res.statusCode == 200) {
          if (res.data === -1) return reject(res.data);
          resolve(res.data);
        } else {
          uni.showToast({
            title: "登录身份过期，请重新登录",
            icon: "none",
          });
          setTimeout(() => {
            uni.redirectTo({
              url: "/pages/login/index",
              success(res) {
                console.log("成功啦", res);
              },
              fail(err) {
                console.log("失败啦", err);
              },
            });
          }, 1500);
        }

        // if (res.data === -1) return reject(res.data)
        // resolve(res.data)
      },
      fail(res) {
        uni.showToast({
          title: "系统维护中",
          icon: "none",
        });
        reject(res.data);
      },
    });
  });
};

export {
  request,
  requestWithFile,
  loginRequest,
  requestUploadFile,
  getDownPicUrl,
  ipConfig,
  ipPrefix,
  urlPrefix,
  requestahm,
  requestahmlogin,
  requestOutUrl,
  request123,
  mesUrlPrefix,
};
