import http from './api.helper.js'
import store from '@/store/index.js'

const install = (app) => {
	http.setConfig({
		baseUrl: '',
		header: {
			"Content-Type": "application/json; charset=utf-8",
		}
	});
	http.interceptor.request = (config) => {
		if (config.url.indexOf('crm-app/login') === -1 && store.state
			.vuex_token) {
			config.header['X-Auth-Token'] = store.state
				.vuex_token;
		}

		if (config.header['Content-Type'] && config.header['Content-Type'].indexOf('x-www-form-urlencoded') ===
			-1) {
			config.header['Content-Type'] = "application/json; charset=utf-8"
		}

		return config;
	}
	http.interceptor.response = (res) => {
		if (res.MSGTYPE === 'S' || res.msgtype === 'S' || res.status === 1 || res.status === 0 || res.result === 'S' || res
			.Status ===
			'Success') {
			return res;
		} else {
			if (!res.status && !res.msgtype && !res.MSGTYPE) {
				return res;
			}
			let errorMsg = res.MESSAGE || res.msg || res.message || res.ErrMsg || ''
			if (res.errors && Array.isArray(res.errors) && res.errors.length > 0) {
				errorMsg = res.errors[0]
			}
			if (errorMsg && typeof errorMsg === 'string' &&
				(errorMsg.indexOf('cannot be cast') !== -1 || errorMsg.indexOf('DCloudApplication') !== -1)) {
				return false
			}
			uni.showToast({
				title: errorMsg,
				duration: 4000,
				icon: 'none'
			});
			return false
		};
	}
}

export default {
	install
}
