import fetch from 'dva/fetch';
import { notification } from 'antd';
import { routerRedux } from 'dva/router';
import axios from 'axios';
import store from 'store';
import querystring from 'querystring';
import store1 from '../index';
import { gup } from './utils';
import qs from 'qs';
import $loading from './loading';
const CancelToken = axios.CancelToken;
notification.config({
  placement: 'topLeft',
  top: 100,
  bottom: 50,
  duration: 3
});

const pending = [];

const removePending = config => {
  for (const p in pending) {
    if (pending[p].u === config.url + '&' + config.method) {
      //当当前请求在数组中存在时执行函数体
      pending[p].f(); //执行取消操作
      pending.splice(p, 1); //把这条记录从数组中移除
    }
  }
};

const instance = axios.create({
  timeout: 60000,
  headers: {
    Authorization: 'Basic c2Fhc3dlYjp3ZWI=',
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
});
const access_token = gup('access_token',window.location.href);
if(access_token) {
  const saas = store.get('saas') || {};
  store.set('saas', {...saas, access_token});
}
const userV5Token = store.get('saas')['access_token'];//获取v5 5.0带过来标识符，1代表v5的token

if(userV5Token){ //用于判断是否从v5那边过来  在src\router.js会用到
  sessionStorage.setItem('userV5Token', userV5Token);

}else{
  // sessionStorage.userV5Token = '';

}

let timeid;
/* instance.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8"; */

function checkStatus(response) {


  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  notification.error({
    message: `请求错误 ${response.status}: ${response.url}`,
    description: response.statusText
  });
  const error1 = new Error(response.statusText);
  error1.response = response;
  throw error1;
}

/**
 * 2019-07-03(Lyq)
 */
// const apiPrefix = '/saas_api';
const apiPrefix = '';

function getHostByPath() {
  const NODE_EVN = process.env.NODE_ENV;
  if(NODE_EVN == 'development') {
    // return 'http://114.116.90.77:9009';  //直连服务（在接口允许跨域的情况下）
    return 'https://personnel-oa.te.baibaodun.com.cn' + apiPrefix;  //node服务
    return apiPrefix;
  }else {
    return 'https://personnel-oa.te.baibaodun.com.cn' + apiPrefix;
  }
}

export { getHostByPath };

/**
 * 需要登录
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */

//  notip 为true的时候不自动提示返回内容
//  noAccessToken 为true的时候不传access_token
export function request(path, options, testUrl, notip, loading = true,noAccessToken= false) {
  let url = path;
  if(url.indexOf('http') == -1) {
    url = (testUrl || getHostByPath()) + path;
  }
  const defaultOptions = {
    credentials: 'include'
  };
  const newOptions = {
    ...defaultOptions,
    ...options
  };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    newOptions.headers = {
      ...newOptions.headers
    };
    newOptions.body = JSON.stringify({ ...newOptions.body, v: 'v1.0' });
  }

  if (options && options.data) {
    delete newOptions.body;
    if (store.get('saas') === undefined) {
      const { dispatch } = store1;
      // dispatch(routerRedux.push('/user/logOn'));
      // notification.error({
      //   message: "请登录"
      // });
      return Promise.reject('未登录');
    }
    const method = options.method.toLowerCase();
    loading && $loading.open();

    let requestData = {};
    if(Object.prototype.toString.call(options.data).slice(8, -1) == 'FormData') {
      options.data.append('api', url);
      options.data.append('v', 'v1.0');
      requestData = options.data;
    }else {
      requestData = querystring.stringify({ ...options.data, api: url, v: 'v1.0' });
    }

    let headers = options.headers || {};
    if(!noAccessToken){
      headers = {
        ...headers,
        access_token: store.get('saas')['access_token'],
        Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,

        userV5Token:userV5Token?1:0,//1待办v5用户，0待办sass用户
      }
    }
    return instance({
      url,
      method,
      headers,
      params: method === 'get' ? { ...options.data, api: url, v: 'v1.0' } : {},
      // data:
      //   method === 'post'
      //     ? requestData
      //     : {}
      data: requestData
    })
      .then(response => {
        console.log(response);
        loading && $loading.close();
        const { status, data } = response;
        // 返回时间获取到服务器时间，用于时间插件天的管理控制
        data.date = response.headers.date;
        if (data.retType === '1') {
          store.remove();
          //防止重复提示
          clearTimeout(timeid);
          timeid = window.setTimeout(() => {
            if(!notip){
              notification.error({
                message: data.msg
              });
            }
          }, 500);

          const { dispatch } = store1;
          store.clearAll();
          // dispatch(routerRedux.push('/user/logOn'));
          return Promise.reject(data);
        }
        if (status !== 200 || data.retType !== '0') {
          if(!notip){
            notification.error({
              message: data.msg
            });
          }
          return Promise.reject(data);
        }
        if (method === 'post' && data.msg) {
          if(!notip) {
            notification.success({
              message: data.msg
            });
          }
        }
        let newData1;
        try {
          newData1 = JSON.parse(JSON.stringify(data).replace(/null/g, '""'));
        } catch (err) {
          newData1 = data;
        }
        return newData1;
      })
      .catch(err => {

        console.log(err.response);

        try {
          if(err.response&&err.response.data&&err.response.data.msg){
            notification.error({
              message: `错误`,
              description:err.response.data.msg
            });
          }
        } catch (error) {
          
        }
 
        loading && $loading.close();
        if (err.toString().indexOf('Network') !== -1) {
          notification.error({
            message: '网络出错了'
          });
          const { dispatch } = store1;
          // dispatch(routerRedux.push('/user/logOn'));
        }
        return Promise.reject(err);
      });
  } else {
    return fetch(url, { ...newOptions, api: url, v: 'v1.0' })
      .then(checkStatus)
      .then(response => {
        loading && $loading.close();
        return response.json()
      })
      .catch(error => {
        loading && $loading.close();
        if (error.code) {
          notification.error({
            message: error.name,
            description: error.message
          });
        }
        if ('stack' in error && 'message' in error) { 吗
          notification.error({
            message: `请求错误: ${url}`,
            description: error.message
          });
        }
        return error;
      });
  }
}

