import {
  go,
  back,
  showModal,
  setStorageSync,
  getStorageSync,
  loading,
} from "./traoAPI";
import { WCUserLogin } from "./Interface";
import Taro from "@tarojs/taro";
import formdata from "./wxFormdata/formData";

import store from "../store";
import { tokenRefresh } from "../store/features/userInfo";

const global = store.getState().globalStore;
const global_requestUrlList = []; // 全局：正在请求的url地址，防止多次点击

// api调用失败重试次数
let api_retry_count = 0;

export const Ajax = (params) => {
  const app = Taro.getApp();
  const domain = global.domain;
  // Taro.showLoading({
  //   title: "请求中...",
  //   mask: true,
  // });

  const whiteListLoading = [""]; // loading

  // 防止多次点击
  const requestUrlList = global_requestUrlList;
  const whiteList = []; // 白名单:不自动重新请求
  if (
    requestUrlList.indexOf(params.url) > -1 &&
    whiteList.indexOf(params.url) < 0
  ) {
    return;
  } else {
    requestUrlList.push(params.url);
  }
  return new Promise((reslove, reject) => {
    let token = getStorageSync("token");
    Taro.request({
      url: domain + params.url,
      method: params.method || "GET",
      header: {
        Authorization: "Bearer " + token,
        ...params.header,
      },
      data: params.data,
      success(res) {
        console.log("res", res);
        if (res.data.code == 401 || res.data.code == 403) {
          // 自动重新登录
          Taro.removeStorageSync("token");
          loginReload(params);

          return;
        }
        if (res.statusCode !== 200) {
          Taro.showModal({
            title: "提示",
            content: String("错误码：" + res.statusCode),
            showCancel: false,
          });
          return false;
        }

        if (res.data.code === 500) {
          let msg =
            typeof res.data.msg == "string"
              ? res.data.msg
              : "系统异常，请联系管理人员";
          if (msg == "请不要操作太快哦") {
            reject(res);
            return false;
          }

          Taro.showModal({
            title: "提示",
            content: String(res.data.msg),
            showCancel: false,
          });
          // reject(res);
          return false;
        }

        if (requestUrlList.length > 0) {
          requestUrlList.splice(requestUrlList.indexOf(params.url), 1);
        }
        reslove(res);
      },
      fail(err) {
        console.log(err);
        go("/pages/errorpage/errorpage");
        // Taro.showModal({
        //   title: "提示",
        //   content: "请检查网络是否连接",
        //   showCancel: false,
        // });
      },
      complete() {
        if (requestUrlList.length === 0) {
          Taro.hideLoading();
        }

        // const requestUrlList = global_requestUrlList;
        // const newRequestUrlList = requestUrlList.splice(
        //   requestUrlList.indexOf(params.url),
        //   1
        // );
      },
    });
  });
};

export const AjaxUploadFile = (params, formData) => {
  const app = Taro.getApp();
  const domain = global.domain;
  Taro.showLoading({
    title: "请求中...",
    mask: true,
  });
  return new Promise((reslove, reject) => {
    let token = getStorageSync("token");
    Taro.uploadFile({
      filePath: params.filePath, // 上传文件地址
      name: params.name || "file", // 上传文件字段
      url: domain + params.url,
      formData: {
        ...formData,
      },
      header: {
        Authorization: "Bearer " + token,
        ...params.header,
      },
      success(res) {
        let o = JSON.parse(res.data);
        if (res.statusCode !== 200) {
          Taro.showModal({
            title: "提示",
            content: "上传出错",
            showCancel: false,
          });
          return false;
        }
        if (o.code !== 200) {
          let msg =
            typeof o.msg == "string" ? o.msg : "系统异常，请联系管理人员";
          Taro.showModal({
            title: "提示",
            content: msg,
            showCancel: false,
          });
          return false;
        }
        reslove(o);
      },
      fail() {
        go("/pages/errorpage/errorpage");
        // Taro.showModal({
        //   title: "提示",
        //   content: "请检查网络是否连接",
        //   showCancel: false,
        // });
      },
      complete() {
        Taro.hideLoading();
      },
    });
  });
};

