/*
 * @Author: ZhengXiaowei
 * @Date: 2019-10-15 12:06:28
 * @LastEditors: ZhengXiaowei
 * @LastEditTime: 2019-10-15 14:32:19
 * @Description: api 配置入口
 */
import fetch from "@system.fetch";
import Fly from "flyio/dist/npm/hap";
import apiConfig from "./config";
import prompt from '@system.prompt';
import storage from "@system.storage";
import { getToken, clearToken, getSendOrderId } from "./utils";
import it from "../helper/interface.js";
var fly = new Fly(fetch);
var qs = require('qs');
var appInfo = it.getAppInfo();
var provider = it.getProvider();
var appDev, sendOrderId;
var packages = apiConfig.package;
var requestTime = 0;


it.getAppDev((res) => {
  appDev = res;
})

getSendOrderId((id) => {
  sendOrderId = id;
})

fly.config.baseURL = apiConfig.baseURL;
fly.config.headers["Content-Type"] =
  "application/x-www-form-urlencoded;charset=utf-8";

const filterNoToken = ["/login", "/refreshToken"];

fly.interceptors.request.use(async config => {
  if (config.headers) {
    config.headers["X-Version"] = appInfo.versionName;
    config.headers["X-Brand"] = qs.stringify(appDev);
    config.headers["X-Package"] = packages;
    config.headers["X-CodeVersion"] = '1.0.2';
    config.headers["X-Provider"] = provider;
    if (sendOrderId) config.headers["send-order-id"] = sendOrderId;
  } else {
    if (sendOrderId) {
      config.headers = {  'X-Version': appInfo.versionName, 'X-Brand': qs.stringify(appDev), "X-Package": packages, 'send-order-id': sendOrderId };
    } else {
      config.headers = { 'X-Version': appInfo.versionName, 'X-Brand': qs.stringify(appDev), "X-Package": packages };
    }
  }
  
  // 过滤一些不需要登录的路由
  if (filterNoToken.indexOf(config.url) === -1) {
    let regId = (await storage.get({ key: "regId" })).data;
    let push_id = (await storage.get({ key: "push_id" })).data;
    let token = await getToken();
    config.headers.Authorization = token;
    config.headers["X-regId"] = regId;
    config.headers["X-pushId"] = push_id;

    if (config.method === "POST") {
      if (qs.stringify(config.body)) {
        config.body = qs.stringify(config.body) + '&package=' + packages;
      } else {
        config.body = 'package=' + packages
      }
    } else {
      config.body ? config.body.package = packages : config.body = { package: packages }
    }
    return config;
  } else {
    return config;
  }
});

fly.interceptors.response.use(
  async res => {
    if (!res.data.code) {
      return Promise.resolve(res.data.data);
    }if (res.data.code == 10029) {
      return Promise.resolve(res.data.data ? res.data.data : {});
    } else if (res.data.code === 10023 || res.data.code === 10001) {
      // token失效
      await clearToken();
      console.log("begin refresh token");
      let refresh_token = await getToken();
      console.log("refresh token:", refresh_token);
      return fly(res.config);

    } else if (res.data.code === 10028) {
      return false;
    } else {
      prompt.showToast({
        message: res.data.msg
      })
      // it.errBackTo();
      return Promise.reject(res);
    }
  },
  err => {
    console.log('err', err)
    return Promise.reject(err);
  }
);

export default fly;