/* 不需要登录 */
export function noLoginRequest(path, options, testUrl) {
  const url = testUrl || getHostByPath() + path;
  // const url = getHostByPath(path) + path;
  const defaultOptions = {
    credentials: 'include,',

  };
  const newOptions = {
    ...defaultOptions,
    ...options
  };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    newOptions.headers = {
      ...newOptions.headers,
    };
    newOptions.body = JSON.stringify({ ...newOptions.body, v: 'v1.0' });
    // newOptions.body = {...newOptions.body, v: "v1.0"};
  }

  const method = options.method.toLowerCase();
  return axios({
    headers:{
    Accesstoken: store.get('saas')['access_token'],

    },
    url,
    method,
    params: method === 'get' ? { ...options.data, api: url, v: 'v1.0' } : {},
    data:
      method === 'post'
        ? querystring.stringify({ ...options.data, api: url, v: 'v1.0' })
        : {}
  })
    .then(response => {
      const { status, data } = response;
      // 返回时间获取到服务器时间，用于时间插件的管理控制
      data.date = response.headers.date;
      if (data.retType === '1') {
        notification.error({
          message: data.msg
        });
        const { dispatch } = store1;
        // dispatch(routerRedux.push('/user/logOn'));
        return Promise.reject(data);
      }
      if (status !== 200 || data.retType !== '0') {
        notification.error({
          message: data.msg
        });
        return Promise.reject(data);
      }
      if (method === 'post' && data.msg) {
        notification.success({
          message: data.msg
        });
      }

      let newData1;
      try {
        newData1 = JSON.parse(JSON.stringify(data).replace(/null/g, '""'));
      } catch (err) {
        newData1 = data;
      }

      return newData1;
    })
    .catch(err => {
      console.log(err, 'err');
      if (err.toString().indexOf('Network') !== -1) {
        // notification.error({
        //   message: "网络出错了"
        // });
        const { dispatch } = store1;
        dispatch({ type: 'global/netError' });
      }
      return Promise.reject(err);
    });
}

/* 登录请求
注意：本应该是post请求提交的参数确要用get提交参数后期要后端整改
---------------------------------------------------*/
export function loginRequest(path, options, testUrl) {
  const url = testUrl || getHostByPath() + path;
  // const url = getHostByPath(path) + path;
  return instance
    .post(url, {
      ...options.data,
      api: url,
      v: 'v1.0',
      grant_type: 'password'
    })
    .then(response => {
      const { status, data } = response;
      if (status === 200 && data.retType === '0') {
        store.set('saas', {
          access_token: data.data.access_token,
        Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,
          
          sessionId: encodeURIComponent(data.data.sessionId), //嵌入百课堂和百保盾页面，直接使用接口数据，iframe不用拼接
          thirdSessionId: data.data.thirdSessionId,  //薪酬管理页面
        });
      } else {
        notification.error({
          message: data.msg
        });
      }
      return data;
    })
    .catch(err => {
      if (err.toString().indexOf('Network') !== -1) {
        notification.error({
          message: '网络出错了'
        });
      }
      return { status: 600, data: { retType: '-1' } };
    });
}


