import { Message } from 'element-ui';
import fetch from './fetch'

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;
        Message.error({ message: msg });
        if (failed) {
            failed(resp);
        }
    }

}

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

export default {
    getJson: function(url, data, success, failed, err) {
        let vm = this;
        fetch({ url: url, method: 'get', params: data }).then((response) => {
            successResponse(vm, response, success, failed)
        }).catch(error => {
            errorResponse(vm, error, err);
        });
    },
    postJson: function(url, data, success, failed, err) {
        let vm = this;
        fetch({ url: url, method: 'post', data: data }).then((response) => {
            successResponse(vm, response, success, failed)
        }).catch(error => {
            errorResponse(vm, error, err);
        });
    }
}