import axios from 'axios'
import qs from 'qs'
import {Message} from 'element-ui'
import router from '../router'
import {BASE_URL, PHOTO_BASE_URL} from './baseUrl'
import Vue from 'vue'
// Vue.prototype.servelUrl = BASE_URL;
Vue.prototype.servelUrl = PHOTO_BASE_URL;


// //  这个baseUrl要根据实际情况进行改变
axios.defaults.baseURL = BASE_URL;
axios.defaults.timeout = 60000;
axios.defaults.headers.common['Content-Type'] =
    'application/json; charset=UTF-8;application/x-www-form-urlencoded';
// axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
//网络请求
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, {
        headers: {
          'openId':window.localStorage.getItem('openId')
        }
      })
    } else {
      if (isupload) {
        promise = axios.post(url, data, {
          headers: {
            'openId':window.localStorage.getItem('openId'),
            'Content-Type': 'multipart/form-data'
          },
          transformRequest: [function (data) {
            return data
          }]
        })
      } else {
        promise = axios.post(url, qs.stringify(data), {
          headers: {
            'openId': window.localStorage.getItem('openId')
          }
        })
      }
    }
    promise.then(function (response) {
      if (response.data.code == 0) {
        resolve(response.data)
      } else if (response.data.code == 2) {
        Message({
          message: '登录失效,请重新登录',
          type: 'error',
          duration: 5000
        });
        router.replace("/login");
      }else if (response.data.code == 222) {
        Message({
          message: response.data.message ,
          type: 'error',
          duration: 5000
        });
        router.replace("/main");
      } else {
        if (response.data.message && response.data.message!=' ') {
          if(response.data.code=='222202')
          {
            Message({
              message: '人脸比对失败,请传老人现场照片！',
              type: 'error',
              duration: 5000
            });
          }
          else {
            Message({
              message: response.data.message,
              type: 'error',
              duration: 5000
            });
          }
        }
        resolve(response.data)
      }
    }).catch(function (error) {
      Message({
        message: '系统异常，请联系管理员',
        type: 'error',
        duration: 5000
      });
      // console.error("异常", error);
      reject(error)
    })
  })
}
