import uni from '@/utils/uniHooks';
import { getUTMSource } from '@/utils/utils';
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import {md} from '@/utils/common'
// import { Message } from 'element-ui';
// import { jumpLogin } from '@/utils';
// import { Loading } from 'element-ui';
// import { ElLoadingComponent } from 'element-ui/types/loading';
// import vm from "@/main";
import { Toast } from 'vant';
// import vue from 'vue';
import store from '@/store';
// import { v4 as uuidv4 } from 'uuid';
// import { wxToLoginCallback } from '@/utils/index.js'
let loadingInstance = null;
let requestNum = 0;

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'),
    // appId: 'wx92c3e55fbef6b2af',
    // '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;
}

const addLoading = () => {
  // 增加loading 如果pending请求数量等于1，弹出loading, 防止重复弹出
  requestNum++;
  if (requestNum === 1) {
    // 展示加载中的状态
    loadingInstance = Toast.loading({
      message: '正在努力加载中....',
    });
  }
};

const cancelLoading = () => {
  // 取消loading 如果pending请求数量等于0，关闭loading
  requestNum--;
  if (requestNum === 0) loadingInstance?.clear();
};

function XUser(config) {
  let params = {
    userId: store.state?.kipUserId || '', // K+用户ID
    // userId: '2c9d85868652dee50186532bdbbb0001', // K+用户ID
    sourceType: 'WECHAT',
    // phoneNumber: '18521563898',
    phoneNumber: store.state?.mobile || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
    // projectId: store.state.projectId || '4028e3817c2b3f79017c2b48c54c0000', // 楼盘id
    projectId: store.state.projectId || '', // 楼盘id
    brandId: store.state.groupId,
    // cid: '8aaa809d835ba76d018378bc57180006',
    cid: store.state?.openid || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
    // vipCode: 'KERRY100213505',
    vipCode: store.state?.member?.vipcode || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
    // vipCode: 'KERRY100213853', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
    // lbsId: '8aaa82ea804d07cd0180516ff03b0008',
    lbsId: store.state?.lbsId || '',
  };
  // params = {"userId": "8aaa809d835ba76d018378bc57180006","sourceType": "WECHAT","phoneNumber": "18521563898","projectId": "paroject1","buildingId": "QHKC-P1","brandId":"8a84853b7c91ac5b017c962dab55030e","cid": "oIUfO5XAVleJ88z13i1_08DCKIhQ","vipCode":"KERRY100200040","lbsId":"8aaa81cb7c836c6b017c83e46b110001"}
  if (/orders-and-prepay|calculate-discount|unlicensed-car-check-in|unlicensed-car-checkout|paper-coupon/g.test(config.url)) {
    params.buildingId = window.localStorage.getItem('buildingId');
  }
  const newParams = {}
  Object.keys(params).forEach(key => {
    const value = params[key]
    if ( value ) {
      newParams[key] = value
    }
  })
  return JSON.stringify(newParams);
}
function getSign(config) {
  let params = {}
  if(config.method === 'get' && config?.params) {
    params = config.params
  }
  if(config.method === 'post' && config?.data) {
    params = config.data
  }
  const newHeader = md(params, true)
  return newHeader
}
export const createAxiosByinterceptors = (config) => {
  const instance = axios.create({
    timeout: 1000000, //超时配置
    baseURL: `${window.profileApi}/temporary-parking-service`,
    // baseURL: `https://dev-kip-service-internal.kerryonvip.com/temporary-parking-service`,
    withCredentials: false, //跨域携带cookie
    xhrFields: {
      withCredentials: false // 允许跨域携带cookie信息
    },
    ...config, // 自定义配置覆盖基本配置
  });
  // 添加请求拦截器
  instance.interceptors.request.use(
    function (config) {
      // 在发送请求之前做些什么
      const { loading = true } = config;
      if (loading) addLoading();
      // 设置 headers
      config.headers = {
        ...config.headers,
        ...handleConfig().header,
        // ...getSign(config),
        // 'x-conversation-id': uuidv4(),
        'X-User': XUser(config),
        'withCredentials': 'false'
      };
      return config;
    },
    function (error) {
      // 对请求错误做些什么
      return Promise.reject(error);
    }
  );

  // 添加响应拦截器
  instance.interceptors.response.use(
    function (response) {
      // 对响应数据做点什么
      console.log('response:', response);
      const { loading = true } = response.config;
      if (loading) cancelLoading();
      const { code, data, message, langMessage } = response.data;
      console.log('success response', response);
      const codeList = ['010902']
      if (codeList.indexOf(code) > -1) {
        uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
      }
      // TODO: 临时注释
      // Promise.reject(response.data)
      return response.data;
    },
    function (error) {
      console.log('error', error);
      // 断网
      if (error.code === 'ERR_NETWORK') {
        uni.showToast({ title: '网络连接失败，请重试', duration: 3000, icon: 'fail' });
        return Promise.reject(error.code);
      }
      // 对响应错误做点什么
      console.log('error-response:', error.response);
      console.log('error-config:', error.config);
      console.log('error-request:', error.request);
      const { loading = true } = error.config || {};
      if (loading) cancelLoading();
      if (error.response) {
        if (error.response.status === 401) {
          // 跳转到登陆
          // jumpLogin();
        }
      }
      // 错误信息提示
      const { code, langMessage, message,status } = error.response.data;
      const codeList = ['INTERNAL_SERVER_ERROR', 'VALIDATION_FAILED', 'CAR_HAS_PLATE', "NOT_FOUND", "LOCAL_PARK_ERROR", "LOCK_OCCUPIED", "REMOTE_CALL_FAIL", 'PLEASE_SCAN_QRCODE', 'SUBIN_CAR_IN_DEVICE_EXCEPTION', 'COUPON_UNAVAILABLE', 'COUPON_SELECTION_FAILED' ]; // 默认处理的错误code
      if (codeList.indexOf(code) > -1) {
        uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
      }
      if ( status === 500 ) {
        uni.showToast({ title: error.response.data.error, duration: 3000, icon: 'fail' });
      }
      // Message.error(error?.response?.data?.message || '服务端异常');
      return Promise.reject(error.response.data);
    }
  );
  return instance;
};