export function saasDownloadBlob(url, params = {}) {
  url = url.replace(/^\//, '');
  let queryStr = '';
  Object.keys(params).forEach(key => {
    queryStr += `${key}=${params[key]}&`;
  });
  queryStr = queryStr.slice(0, -1);
  return axios({
    method: 'get',
    url:
      `${apiPrefix}/${url}?${queryStr}`, //后台请求地址
    responseType: 'blob',
    headers: {
      access_token: store.get('saas')['access_token'],
      Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,

    }
  });
}

/**
 * @lyq
 */
instance.interceptors.request.use(config => {
  removePending(config);
  config.cancelToken = new CancelToken(c => {
    // 这里的ajax标识我是用请求地址&请求方式拼接的字符串，当然你可以选择其他的一些方式
    pending.push({
      u: config.url + '&' + config.method + config.data,
      f: c
    });
  });
  return config;
}, err => {
  return Promise.reject(err);
});



axios.interceptors.response.use(
  res => {
    console.log(res);

    return res;
  },
  err => {

    return Promise.reject(err);
  }
);
/**
 * @lyq
 * 百课堂的接口请求
 * 接口名称以bkt_api开头，后面跟上对应的接口名
 */
/************************百课堂请求********************** */
// window.bktReqCancels = [];
const bktInstance = axios.create();
bktInstance.interceptors.request.use(function (config) {
  if(config.method.toLowerCase() == 'get') {
    config.params = {...config.params, ...config.data};
  }else {
    if(config.data.data) {
      config.data.data = JSON.stringify(config.data.data);
      config.data = qs.stringify(config.data);
    }
  }
  // cancel
  removePending(config);
  config.cancelToken = new CancelToken(c => {
    // 这里的ajax标识我是用请求地址&请求方式拼接的字符串，当然你可以选择其他的一些方式
    pending.push({
      u: config.url + '&' + config.method + config.data,
      f: c
    });
  });
  return config;
}, function (error) {
  // Do something with request error
  removePending(error.config);
  return Promise.reject(error);
});

// Add a response interceptor
bktInstance.interceptors.response.use(function (response) {
  // Do something with response data
  return response;
}, function (error) {
  // Do something with response error
  return Promise.reject(error);
});
export function bktRequest(axiosOptions = {}, reqOptions = {}) {
  reqOptions = {
    loading: true,  //显示加载动画
    successMsg: false,   // 显示成功提示
    errMsg: true,   // 显示成功提示
    withToken: true, // 是否需要token
    type: '',  //请求类型 如果是上传文件‘upload’不用重整数据
    ...reqOptions
  };
  const { loading, successMsg, errMsg, withToken } = reqOptions;
  if(withToken && store.get('saas') === undefined) {
    store.remove();
    const { dispatch } = store1;
      // dispatch(routerRedux.push('/user/logOn'));
      return Promise.reject('未登录');
  }
  const url = '/bkt_api/' + axiosOptions.url.replace(/^\//, "");
  axiosOptions.headers = axiosOptions.headers || {};
  const headers = {
    Authorization: 'Basic c2Fhc3dlYjp3ZWI=',
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    // 'Content-Type': 'application/form-data',
    // access_token: store.get('saas')['access_token'],
    sessionId: store.get('saas')['sessionId'],
    ...axiosOptions.headers
  };
  axiosOptions.data = axiosOptions.data || {};
  
  if(reqOptions.type !== 'upload') {
    axiosOptions.data = {
      api: axiosOptions.url, 
      v: 'v1.0',
      method: axiosOptions.method || 'post',
      // data: axiosOptions.data
      ...axiosOptions.data
    };
  }

  const btkDefOptions = {
    // method: 'post',
    baseURL: location.origin,
    timeout: 60000,
    cancelToken: new CancelToken(function (cancel) {
      // bktReqCancels.push(cancel);
    })
  };
  const options = {
    method: axiosOptions.method || 'post',
    ...btkDefOptions,
    ...axiosOptions,
    url,
    headers,
  };
  loading && $loading.open();
  return new Promise((resolve, reject) => {
    bktInstance(options).then(res => {
      loading && $loading.close();
      if(res.data.retType == '0') {
        successMsg && notification.success({
          message: res.data.msg
        });
        // 获取服务器时间
        res.data.date = res.headers.date;
        resolve(res.data);
      }else {
        reject(res.data);
        errMsg && notification.error({
          message: res.data.msg
        });
      }
      if(res.data.retType == '1') {
        store.remove();
        const { dispatch } = store1;
        store.clearAll();
        // dispatch(routerRedux.push('/user/logOn'));
      }
    }).catch(err => {
      loading && $loading.close();
      reject(err);
    });
  });
};


