import ky, { Options } from "ky";
// 请求服务器地址
const API_DOMAIN = "http://test.com/api/";

export interface AppRequestConfig extends Options {
  url: string;
  encoding?: string;
  method?: string;
  data?: any;
  done?: () => void;
  success?: (data: any) => void;
  fail?: (msg: string) => void;
}

// API请求正常，数据正常
export const API_CODE = {
  // API请求正常
  OK: 200,
  // API请求正常，权限不足
  ERR_DATA: 403,
  // API请求正常，空数据
  ERR_NO_DATA: 301,
  // API请求正常，登录异常
  ERR_LOGOUT: 401,
};
// API请求异常报错内容
export const API_FAILED = "网络连接异常，请稍后再试";

// contentAPI请求汇总
export const apiReqs = {
  // 登录
  signIn: (config: AppRequestConfig) => {
    config.url = API_DOMAIN + "login";
    config.method = "post";
    sendRequestToBackground(config);
  },
  // 获取数据
  getData: (config: AppRequestConfig) => {
    config.url = API_DOMAIN + "getData";
    config.method = "get";
    sendRequestToBackground(config);
  },
};

/*
 * API请求封装（带验证信息）
 * config.this: [必填]组件作用域，用于页面跳转等逻辑
 * config.method: [必须]请求method
 * config.url: [必须]请求url
 * config.data: 请求数据
 * config.formData: 是否以formData格式提交（用于上传文件）
 * config.success(res): 请求成功回调
 * config.fail(err): 请求失败回调
 * config.done(): 请求结束回调
 * background 后台请求
 */
export function apiRequest<T>(config: AppRequestConfig): Promise<T> {
  const { encoding = "utf-8" } = config;
  // 如果没有设置config.data，则默认为{}
  if (config.data === undefined) {
    config.data = {};
  }

  // 如果没有设置config.method，则默认为get
  config.method = config.method || "get";

  // 放在请求头里的Access-Token，根据业务需求，可从localstorage里获取。演示代码暂为空。
  if (config.headers) {
    if (!(config.headers as any)["user-agent"]) {
      (config.headers as any)["user-agent"] =
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36";
    }
  } else {
    config.headers = {
      "user-agent":
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
    };
  }

  // 发起请求
  return ky(config.url, config).then((res) => {
    if (res.ok) {
      return res.blob().then((data) => {
        const reader = new FileReader();
        return new Promise((resolve, reject) => {
          reader.onload = () => {
            const text = reader.result;
            // 请求结束的回调
            config.done && config.done();
            // 请求成功的回调
            config.success && config.success(text);
            resolve(text as any);
          };
          reader.onerror = (e) => {
            reject(e);
          };
          reader.readAsText(data, encoding);
        });
      }) as Promise<T>;
    } else {
      // 请求结束的回调
      config.done && config.done();
      // 请求失败的回调
      config.fail && config.fail(API_FAILED);
      throw new Error(API_FAILED);
    }
  });
}

/**
 * content 请求
 * @param config
 */
export function sendRequestToBackground(config: AppRequestConfig) {
  if (window.chrome && window.chrome.runtime) {
    window.chrome &&
      window.chrome.runtime.sendMessage(
        {
          type: "apiRequest",
          data: config,
        },
        (result) => {
          config.done && config.done();
          if (result.status === 200) {
            config.success && config.success(result);
          } else {
            config.fail && config.fail(result);
          }
        }
      );
  } else {
    console.log("未找到chrome API");
  }
}
