/**
 * @flow
 */

import moment from 'moment';
import DeviceInfo from 'react-native-device-info';
import axios from 'axios';
import {
  getCoreAPIRequestUrl,
} from './APIConfig';
import { ENV, ppkVersion, MOCK } from '../constants';
import responseCode from './responseCode';
import { AssetsModule } from '../native-utils';
import toast from '../../components/Toast';
import mockUtil from './mockUtil';

export const APIDeps = {
  sessionid: '',
  ppkPath: '',
  deviceInfo: {},
  mobile: '',
  source: null,
  loadingQueue: 0,
};

function showToast() {
  APIDeps.loadingQueue += 1;
  console.log('拼命加载中');
  //AssetsModule.showToast('拼命加载中');
}

function dismissToast() {
  APIDeps.loadingQueue = Math.max(0, APIDeps.loadingQueue - 1);
  if (APIDeps.loadingQueue === 0) {
    console.log('关闭转圈');
    //AssetsModule.dismissToast();
  }
}


axios.interceptors.request.use((config) => {
  //console.log(config)
  if (config.config.shouldLoading) {
    showToast();
  }
  return config;
},
(err) => {
  showToast();
  const msg = responseCode.networkError;
  toast(msg);
  return Promise.reject(err);
});

axios.interceptors.response.use((response) => {
  //console.log(response)
  if (response.config.config.hiddenLoading) {
    dismissToast();
  }
  if (response.data.code === '0000') {
    return response;
  } if (responseCode.businessError.indexOf(response.data.code) !== -1) {
    //跳转登录
    return Promise.resolve(response);
  } if (response.data.code[0] === '9') {
    if (response.config.config.shouldHandleError) {
      toast(responseCode.systemError);
    }
    return Promise.resolve(response);
  } if (Number(response.data.code[0]) >= 0 && Number(response.data.code[0]) <= 8) {
    if (response.config.config.shouldHandleError) {
      toast(response.data.desc);
    }
    return Promise.resolve(response);
  }
  if (response.config.config.shouldHandleError) {
    toast(responseCode.systemError);
  }
  return Promise.resolve(response);
}, (err) => {
  dismissToast();
  if (err.message === '用户取消') {
    return Promise.resolve(err.response);
  }
  if (err.toString().indexOf('Network') !== -1) {
    toast(responseCode.networkError);
    return Promise.resolve(err.response);
  }
  toast(responseCode.networkError);
  return Promise.resolve(err.response);
});

export async function fetchCoreAPI(APICode, {
  params,
  method = 'POST',
  shouldHandleError = true,
  shouldLoading = true, // 是否显示loading（非必传,默认为true）
  hiddenLoading = true,
  requestTimeout = 30 * 1000,
}) {
  const url = getCoreAPIRequestUrl({ env: ENV, APICode });

  const { CancelToken } = axios;
  //console.log('url =', url)
  APIDeps.source = CancelToken.source();

  let data;
  if (params) {
    data = JSON.stringify(params);
  }
  const config = {
    method,
    data,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      'x-ac-app-version': DeviceInfo.getVersion() || '',
      'x-ac-channel-id': 'channel',
      'x-ac-device-id': DeviceInfo.getUniqueID() || '',
      'x-ac-os-info': DeviceInfo.getUserAgent(),
      'x-ac-ppk-version': ppkVersion,
      'x-ac-sign': 'RNRNRNRNRNRN',
      'x-ac-time': `${moment()}`,
      'Accept': 'application/json;charset=UTF-8',
      'x-ac-token-ticket': 'accesstokeninfo',
    },
    timeout: requestTimeout,
    cancelToken: APIDeps.source.token,
    config: {
      shouldHandleError,
      shouldLoading,
      hiddenLoading,
    },
    APICode,
  };
  if (method === 'GET' && !params) {
    delete (config.data);
  }


  console.log('请求参数：', config.data);
  // console.log('请求参数：', JSON.stringify(config.data))

  //mock
  if (MOCK) {
    if (config.config.shouldLoading) {
      showToast();
    }
    return new Promise((resolve, reject) => {
      mockUtil(url, config,
        (responseData) => {
          console.log('incallback_responseData', responseData);
          resolve({ code: '0000', data: responseData });
          if (config.config.shouldLoading) {
            dismissToast();
          }
        });
    });
  }
  return new Promise((resolve, reject) => {
    axios(url, config)
      .then((response) => {
        if (response && response.data && response.data.code === '0000') {
          //  console.log('response:', response)
          resolve(response.data);
        } else if (response && response.data) {
          resolve(response.data);
        } else {
          resolve([]);
        }
      })
      .catch((error) => {
        toast(responseCode.systemError);
        reject(error);
      });
  });
}
