
import axios from 'axios';
import qs from 'qs';
import LocalStorage from 'local-storage';

import { IsArr, showMessage, isSzseEnv, generateUUID } from './index';
import { appId } from '../App';

const CancelToken = axios.CancelToken;
const baseURL = '/api/';
const debugEnv = 475629450;

const instance = axios.create({
  baseURL,
  timeout: 300000,
  headers: {
    //'X-Custom-Header': 'rest',
    'Cache-Control': 'no-cache,no-store,must-revalidate,max-age=-1,private'
  },
  responseType: 'json', // default
  validateStatus: (status) => {
    return true; 
  }
});

const instanceRow = axios.create({
  baseURL: '',
  timeout: 300000,
  headers: {
    //'X-Custom-Header': 'rest',
    'Cache-Control': 'no-cache,no-store,must-revalidate,max-age=-1,private'
  },
  responseType: 'json', // default
  validateStatus: (status) => {
    return true; 
  }
});

const textplain = axios.create({
  baseURL,
  timeout: 300000,
  headers: {
    //'X-Custom-Header': 'rest',
    'Cache-Control': 'no-cache,no-store,must-revalidate,max-age=-1,private'
  },
  transformResponse: [(data) => {
     return data; 
  }],
});

textplain.interceptors.request.use(
  (config) => {
    let parmas = config.params
    
    if (config.method === 'post' && parmas) {
      let url_params = ''

      for (const key in parmas) {
        const val = parmas[key];
        let url_params_temp = url_params;
        if (IsArr(val)){
          val.map((_val)=> {
            url_params_temp +=  url_params_temp ? '&' : '?';
            url_params_temp += encodeURIComponent(key+'[]') + '=' + encodeURIComponent(_val);
            return _val;
          });
        } else {
          url_params_temp += url_params_temp ? '&' : '?';
          url_params_temp += encodeURIComponent(key) + '=' + encodeURIComponent(parmas[key]);
        }

        url_params = url_params_temp;
      }

      config.url = config.url+url_params;
      config.params = {};
    }

    return config;
  }
);



const fileplain = axios.create({
  baseURL,
  timeout: 300000,
  headers:{'Content-Type':'multipart/form-data'},
  processData:false,
  validateStatus: (status) => {
    return true; 
  }
});

let __source = null;
export const Cancel = function (msg) {
  return new Promise(res => __source && __source.cancel(msg));
}
export const SetSource = function (source) {
  __source = source || CancelToken.source();
}

const callback = resp => {

  if (resp.status === 401) {
    showMessage('warn', 'session过期,请重新登录!');

    window.location.href = isSzseEnv?`/api/auth/oauth/login?redirectURL=${encodeURIComponent(window.location.href)}`:`/center-home/view/login?redirectURL=${encodeURIComponent(window.location.href)}`
   
    return null;
  }
  else if (resp.status !== 200) {
    throw resp.data;
  }

  return resp.data || resp;
}

export function getTemplateType() {
  return LocalStorage.get(`templateType-${appId}`)
}

export function Get(url, params) {
  const cancelToken = __source ? __source.token : null;
  const templateType = getTemplateType();
  const env = LocalStorage.get('assetsEnv')??debugEnv;

  return textplain.get(url, {
    params: {templateType, env, ...params}, cancelToken
  }).then(
    callback
  )
}

export function GetJSON(url, params) {
  const cancelToken = __source ? __source.token : null;
  const templateType = getTemplateType();
  const env = LocalStorage.get('assetsEnv')??debugEnv;

  return instance.get(url, {
    params: {templateType, env, ...params}, cancelToken,
    validateStatus: false
  }).then(
    callback
  )
}

export const GetJSONRaw = (url, params) => {
  const cancelToken = __source ? __source.token : null;
  const templateType = getTemplateType();
  const env = LocalStorage.get('assetsEnv')??debugEnv;

  return instanceRow.get(url, {
    params: {templateType, env, ...params}, cancelToken,
    validateStatus: false
  }).then(
    callback
  )
}

export function Delete(url, params) {
  const cancelToken = __source ? __source.token : null;
  const templateType = getTemplateType();
  const env = LocalStorage.get('assetsEnv')??debugEnv;

  return instance.delete(url, {
    params: {templateType, env, ...params}, cancelToken,
  }).then(
    callback
  )
}

export function PostJSON(url, payload) {
  const { params = null, data = null } = payload||{};
  const cancelToken = __source ? __source.token : null;
  const templateType = getTemplateType();
  const env = LocalStorage.get('assetsEnv')??debugEnv;

  return IsArr(data) ? instance.post(url, data, {
    params: {templateType, env, ...params}, cancelToken
  }).then(
    callback
  ) : instance.post(url, null, {
    params: {templateType, env, ...params}, data, cancelToken
  }).then(
    callback
  )
}

export function Post(url, payload) {
  const { params = null, data = null } = payload||{};
  const cancelToken = __source ? __source.token : null;
  const templateType = getTemplateType();
  const env = LocalStorage.get('assetsEnv')??debugEnv;

  return textplain.post(url, null, {
    params: {templateType, env, ...params}, data, cancelToken
  }).then(
    callback
  )
}

export function PostFile(url, payload) {
  const { fileList = null, params = null } = payload||{};
  const templateType = getTemplateType();
  const env = LocalStorage.get('assetsEnv')??debugEnv;

  let formData = new FormData();
  (fileList||[]).forEach(file=> {
    formData.append('file', file);
  });

  return fileplain.post(url, formData, { params: {templateType, env, ...params} }  ).then(
    callback
  )
}

export const callFetchRaw = (method, url, options) => {
  const { params, ...reqConfig } = options;

  const config = {
    baseURL,
    timeout: 300000,
    cache: 'no-cache',
  }

  const templateType = getTemplateType();
  const env = LocalStorage.get('assetsEnv')??debugEnv;

  var bodyFormData = new FormData();
  Object.keys(params||[]).forEach(key => {
    bodyFormData.append(key, params[key]);
  });

  bodyFormData.append('templateType', templateType);
  bodyFormData.append('env', env);


  return axios.request({
    method,
    url,
    data: bodyFormData,
    ...config,
    ...reqConfig
  })
}

export const callFetchRawByFormData = (method, url, options) => {
  const { params, ...reqConfig } = options;

  const config = {
    baseURL,
    timeout: 300000,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    cache: 'no-cache',
  }

  const templateType = getTemplateType();

  var bodyFormData = new FormData();
  Object.keys(params||{}).forEach(key => {
    bodyFormData.append(key, params[key]);
  });
  bodyFormData.append('templateType', templateType);

  return axios.request({
    method,
    url,
    data: bodyFormData,
    ...config,
    ...reqConfig
  })
}
