import type { AxiosRequestConfig, AxiosError } from 'axios';
import axios, { AxiosResponse } from 'axios';
import { createHttp, icpxTransform, icpxTransformConfig } from '@crami/http';
import { HModal } from '@crami/ui';
import { notification } from 'ant-design-vue';

import { baseParams, getInfo, ICP_CONFIG, localStorage } from '@remote/icpx-platform/utils';
/* import { baseParams, getInfo, ICP_CONFIG } from './commMethods'; */
import { computed } from 'vue';

// 公共参数
const commonParams = computed(() => {
  return {
    ...getInfo(ICP_CONFIG),
  };
});

// 这里是用于设定请求后端时，所用的 Token KEY
// 可以根据自己的需要修改，常见的如 Access-Token，Authorization
// 需要注意的是，请尽量保证使用中横线`-` 来作为分隔符，
// 避免被 nginx 等负载均衡器丢弃了自定义的请求头
export const REQUEST_TOKEN_KEY = 'Authorization';

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 16000, // 请求超时时间
});

// token取主应用的token
const token = baseParams.token
  ? baseParams.token
  : 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyLWtleSI6ImUyMDEzYzU2LTA3NWUtNDZmYS05MjgyLTAwMjBlZWI3YTQxMSIsImNvbXBhbnlpZCI6IlBfU1lTX0NPTVBBTllfMTU1ZjZhMzMxZTgwNGI2OWE2ZmM0N2U2MjczNjk5ZmMiLCJwcm9qZWN0Y29kZSI6IlBMTUJBU0UiLCJ1c2VyaWQiOiJQX1NZU19VU0VSXzAxNjJhM2MyYzg1YzQ1ZjJiNGZhM2JhZmZjMzUwZDZkIiwib3JnSWQiOm51bGwsInVzZXJuYW1lIjoiYWRtaW4ifQ.OVvy9pktLwnbBXhWeW2hOr7a0QTIeOVvSCaT6QBAhWXdERFDG94OJQPexoOW5ODZ062UZYoKEkMUcCiy4lLhEQ';

export const http = createHttp(request, {
  responseTransform: icpxTransform,
  requestTransform: icpxTransformConfig,
  urlParser: url => url.trim().replace(/^\/api/, ''),
});

// 异常拦截处理器
const errorHandler = (error: AxiosError): Promise<any> => {
  if (error.response) {
    const { data = {}, status, statusText } = error.response;
    // 403 无权限
    if (status === 403) {
      notification.destroy();
      notification.error({
        message: 'Forbidden',
        description: (data && data.message) || statusText,
      });
    }
    // 401 未登录/未授权
    if (status === 401 && data.result && data.result.isLogin) {
      const savedToken = token; // localStorage.get(STORAGE_TOKEN_KEY);
      if (savedToken) {
        notification.destroy();
        notification.error({
          message: 'Unauthorized',
          description: (data && data.message) || statusText,
        });
      }
      // const router = useRouter();
      // store
      //   .dispatch(`user/${LOGOUT}`)
      //   .then(() => {
      //     //location.href = '/user/login';
      //     // console.log(router)
      //     router.push({ path: '/user/login' });
      //     window.localStorage.clear();
      //     window.sessionStorage.clear();
      //   })
      //   .catch((err) => {
      //     console.log(err);
      //   })
      //   .finally(() => {});
    }
  }
  return Promise.reject(error);
};

// 请求拦截器
const requestHandler = (
  config: AxiosRequestConfig,
): AxiosRequestConfig | Promise<AxiosRequestConfig> => {
  // 开启跨域设置
  config.headers['Access-Control-Allow-Credentials'] = true;
  config.headers['Access-Control-Allow-Origin'] = '*';
  config.headers['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Typ';
  config.headers['Access-Control-Allow-Methods'] = 'PUT,POST,GET,DELETE,OPTIONS';

  const savedToken = token; //localStorage.get(STORAGE_TOKEN_KEY);
  // 设置请求头多语言，默认是中文
  config.headers[`Accept-Language`] = 'zh-CN';
  // localStorage.get(STORAGE_LANG_KEY) ?? 'zh-CN';

  // 让每个请求携带自定义 token, 请根据实际情况修改
  if (savedToken) {
    config.headers[REQUEST_TOKEN_KEY] = 'Bearer ' + savedToken;
  }
  // 添加companyId和userid,get随便添加data会报错
  if (config.data || config.method != 'get') {
    config.data = {
      ...config.data,
      ...{
        companyId: commonParams.value.companyId,
        // orgId: 'P_SYS_COMPANY_155f6a331e804b69a6fc47e6273699fc',
        // userDept: 'P_SYS_DEPT_21a0a27ac5de49609028dcfe8976a5ca',
        // userGroup: 'P_SYS_COMPANY_155f6a331e804b69a6fc47e6273699fc',
        // userId: 'P_SYS_USER_0162a3c2c85c45f2b4fa3baffc350d6d',
        // project: 'PLMBASE',
        // projectCode: 'PLMBASE',
        // productLine: 'PLM_PROJECT;baicsrm;PLM_CAPP;PLMBASE;PLMPRODUCT;loxamom',
        timeZone: commonParams.value.TIME_ZONE,
        connect: commonParams.value.connect,
        // paraList:
        //   config.data.paraList && config.data.paraList.indexOf('parentId') != -1
        //     ? config.data.paraList
        //     : '{"companyId":"P_SYS_COMPANY_155f6a331e804b69a6fc47e6273699fc","connect":"MYSQL","lang":"zhs","productLine":"PLM_PROJECT;baicsrm;PLM_CAPP;PLMBASE;PLMPRODUCT;loxamom","userId":"P_SYS_USER_0162a3c2c85c45f2b4fa3baffc350d6d","userDept":"P_SYS_DEPT_21a0a27ac5de49609028dcfe8976a5ca","userGroup":"P_SYS_COMPANY_155f6a331e804b69a6fc47e6273699fc","projectCode":"PLMBASE"}',
      },
    };
  }
  // 如果是树请求，添加paraList
  if (config.url && config.url.indexOf('getGetTreeRootDataList') != -1) {
    config.data.paraList = `{"companyId":"${commonParams.value.companyId}","connect":"${commonParams.value.connect}","lang":"${commonParams.value.lang}","productLine":"${commonParams.value.productLine}","userId":"${commonParams.value.userId}","userDept":"${commonParams.value.userDept}","userGroup":"${commonParams.value.userGroup}","projectCode":"${commonParams.value.projectCode}"}`;
  }
  // 有一些请求，添加需要添加语言
  const langArray = [
    '/system/model/getGetOnePageGridDataList',
    '/system/model/dealEnumItemTree',
    '/datapermission/dataPer/checkPermission',
  ];
  if (config.url && langArray.indexOf(config.url) != -1) {
    config.data.lang = commonParams.value.lang;
    config.data.userId = commonParams.value.userId;
  }

  // 请求权限，添加userid
  const userArray = [
    '/platform-base-workflow/workFlowDataPermission/getProcessTaskNodeInfoWithCurrentUserId',
  ];
  if (config.url && userArray.indexOf(config.url) != -1) {
    config.data = {
      ...config.data,
      userId: commonParams.value.userId,
    };
  }

  if (config.url.indexOf('/seniorquery/seniorQuery/getConditionGroupNameAll') !== -1) {
    config.data = {
      ...config.data,
      createUid: commonParams.value.userId,
    };
  }

  return config;
};
request.interceptors.request.use(requestHandler, errorHandler);
export type { AxiosResponse };

export default request;
