import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME,
	TIMEOUT
} from '@/config/app';
import store from '../store';
import UrlUtils from './urlUtils.js';

/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}) {
	let Url = HTTP_REQUEST_URL;
	let	header = HEADER;
	
	HEADER['form-type'] = 'gzh';
	header = HEADER;

	
	if (store.state.app.token) header[TOKENNAME] = 'Bearer ' + store.state.app.token;
	return new Promise((reslove, reject) => {
		if (uni.getStorageSync('locale')) {
			header['Cb-lang'] = uni.getStorageSync('locale')
		}
		uni.request({
			url: url,
			method: method || 'GET',
			header: header,
			data: data || {},
			timeout: TIMEOUT,
			success: (res) => {
				if (noVerify)
					reslove(res.data, res);
				else if (res.data.status == 200)
					reslove(res.data, res);
				else if ([110002, 110003, 110004].indexOf(res.data.status) !== -1) {
					// #ifdef H5
					window.location.replace(`${HTTP_REQUEST_URL}/api/v2/routine/gzhLogin?back_url=${encodeURIComponent(UrlUtils.keepParams(window.location.href))}`);
					// #endif
					
					reject(res.data);
				} else if (res.data.status == 400 && res.data.msg !== '商户未绑定码牌') {
					uni.showToast({
						title: res.data.msg,
						icon: 'error'
					})
					reject(res.data.msg || '系统错误');
				} else if (res.data.status == 100103) {
					uni.showModal({
						title: '提示',
						content: res.data.msg,
						showCancel: false,
						confirmText: 我知道了
					});
				} else
					reject(res.data.msg || '系统错误');
			},
			fail: (msg) => {
				console.log(msg)
				let data = {
					mag: '请求失败1',
					status: 1 //1没网
				}
				// #ifdef APP-PLUS
				reject(data);
				// #endif
				// #ifndef APP-PLUS
				reject('请求失败');
				// #endif
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;