import { APPID, SOURCE_KEY } from '@/constants.js';
import CacheTool from '@/utils/cache-tool.js';
import log from './log.js';
import { getUTMSource } from '@/utils/utils.js';
import uni from './uniHooks';

const CONTENT_TYPE_ARRAY = {
  json: 'application/json',
  form: 'application/x-www-form-urlencoded',
};

function getHeaders(config = {}) {
  const { contentType = 'json' } = config;
  const ct = CONTENT_TYPE_ARRAY[contentType];
  let header = {
    appId: uni.getStorageSync('appId'),
    'Content-Type': ct,
  };
  const token = getToken();
  if (token) {
    header['Authorization'] = `Bearer ${token}`;
  }

  const groupId = uni.getStorageSync('groupId');
  const mallId = uni.getStorageSync('mallId');
  if (groupId) {
    header['brandId'] = groupId;
  }
  if (mallId) {
    header['lbsId'] = mallId;
  }
  const sourceObj = getUTMSource();
  return Object.assign(header, sourceObj);
}

function handleConfig(config = {}) {
  const header = getHeaders(config);
  const noToken = config.noToken;
  if (noToken) {
    delete header.Authorization;
  }
  return { header, ...config };
}

function getToken() {
  const token = uni.getStorageSync('kipAccessToken');
  // if (!token || token?.trim() == '' || token == 'null' || token == 'undefined') {
  if (!token || token == 'null' || token == 'undefined') {
    return false;
  }
  return token;
}

function getUrl(path) {
  // console.log(555555555, path);
  // 如果是dev、qa、prod环境
  if (window.ininjectConfig) {
    if (path.indexOf(`/${window.profileApi}`) > -1) {
      return `${window.profileApi}${path}`;
    }
    if (/weixinApi/g.test(path)) {
      return path;
    }
    if (/\/qaPayment/g.test(path)) {
      return `${window.ininjectConfig.qaPayment}${path.replace(
        /\/qaPayment/g,
        ''
      )}`;
    }
  }
  // 本地开发环境
  // path.indexOf('http') > -1 &&
  if (path.indexOf(`/${window.profileApi}`) > -1 || path) {
    return path;
  } else if (/\/qaPayment/g.test(path)) {
    // 支付
    return `https://qa-payment.kerryonvip.com${path}`;
  } else {
    return CacheTool.getCurEnvConst('KIP_API') + path;
  }
}

function cleanCacheAndGoLogin() {
  // 删除token以及会员数据
  uni.removeStorageSync('kipAccessToken');
  uni.removeStorageSync('isNewUser');
  uni.removeStorageSync('kipRefreshToken');
  // 直接跳转到登录页面
  uni.removeStorageSync('member');
  uni.removeStorageSync('wxMember');
  uni.removeStorageSync('openId');
  uni.removeStorageSync('userInfo');
  uni.reLaunch({
    url: '/pages/automatic/automaticMy.vue',
  });
}

function handleKipResponse(resp, request) {
  if (resp && resp.data) {
    const { status } = resp;
    console.log(`kip request resp => errMsg ${status}`);
    const { path } = request.detail;
    let isLogout = false;
    if (path.indexOf('/logout') > -1) {
      isLogout = true;
    }
    if (!resp || !resp.data) {
      return resp;
    }
    const result = resp.data;
    if (result) {
      const { message, code } = result || {};
      console.log(`kip api resul => message: ${message} code: ${code}`);
      if (result.code == '300000' && !isLogout) {
        console.warn('===> kip的access_token已过期');
        log.info(`kip的access_token已过期`, result);
      }
    }
  }
  return resp.data;
}

export default {
  detail: null,
  base(method, path, param = {}, config) {
    const _this = this;
    _this.detail = {
      method,
      path,
      param,
      config,
    };
    return new Promise((resolve, reject) => {
      const url =
        path.indexOf('http') > -1 ? path : `${window.profileApi}${path}`;
      const { header } = handleConfig(config);
      log.info(`===>request-kip url: ${url}`);
      log.info(`===>request-kip header: ${JSON.stringify(header)}`);
      uni
        .request({
          header: header,
          method: method,
          url: url,
          data: param,
        })
        .then((res) => {
          log.info(`===>request-kip response: ${JSON.stringify(res.data)}`);
          resolve(handleKipResponse(res, _this));
          if (res.status == 581) {
            uni.navigateTo({
              url: '/pages/errorPage/errorLimit?msg=当前访问太火爆了，稍后试试吧~',
            });
          }
        })
        .catch((response) => {
          log.error(`===>request-kip error: ${JSON.stringify(response)}`);
          reject(response);
        });
    });
  },
  get(path, param = {}, config) {
    return this.base('GET', path, param, config);
  },
  post(path, param = {}, config) {
    return this.base('POST', path, param, config);
  },
  put(path, param = {}, config) {
    return this.base('PUT', path, param, config);
  },
  delete(path, param = {}, config) {
    return this.base('DELETE', path, param, config);
  },
  uploadFile(path, param = {}, config) {
    const _this = this;
    _this.detail = {
      method: 'POST',
      path,
      param,
      config,
    };
    return new Promise((resolve, reject) => {
      const url = getUrl(path);
      const { fileType, file, formData } = param;
      let header = getHeaders(config);
      header['Content-Type'] = 'multipart/form-data';
      uni
        .uploadFile({
          header: header,
          method: 'POST',
          url: url,
          name: 'file',
          fileType: fileType,
          filePath: file.path,
          file: file,
          formData: formData,
        })
        .then((res) => {
          resolve(handleKipResponse(res[1], _this));
        })
        .catch((response) => {
          reject(response);
        });
    });
  },
  refreshToken(path) {
    return new Promise((resolve, reject) => {
      const url = getUrl(path);
      const header = getHeaders();
      delete header.Authorization;
      uni
        .request({
          header: header,
          method: 'POST',
          url: url,
        })
        .then((res) => {
          resolve(res[1]);
        })
        .catch((response) => {
          reject(response);
        });
    });
  },
};