export const AjaxFormData = (params) => {
  const app = Taro.getApp();
  const domain = global.domain;

  // 防止多次点击
  const requestUrlList = global_requestUrlList;
  const whiteList = ["/Api/MessageList"];
  if (
    requestUrlList.indexOf(params.url) > -1 &&
    whiteList.indexOf(params.url) < 0
  ) {
    return;
  } else {
    requestUrlList.push(params.url);
  }
  return new Promise((reslove, reject) => {
    let token = getStorageSync("token");
    Taro.request({
      url: domain + params.url,
      method: params.method || "GET",
      header: {
        Authorization: "Bearer " + token,
        ...params.header,
        "content-type": params.data.contentType,
      },
      data: params.data.buffer,
      success(res) {
        if (res.data.code == 401 || res.data.code == 403) {
          // 自动重新登录
          Taro.removeStorageSync("token");
          loginReload(params);

          return;
        }
        if (res.statusCode !== 200) {
          Taro.showModal({
            t2: String("错误码：" + res.statusCode),
            showCancel: false,
          });
          return false;
        }
        if (res.data.code !== 200) {
          let msg =
            typeof res.data.msg == "string"
              ? res.data.msg
              : "系统异常，请联系管理人员";
          if (msg == "请不要操作太快哦") {
            reject(res);
            return false;
          }
          const noTipsCodes = [5001, 5002, 5003];
          if (noTipsCodes.indexOf(res.data.code) == -1) {
            Taro.showModal({
              title: "提示",
              content: msg,
              showCancel: false,
            }).then(() => {
              reject(res);
              if (
                res.data.code == 401 ||
                res.data.code == 403 ||
                res.data.msg === "登录状态已过期"
              ) {
                // 自动重新登录
                Taro.removeStorageSync("token");
                loginReload(params);
                return;
              }
            });
          } else {
            reject(res);
          }
          return false;
        }
        reslove(res);
      },
      fail(err) {
        console.log(err);
        go("/pages/errorpage/errorpage");
        // Taro.showModal({
        //   title: "提示",
        //   content: "请检查网络是否连接",
        //   showCancel: false,
        // });
      },
      complete() {
        // Taro.hideLoading();
        const requestUrlList = global_requestUrlList;
        const newRequestUrlList = requestUrlList.splice(
          requestUrlList.indexOf(params.url),
          1
        );
      },
    });
  });
};

// 自动重新登录后，重新发起上一个请求
const AjaxReloadAPI = async (_params) => {
  if (api_retry_count === 0) {
    Ajax(_params);
  }
  if (api_retry_count < 3) {
    api_retry_count = api_retry_count + 1;
    Ajax(_params);
  } else {
    api_retry_count = 0; // 清空重新调用次数，
    Taro.showModal({
      title: "提示",
      content: "接口请求失败，请联系管理员",
      showCancel: false,
    }).then((res) => {});
  }
};

// 重新登陆后，发起上一个请求
const loginReload = async (_params) => {
  Taro.showLoading({
    title: "请求中...",
    mask: true,
  });
  const { code } = await Taro.login();
  const { data } = await Ajax({
    // url: "/wx/user/login",
    url: "/user/login?code=" + code,
    data: { code: code },
    method: "POST",
  });
  Taro.hideLoading();
  if (data.code === 200) {
    setStorageSync("isWelcome", true);
    setStorageSync("mobile", data.data.mobile);
    store.dispatch(tokenRefresh(data.data));

    Ajax(_params);
  } else {
    Taro.showModal({
      title: "提示",
      content: "登录已过期，请重新登录",
      showCancel: false,
    }).then((res) => {
      Taro.removeStorageSync("token");
      Taro.clearStorage(); // 清空所有缓存
      Taro.navigateTo({
        url: "/pages/initiate/initiate",
      });
    });
  }
};
