
import axios from 'axios';
import LocalStorage from 'local-storage';
import { appId } from '../App';

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

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

const instance = axios.create({
  baseURL,
  timeout: 15000,
  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: 15000,
  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: 15000,
  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/login":"/center-home/view/login"
   
    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 env = LocalStorage.get('assetsEnv')??debugEnv;

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

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

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

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

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

export function PostJSON(url, payload) {
  const { params = null, data = null } = payload||{};
  const cancelToken = __source ? __source.token : null;
  const env = LocalStorage.get('assetsEnv')??debugEnv;
  // let templateType = getTemplateType()
  // try {
  //   if(!templateType){
  //     templateType = params
  //   }
  // } catch (error) {
    
  // }
  console.log(params)

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

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

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

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

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

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

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

export const callFetchRaw = (method, url, options) => {
  const { params, ...reqConfig } = options;
  var bodyFormData = new FormData();
  Object.keys(params||[]).forEach(key => {
    bodyFormData.append(key, params[key]);
  });
  bodyFormData.append('templateType', getTemplateType());

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