import apiCfg from './apicfg';
import {getPxToken} from "@spark/projectx";
import {callApi} from '@spark/api-base'
import {Toast} from '@spark/ui'

import {isFromShare, newUser} from 'duiba-utils';

const mergeData = {
	user_type: newUser ? '0' : '1',
	is_from_share: isFromShare ? '0' : '1',
}

const apiList = {
	...apiCfg
}


const API = generateAPI(apiList);
export default API;
/**
 * 请求方法get、post处理
 * @param {*} value 
 * @returns 
 */
function getRequestParams(value) {
	if (typeof value === 'string') {
		return {
			uri: value,
			method: 'get'
		}
	} else if (typeof value === 'object') {
		const {uri, method = 'get', headers, withToken, secret, secretKey, contentType = 'form'} = value;
		return {
			uri,
			method,
			headers,
			withToken,
			secret,
			secretKey,
			contentType,
		}
	} else {
		console.error('getRequestParams: 传参有误');
	}
}

/**
 * 请求API通用处理
 * @param {*} value 
 * @returns 
 */
function generateAPI(apiList) {
	const api = {};
	for (const key in apiList) {
		const value = apiList[key];

		const {method, uri, headers: mHeaders, withToken, secret, secretKey, contentType} = getRequestParams(value);
		api[key] = async (params = {}, headers) => {
			let token;
			if (withToken) {   // 是否携带token
				try {
					token = await getPxToken(); // 获取token
				} catch (e) {
					Toast('网络异常，请稍后再试~');
					return({ success: false ,data:''});
				}
			}

			const mergedHeaders = {...mHeaders, ...headers} 
			if (withToken && token) {
				params.token = token;
			}

			params = {...params, ...mergeData};

			const result = await callApi(uri, params, method, mergedHeaders, false, secret, secretKey, contentType)
				.catch(e => {
					// 捕获网络异常
					Toast(e.message || '网络异常，请稍后再试~');
				});
			return new Promise((resolve) => {
				if (result) {
					// 判断接口错误
					if (!result.success) {
						Toast(result.message || '网络异常，请稍后再试~');
					}
					// 返回整个结果
					resolve(result);
				} else {
					resolve({ success: false, data: '' });
				}
			})
		}
	}

	return api;
}
