define(['app'], function (app) {
    'use strict';

    app.factory('app.httpInterceptor', function ($q, $location, $rootScope) {
        var handleRequest = function (config) {
            // 提前处理AJAX 服务器返回的结果,如果有错误显示错误信息,如果需要登录,转到登陆
            if (config.url.indexOf('api') >= 0) {
                config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
                if (localStorage.access_token) {
                    config.headers['x-access-token'] = localStorage.access_token;
                }

                if (config.data && typeof (config.data) === 'object') {
                    var params = [];
                    for (var key in config.data) {
                        // 如果值是"对象"，转换成json格式后传给服务器
                        if (typeof(config.data[key]) === 'object') {
                            params.push(encodeURIComponent(key) + '=' + encodeURIComponent(JSON.stringify(config.data[key])));
                        } else {
                            params.push(encodeURIComponent(key) + '=' + encodeURIComponent(config.data[key]));
                        }
                    }

                    config.data = params.join('&');
                }
            }
            return config;
        };
        var handleRequestError = function (rejection) {
            return $q.reject(rejection);
        };
        var handleResponse = function (response) {
            var type = response.headers()['content-type'];
            if (type && type.indexOf('application/json') !== -1) {
                // 服务器返回错误
                if (response.data.error) {
                    // 需要登录?
                    if (response.data.error.code === 1005 || response.data.error.code === 1008) {
                        $rootScope.$broadcast('loginRequired');
                    } else {
                        $rootScope.$broadcast('apiError', response.data.error);
                    }
        };
        var handleResponseError = function (rejection) {
            return $q.reject(rejection);
        };

        return {
            request: handleRequest,
            requestError: handleRequestError,
            response: handleResponse,
            responseError: handleResponseError
        };
    });

    return app.config(function ($httpProvider) {
        $httpProvider.interceptors.push('app.httpInterceptor');
    });
});
                }
            }

            return response;