import {Message} from 'element-ui';
import fetch from './fetch'
import storage from '@/framework/utils/storage'

function successResponse(vm, response, success, failed) {
  let resp = response.data;
  let result = resp.result ? resp.result : resp.Result;
  if (result === 'success') {
    if (success) {
      success(resp);
    }
  } else {
    let msg = resp.message ? resp.message : resp.ResultMsg || resp.resultMsg || resp.Message;
    Message.error({ message: msg });
    if (failed) {
      failed(resp);
    }
  }

}

function errorResponse(vm, response, err) {
  let json = JSON.parse(JSON.stringify(response))
  console.error(response)
  if (json.response) {
    Message.error({ message: `接口：${json.response.config.url}请求错误，错误状态为：${json.response.status}` })
  } else {
    console.error(vm, response, err)
    Message.error({ message: '请求错误' });
  }
}

export default {
  getJson: function(url, data, success, failed, err) {
    let ProjectId = localStorage.getItem("projectId")
    let userName = storage.get("user_name")
    let vm = this;
    fetch({ url: url, method: 'get', params: data, headers: {'ProjectId': ProjectId, 'Comming': 'adm' ,'Account': userName}}).then((response) => {
      successResponse(vm, response, success, failed)
    }).catch(error => {
      errorResponse(vm, error, err);
    });
  },
  postJson: function(url, data, success, failed, err) {
    let ProjectId = localStorage.getItem("projectId")
    let userName = storage.get("user_name")
    let vm = this;
    fetch({ url: url, method: 'post', data: data, headers: {'ProjectId': ProjectId, 'Comming': 'adm' ,'Account': userName} }).then((response) => {
      successResponse(vm, response, success, failed)
    }).catch(error => {
      errorResponse(vm, error, err);
    });
  }
}
