import axios from 'axios';
import qs from 'qs';
import { Message } from 'element-ui';

axios.defaults.headers.common['Content-Type'] = 'application/json; charset=UTF-8';
//网络请求
export default function ajax(url, data = {}, type = 'GET', isupload) {
  return new Promise(function(resolve, reject) {
    let promise;
    if (type === 'GET') {
      let dataStr = '';
      Object.keys(data).forEach(key => {
        dataStr += key + '=' + data[key] + '&';
      });
      if (dataStr !== '') {
        dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'));
        url = url + '?' + dataStr;
      }
      promise = axios.get(url);
    } else if (type === 'DELETE') {
      let dataString = '';
      Object.keys(data).forEach(key => {
        dataString += key + '=' + data[key] + '&';
      });
      if (dataString !== '') {
        dataString = dataString.substring(0, dataString.lastIndexOf('&'));
        url = url + '?' + dataString;
      }
      promise = axios.delete(url);
    } else {
      if (isupload) {
        promise = axios.post(url, data, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          transformRequest: [
            function(data) {
              return data;
            },
          ],
        });
      } else {
        promise = axios.post(url, qs.stringify(data));
      }
    }
    promise
      .then(function(response) {
        if (response.data.msg == '请求成功') {
          resolve(response.data);
        } else {
          if (response.data.msg) {
            Message({
              message: response.data.msg,
              type: 'error',
              duration: 5000,
            });
          }
          resolve(response.data);
        }
      })
      .catch(function(error) {
        Message({
          message: '系统异常，请联系管理员',
          type: 'error',
          duration: 5000,
        });
        // console.error("异常", error);
        reject(error);
      });
  });
}
