import { Router } from 'express';
import axios from 'axios';
import { CONSTANTS_XG, TEXT_CONSTANTS } from '../constants';
import { Ticker, PayType, OrderStatus, User } from '../models_nosql';
// import { getSignature_XG } from '../utilities';
import { getUserProvidedId } from '../utilities';
import {
	handlerTotalBalance,
	getMerchantOrders,
	getUserPayMethods,
	getMerchantAdvs,
	getResultAdvUpdate,
	getOrderDetails,
	getTickerPriceUSDT,
	checkOrderInDB,
	insertOrderToDB,
	getP2POrders,
	getSpotOrders,
	getP2POrdersNomalized,
	getSpotOrdersNomalized,
	getMerchantAdvsNomalized,
	getMerchantOrdersNomalized,
	getBalancesNormalized,
	getSingleUserProperty,
	getPayMethodProps,
	getPayMethodPropsReverse,
	getPaySubAccount,
	consoleProcessed,
	getOrderDetailsNomalized,
	getObjectRequestParams,
} from '../common';

export const ordersRouter_XG = Router();

// получение балансов
ordersRouter_XG.post('/get-balances', async (req, res) => {
	const { userId, exchangeId, shortName } = req.body;
	const user = await User.findOne({ _id: userId });

	const objParams = {
		userId,
		shortName,
		prefix: `balance_${shortName}_API`,
		constants: CONSTANTS_XG,
		apiKeys: getSingleUserProperty('apiKeys', exchangeId, user.properties),
		requestHeader: {},
		additionals: {},
	};
	// console.log(objParams);
	const totalBalance = await handlerTotalBalance(objParams);

	return res.status(200).json({
		success: totalBalance.spotBalance.length === 0 ? false : true,
		balances: totalBalance,
		message:
			totalBalance.spotBalance.length === 0
				? `${shortName}: ${TEXT_CONSTANTS.BALANCE_ER}`
				: `${shortName}: ${TEXT_CONSTANTS.BALANCE_OK}`,
	});
});

// перевод крипты spot <=> p2p
ordersRouter_XG.put('/transferAsset/:toNameAccount', async (req, res) => {
	const { userId, exchangeName, shortName } = req.body;

	return res.status(200).json({
		success: true,
		tickers: await Ticker.find(),
		balances: {
			spotBalance: [],
			p2pBalance: [],
			futBalance: [],
			earnBalance: [],
		},
		message,
	});
});

// получение массива объявлений
ordersRouter_XG.post('/merchant-advs', async (req, res) => {
	const { userId, shortName, exchangeId, objParams } = req.body;
	const user = await User.findOne({ _id: userId });
	const requestHeaderTW = getSingleUserProperty(
		'requestHeader',
		exchangeId,
		user.properties
	);

	const params = {
		userId,
		prefix: shortName,
		config: {
			withCredentials: true,
			method: GET_MERCHANT_ADVS.method,
			url: GET_MERCHANT_ADVS.url,
			data: {
				page: objParams.page,
				rows: objParams.rows,
				inDeal: 1,
			},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				c2ctype: 'c2c_merchant',
				clienttype: 'web',
				cookie: '',
				csrftoken: '',
				'device-info': '',
				'user-agent': '',
			},
		},
	};

	// const arrData = await getMerchantAdvs(params);
	const arrData = [
		{
			id: 170810,
			number: 'AS-00170810',
			status: 'ACTIVE',
			type: 'SALE',
			price: {
				type: 'FIXED',
				baseCurrencyCode: 'USDT',
				quoteCurrencyCode: 'RUB',
				value: '116.16',
				estimated: '116.16',
			},
			availableVolume: { currencyCode: 'USDT', amount: '49.550000' },
			orderAmountLimits: {
				currencyCode: 'RUB',
				min: '100',
				max: '5755.72',
				approximate: false,
			},
			orderVolumeLimits: {
				currencyCode: 'USDT',
				min: '0.860881',
				max: '49.55',
				approximate: true,
			},
			paymentDetails: [
				{
					id: 254187,
					userId: 3391617,
					paymentMethod: {
						code: 'vtbbankru',
						name: 'ВТБ',
						originNameLocale: 'ru',
						nameEng: 'VTB',
					},
					currency: 'RUB',
					attributes: {
						version: 'V1',
						values: [
							{
								name: 'PAYMENT_DETAILS_NUMBER',
								value: '4893 4702 8979 1946',
							},
						],
					},
					name: 'VTB',
				},
				{
					id: 254208,
					userId: 3391617,
					paymentMethod: {
						code: 'mts',
						name: 'МТС-банк',
						originNameLocale: 'ru',
						nameEng: 'MTS-bank',
					},
					currency: 'RUB',
					attributes: {
						version: 'V1',
						values: [
							{
								name: 'PAYMENT_DETAILS_NUMBER',
								value: '2200 2806 9200 2027',
							},
						],
					},
					name: 'MTS-bank',
				},
				{
					id: 254180,
					userId: 3391617,
					paymentMethod: {
						code: 'sberbankru',
						name: 'Сбербанк',
						originNameLocale: 'ru',
						nameEng: 'Sberbank',
					},
					currency: 'RUB',
					attributes: {
						version: 'V1',
						values: [
							{
								name: 'PAYMENT_DETAILS_NUMBER',
								value: '2202 2067 9607 4354',
							},
						],
					},
					name: 'Sberbank',
				},
				{
					id: 254219,
					userId: 3391617,
					paymentMethod: {
						code: 'alfabank',
						name: 'Альфа-Банк',
						originNameLocale: 'ru',
						nameEng: 'Alfa-Bank',
					},
					currency: 'RUB',
					attributes: {
						version: 'V1',
						values: [
							{
								name: 'PAYMENT_DETAILS_NUMBER',
								value: '4790 8730 0927 6425',
							},
						],
					},
					name: 'Alfa-Bank',
				},
				{
					id: 254176,
					userId: 3391617,
					paymentMethod: {
						code: 'tinkoff',
						name: 'Тинькофф',
						originNameLocale: 'ru',
						nameEng: 'Tinkoff',
					},
					currency: 'RUB',
					attributes: {
						version: 'V1',
						values: [
							{
								name: 'PAYMENT_DETAILS_NUMBER',
								value: '5536 9139 7791 5624',
							},
						],
					},
					name: 'Tinkoff',
				},
			],
		},
		{
			id: 168526,
			number: 'AB-00168526',
			status: 'ACTIVE',
			type: 'PURCHASE',
			price: {
				type: 'FLOATING',
				baseCurrencyCode: 'TON',
				quoteCurrencyCode: 'RUB',
				value: '90',
				estimated: '186.21068575863267',
			},
			availableVolume: {
				currencyCode: 'TON',
				amount: '4000.000000000',
			},
			orderAmountLimits: {
				currencyCode: 'RUB',
				min: '100',
				max: '744842.74',
				approximate: false,
			},
			orderVolumeLimits: {
				currencyCode: 'TON',
				min: '0.537026108',
				max: '4000',
				approximate: true,
			},
			paymentMethods: [
				{
					code: 'rosbank',
					name: 'Росбанк',
					originNameLocale: 'ru',
					nameEng: 'Rosbank',
				},
				{
					code: 'raiffeisenru',
					name: 'Райффайзен Банк',
					originNameLocale: 'ru',
					nameEng: 'Raiffeisen Bank',
				},
				{
					code: 'sberbankru',
					name: 'Сбербанк',
					originNameLocale: 'ru',
					nameEng: 'Sberbank',
				},
				{
					code: 'tinkoff',
					name: 'Тинькофф',
					originNameLocale: 'ru',
					nameEng: 'Tinkoff',
				},
				{
					code: 'mts',
					name: 'МТС-банк',
					originNameLocale: 'ru',
					nameEng: 'MTS-bank',
				},
			],
		},
		{
			id: 168525,
			number: 'AB-00168525',
			status: 'ACTIVE',
			type: 'PURCHASE',
			price: {
				type: 'FLOATING',
				baseCurrencyCode: 'TON',
				quoteCurrencyCode: 'RUB',
				value: '90',
				estimated: '186.21068575863267',
			},
			availableVolume: {
				currencyCode: 'TON',
				amount: '4000.000000000',
			},
			orderAmountLimits: {
				currencyCode: 'RUB',
				min: '100',
				max: '744842.74',
				approximate: false,
			},
			orderVolumeLimits: {
				currencyCode: 'TON',
				min: '0.537026108',
				max: '4000',
				approximate: true,
			},
			paymentMethods: [
				{
					code: 'sbp',
					name: 'СБП',
					originNameLocale: 'ru',
					nameEng: 'SBP',
				},
				{
					code: 'alfabank',
					name: 'Альфа-Банк',
					originNameLocale: 'ru',
					nameEng: 'Alfa-Bank',
				},
				{
					code: 'yoomoney',
					name: 'ЮMoney',
					originNameLocale: 'ru',
					nameEng: 'YooMoney',
				},
				{
					code: 'vtbbankru',
					name: 'ВТБ',
					originNameLocale: 'ru',
					nameEng: 'VTB',
				},
				{
					code: 'qiwi',
					name: 'QIWI',
					originNameLocale: 'ru',
					nameEng: 'QIWI',
				},
			],
		},
		{
			id: 168521,
			number: 'AB-00168521',
			status: 'ACTIVE',
			type: 'PURCHASE',
			price: {
				type: 'FLOATING',
				baseCurrencyCode: 'BTC',
				quoteCurrencyCode: 'RUB',
				value: '90',
				estimated: '2919784.62529030896',
			},
			availableVolume: {
				currencyCode: 'BTC',
				amount: '0.25000000',
			},
			orderAmountLimits: {
				currencyCode: 'RUB',
				min: '100',
				max: '729946.15',
				approximate: false,
			},
			orderVolumeLimits: {
				currencyCode: 'BTC',
				min: '0.00003424',
				max: '0.25',
				approximate: true,
			},
			paymentMethods: [
				{
					code: 'rosbank',
					name: 'Росбанк',
					originNameLocale: 'ru',
					nameEng: 'Rosbank',
				},
				{
					code: 'raiffeisenru',
					name: 'Райффайзен Банк',
					originNameLocale: 'ru',
					nameEng: 'Raiffeisen Bank',
				},
				{
					code: 'sberbankru',
					name: 'Сбербанк',
					originNameLocale: 'ru',
					nameEng: 'Sberbank',
				},
				{
					code: 'tinkoff',
					name: 'Тинькофф',
					originNameLocale: 'ru',
					nameEng: 'Tinkoff',
				},
				{
					code: 'mts',
					name: 'МТС-банк',
					originNameLocale: 'ru',
					nameEng: 'MTS-bank',
				},
			],
		},
		{
			id: 168519,
			number: 'AB-00168519',
			status: 'ACTIVE',
			type: 'PURCHASE',
			price: {
				type: 'FLOATING',
				baseCurrencyCode: 'BTC',
				quoteCurrencyCode: 'RUB',
				value: '90',
				estimated: '2919784.62529030896',
			},
			availableVolume: {
				currencyCode: 'BTC',
				amount: '0.25000000',
			},
			orderAmountLimits: {
				currencyCode: 'RUB',
				min: '100',
				max: '729946.15',
				approximate: false,
			},
			orderVolumeLimits: {
				currencyCode: 'BTC',
				min: '0.00003424',
				max: '0.25',
				approximate: true,
			},
			paymentMethods: [
				{
					code: 'sbp',
					name: 'СБП',
					originNameLocale: 'ru',
					nameEng: 'SBP',
				},
				{
					code: 'alfabank',
					name: 'Альфа-Банк',
					originNameLocale: 'ru',
					nameEng: 'Alfa-Bank',
				},
				{
					code: 'yoomoney',
					name: 'ЮMoney',
					originNameLocale: 'ru',
					nameEng: 'YooMoney',
				},
				{
					code: 'vtbbankru',
					name: 'ВТБ',
					originNameLocale: 'ru',
					nameEng: 'VTB',
				},
				{
					code: 'qiwi',
					name: 'QIWI',
					originNameLocale: 'ru',
					nameEng: 'QIWI',
				},
			],
		},
		{
			id: 168487,
			number: 'AB-00168487',
			status: 'ACTIVE',
			type: 'PURCHASE',
			price: {
				type: 'FLOATING',
				baseCurrencyCode: 'USDT',
				quoteCurrencyCode: 'RUB',
				value: '92',
				estimated: '85.815170401509322',
			},
			availableVolume: {
				currencyCode: 'USDT',
				amount: '10000.000000',
			},
			orderAmountLimits: {
				currencyCode: 'RUB',
				min: '100',
				max: '858151.7',
				approximate: false,
			},
			orderVolumeLimits: {
				currencyCode: 'USDT',
				min: '1.165295',
				max: '10000',
				approximate: true,
			},
			paymentMethods: [
				{
					code: 'rosbank',
					name: 'Росбанк',
					originNameLocale: 'ru',
					nameEng: 'Rosbank',
				},
				{
					code: 'raiffeisenru',
					name: 'Райффайзен Банк',
					originNameLocale: 'ru',
					nameEng: 'Raiffeisen Bank',
				},
				{
					code: 'sberbankru',
					name: 'Сбербанк',
					originNameLocale: 'ru',
					nameEng: 'Sberbank',
				},
				{
					code: 'tinkoff',
					name: 'Тинькофф',
					originNameLocale: 'ru',
					nameEng: 'Tinkoff',
				},
				{
					code: 'mts',
					name: 'МТС-банк',
					originNameLocale: 'ru',
					nameEng: 'MTS-bank',
				},
			],
		},
		{
			id: 138468,
			number: 'AB-00138468',
			status: 'ACTIVE',
			type: 'PURCHASE',
			price: {
				type: 'FLOATING',
				baseCurrencyCode: 'USDT',
				quoteCurrencyCode: 'RUB',
				value: '93',
				estimated: '86.7479439928300755',
			},
			availableVolume: {
				currencyCode: 'USDT',
				amount: '10000.000000',
			},
			orderAmountLimits: {
				currencyCode: 'RUB',
				min: '100',
				max: '867479.43',
				approximate: false,
			},
			orderVolumeLimits: {
				currencyCode: 'USDT',
				min: '1.152765',
				max: '10000',
				approximate: true,
			},
			paymentMethods: [
				{
					code: 'sbp',
					name: 'СБП',
					originNameLocale: 'ru',
					nameEng: 'SBP',
				},
				{
					code: 'alfabank',
					name: 'Альфа-Банк',
					originNameLocale: 'ru',
					nameEng: 'Alfa-Bank',
				},
				{
					code: 'yoomoney',
					name: 'ЮMoney',
					originNameLocale: 'ru',
					nameEng: 'YooMoney',
				},
				{
					code: 'vtbbankru',
					name: 'ВТБ',
					originNameLocale: 'ru',
					nameEng: 'VTB',
				},
				{
					code: 'qiwi',
					name: 'QIWI',
					originNameLocale: 'ru',
					nameEng: 'QIWI',
				},
			],
		},
	];
	const arrPayTypes = await PayType.find();

	return res.status(200).json({
		success: arrData.length !== 0 ? true : false,
		data: {
			// merchantAdvs: [],
			merchantAdvs:
				arrData.length !== 0
					? getMerchantAdvsNomalized(
							arrData,
							{
								userId,
								exchangeId,
								prefix: shortName,
							},
							arrPayTypes
					  )
					: [],
			userPayMethods: [],
		},
		message:
			arrData.length !== 0
				? `${shortName}: ${TEXT_CONSTANTS.USER_ADVS_OK}`
				: `${shortName}: ${TEXT_CONSTANTS.USER_ADVS_ER}`,
	});
});

// изменение статуса объявления (-ий) мерчанта
ordersRouter_XG.post('/adv-status', async (req, res) => {
	const axiosRequestConfig = {
		withCredentials: true,
		method: CHANGE_STATUS_ADVS.method,
		url: CHANGE_STATUS_ADVS.url,
		data: {
			adNos: req.body.adNos,
			adStatus: req.body.adStatus,
		},
		headers: {
			'access-control-allow-credentials': true,
			'Access-Control-Allow-Origin': '*',
			'content-type': 'application/json;charset=UTF-8',
			c2ctype: 'c2c_merchant',
			clienttype: 'web',
			cookie: req.body.requestHeader.cookie,
			csrftoken: req.body.requestHeader.csrftoken,
			'device-info': req.body.requestHeader.deviceInfo,
			'user-agent': req.body.requestHeader.userAgent,
		},
	};
	await axios(axiosRequestConfig)
		.then((response) => {
			// console.log(response.data)
			return res.status(200).json({
				success: true,
				data: response.data.data,
				arrayAdvNumbers: req.body.adNos,
				advStatus: req.body.adStatus,
			});
		})
		.catch((error) => {
			res.status(400).json({
				error,
				message: `${SHORT_NAME}: ${TEXT_CONSTANTS.ADV_STATUS_ER}`,
			});
		});
});

// получение редактируемого объявления мерчанта
ordersRouter_XG.post('/adv-edit', async (req, res) => {
	const headers = {
		'access-control-allow-credentials': true,
		'Access-Control-Allow-Origin': '*',
		'content-type': 'application/json;charset=UTF-8',
		c2ctype: 'c2c_merchant',
		clienttype: 'web',
		cookie: req.body.requestHeader.cookie,
		csrftoken: req.body.requestHeader.csrftoken,
		'device-info': req.body.requestHeader.deviceInfo,
		'user-agent': req.body.requestHeader.userAgent,
	};

	const advEditRequestConfig = {
		withCredentials: true,
		method: GET_ADV_DETAIL.method,
		url: GET_ADV_DETAIL.url,
		data: { adNo: req.body.advIdNumber },
		headers,
	};

	const p2pBalanceRequestConfig = {
		withCredentials: true,
		method: GET_P2P_BALANCE.method,
		url: GET_P2P_BALANCE.url,
		data: { needBtcValuation: true },
		headers,
	};

	const userPayRequestConfig = {
		withCredentials: true,
		method: GET_MERCHANT_ADV_PAYMENTS.method,
		url: GET_MERCHANT_ADV_PAYMENTS.url,
		data: {},
		headers,
	};

	const userPayMethods = await getUserPayMethods(
		userPayRequestConfig,
		SHORT_NAME
	);
	const p2pBalance = await getBalance(
		p2pBalanceRequestConfig,
		GET_P2P_BALANCE,
		'P2P',
		null
	);

	await axios(advEditRequestConfig)
		.then((response) => {
			// console.log(response.data)
			return res.status(200).json({
				success: true,
				advDetails: response.data.data,
				userPayMethods,
				p2pBalance,
				tickers,
				message: `${SHORT_NAME}: ${TEXT_CONSTANTS.ADV_EDIT_OK}`,
			});
		})
		.catch((error) => {
			res.status(400).json({
				error,
				message: `${SHORT_NAME}: ${TEXT_CONSTANTS.ADV_EDIT_ER}`,
			});
		});
});

// обновление редактируемого объявления
ordersRouter_XG.post('/adv-update', async (req, res) => {
	const headers = {
		'access-control-allow-credentials': true,
		'Access-Control-Allow-Origin': '*',
		'content-type': 'application/json;charset=UTF-8',
		c2ctype: 'c2c_merchant',
		clienttype: 'web',
		cookie: req.body.requestHeader.cookie,
		csrftoken: req.body.requestHeader.csrftoken,
		'device-info': req.body.requestHeader.deviceInfo,
		'user-agent': req.body.requestHeader.userAgent,
	};

	const advUpdateRequestConfig = {
		withCredentials: true,
		method: UPDATE_DETAILS_ADV.method,
		url: UPDATE_DETAILS_ADV.url,
		data: req.body.advDetails,
		headers,
	};

	const getAdvsRequestConfig = {
		withCredentials: true,
		method: GET_MERCHANT_ADVS.method,
		url: GET_MERCHANT_ADVS.url,
		data: {
			page: req.body.objOrder.page,
			rows: req.body.objOrder.rows,
			inDeal: 1,
		},
		headers,
	};

	const p2pOrdersParams = {
		quantityPages: +req.body.objOrder.quantityPages / 20,
		payloadOrders: {
			page: req.body.objOrder.page,
			rows: req.body.objOrder.rows,
			fiat: req.body.objOrder.fiat,
			asset: req.body.objOrder.asset,
			tradeType: req.body.objOrder.tradeType,
			transAmount: req.body.objOrder.transAmount,
			payTypes: req.body.objOrder.payTypeList,
		},
	};

	const isAdvUpdated = await getResultAdvUpdate(
		advUpdateRequestConfig,
		SHORT_NAME
	);
	const p2pOrders = [];
	const merchantAdvs = await getMerchantAdvs(
		getAdvsRequestConfig,
		SHORT_NAME
	);

	if (isAdvUpdated) {
		return res.status(200).json({
			success: true,
			data: {
				merchantAdvs,
				p2pOrders,
				tickers,
			},
			message: `${SHORT_NAME}: ${TEXT_CONSTANTS.ADV_UPDATE_OK}`,
		});
	} else {
		res.status(400).json({
			message: `${SHORT_NAME}: ${TEXT_CONSTANTS.ADV_UPDATE_ER}`,
		});
	}
});

// получение массива p2p-ордеров стакана
ordersRouter_XG.post('/p2p', async (req, res) => {
	const { userId, exchangeName, exchangeId, shortName } = req.body;
	const {
		asset,
		fiat,
		arrPayments,
		sideType,
		rows,
		page,
		amount,
	} = req.body.objParams;
	const quantityPages = +req.body.objParams.quantityPages / 20;
	const arrPayTypes = await PayType.find();
	// const tradeType = sideType === 'BUY' ? 'SELL' : 'BUY';
	const paymentNames =
		arrPayments.length === 0
			? []
			: arrPayments.map((item, index) => {
					return getPayMethodPropsReverse(
						exchangeId,
						'payName', // payId or payName
						item, // internalPayMethod
						arrPayTypes
					);
			  });

	const params = {
		userId,
		prefix: shortName,
		config: {
			withCredentials: true,
			method: GET_P2P_ORDERS.method,
			url: GET_P2P_ORDERS.url,
			data: {
				asset,
				classifies: [],
				fiat,
				filter: { payTypes: [] },
				merchantCheck: false,
				page,
				// payTypes: paymentNames,
				payTypes: ['Tinkoff'],
				rows,
				tradeType: sideType,
				transAmount: amount,
			},
			headers: null,
		},
	};

	let arrData = [];
	for (let i = page; i <= quantityPages; i++) {
		params.config.data.page = i;
		const result = await getP2POrders(params);
		// console.log(params.config.url);
		arrData = arrData.concat(result);
	}

	return res.status(200).json({
		success: arrData.length !== 0 ? true : false,
		data: {
			// p2pOrders: [],
			p2pOrders:
				arrData.length !== 0
					? getP2POrdersNomalized(
							arrData,
							{
								userId,
								exchangeId,
								prefix: shortName,
							},
							arrPayTypes
					  )
					: [],
			tickers: await Ticker.find(),
		},
		message:
			arrData.length !== 0
				? `${shortName}: ${arrData.length} ${TEXT_CONSTANTS.P2P_ORDERS_OK}`
				: `${shortName}: ${TEXT_CONSTANTS.P2P_ORDERS_ER}`,
	});
});

// получение массива текущих merchant-ордеров
ordersRouter_XG.post('/merchant-orders', async (req, res) => {
	const { userId, exchangeId, shortName, objParams } = req.body;

	const user = await User.findOne({ _id: userId });

	const params = {
		userId,
		prefix: `otc_${shortName}`,
		apiKeys: getSingleUserProperty('apiKeys', exchangeId, user.properties),
		requestHeader: getSingleUserProperty(
			'requestHeader',
			exchangeId,
			user.properties
		),
		constants: CONSTANTS_XG,
		additionals: {},
	};

	const objReqParams = getObjectRequestParams(params);
	const arrData = await getMerchantOrders(objReqParams);
	// console.log(arrData);
	const arrPayTypes = await PayType.find();
	const arrOrderStatus = await OrderStatus.find();

	return res.status(200).json({
		success: arrData.length !== 0 ? true : false,
		// data: [],
		data:
			arrData.length !== 0
				? getMerchantOrdersNomalized(
						arrData,
						{
							userId,
							exchangeId,
							prefix: shortName,
						},
						arrPayTypes,
						arrOrderStatus
				  )
				: [],
		message:
			arrData.length !== 0
				? `${shortName}: ${arrData.length} ${TEXT_CONSTANTS.USER_ORDERS_OK}`
				: `${shortName}: ${TEXT_CONSTANTS.USER_ORDERS_ER}`,
	});
});

// получение сведений об мерчанте и его объявлениях по id
ordersRouter_XG.get('/merchant-details/:id', async (req, res) => {
	const merchantId = req.params.id;
	const axiosRequestConfig = {
		method: GET_MERCHANT_DETAILS.method,
		url: `${GET_MERCHANT_DETAILS.url}?userNo=${merchantId}`,
		data: null,
		headers: null,
	};
	await axios(axiosRequestConfig)
		.then((response) => {
			// console.log(response.data)
			return res.status(200).json({
				success: true,
				data: response.data.data,
				message: `${SHORT_NAME}: ${TEXT_CONSTANTS.USER_DETAILS_OK}`,
			});
		})
		.catch((error) => {
			res.status(400).json({
				error,
				message: `${SHORT_NAME}: ${TEXT_CONSTANTS.USER_DETAILS_ER}`,
			});
		});
});

// сохранение данных об merchant-ордере в БД по id
ordersRouter_XG.post('/save-user-orders', async (req, res) => {
	const arrTickers = await Ticker.find(); // тикеры и цены из БД
	let countOrder = 0;

	const { userId, orders, typeOrder, shortName, exchangeId } = req.body;

	// проверка наличия ордера в БД
	for (let i = 0; i < orders.length; i++) {
		if (orders[i].statusProps.value === 'Completed') {
			const result = await checkOrderInDB(
				userId,
				typeOrder,
				orders[i].orderId,
				shortName
			);

			// Если ордера нет в БД
			if (result.isUnique) {
				const params = {
					userId,
					shortName,
					exchangeId,
					arrTickers,
					orderDetails: orders[i], // нормализованный ордер from frontend
				};

				const newOrder = getOrderDetailsNomalized(params);
				// если newOrder не пустой объект - сохраняем в БД
				if (Object.keys(newOrder).length !== 0) {
					await insertOrderToDB(typeOrder, newOrder);
					// console.log(newOrder);
					++countOrder;
				}
			}
		}
	}

	// log print
	consoleProcessed(userId, shortName, orders, countOrder, typeOrder);

	return res.status(200).json({
		success: true,
		message: `${shortName}: ${countOrder} inserted`,
	});
});

// получение массива активных spot-ордеров
ordersRouter_XG.post('/spot-orders-active', async (req, res) => {
	const { userId, exchange, exchangeId, shortName } = req.body;
	const arrTickers = await Ticker.find();
	let status = 200;

	const user = await User.findOne({ _id: userId });
	const requestHeader = getSingleUserProperty(
		'requestHeader',
		exchange,
		user.properties
	);

	// проверям существуют ли куки на этом сервисе
	if (requestHeader.userAgent === '') {
		return res.status(status).json({
			success: true,
			message: `${shortName}: requestHeader is empty`,
			spotOrders: [],
			tickers: await Ticker.find(),
		});
	}

	const objParams = {
		userId,
		prefix: `active_${shortName}`,
		// apiKeys,
		requestHeader,
		constants: CONSTANTS_XG,
		additionals: {},
	};

	const objReqParams = getObjectRequestParams(objParams);
	const arrActiveSpots = await getSpotOrders(objReqParams);

	return res.status(status).json({
		success: arrActiveSpots.length === 0 ? false : true,
		message:
			arrActiveSpots.length === 0
				? `${shortName}: ${TEXT_CONSTANTS.SPOT_ORDERS_ER}`
				: `${shortName}: ${arrActiveSpots.length} ${TEXT_CONSTANTS.SPOT_ORDERS_OK}`,
		spotOrders:
			arrActiveSpots.length === 0
				? []
				: getSpotOrdersNomalized(
						arrActiveSpots,
						{
							userId,
							shortName,
							exchangeId,
							flag: 'active_XG',
						},
						arrTickers
				  ),
		tickers: await Ticker.find(),
	});
});

// сохранение spot-ордеров в БД
ordersRouter_XG.post('/spot-orders-history', async (req, res) => {
	let message;
	let success = true;
	let status = 200;
	let countOrder = 0;
	const {
		userId,
		exchange,
		exchangeId,
		shortName,
		typeOrder,
		params,
	} = req.body;

	const user = await User.findOne({ _id: userId });
	const requestHeader = getSingleUserProperty(
		'requestHeader',
		exchange,
		user.properties
	);

	const objParams = {
		userId,
		prefix: `history_${shortName}`,
		// apiKeys,
		requestHeader,
		constants: CONSTANTS_XG,
		additionals: {},
	};

	const objReqParams = getObjectRequestParams(objParams);
	const spotArray = await getSpotOrders(objReqParams);

	const arrTickers = await Ticker.find();
	// const spotOrders = [];
	const spotOrders = getSpotOrdersNomalized(
		spotArray,
		{
			userId,
			shortName,
			exchangeId,
			flag: `history_${shortName}`,
		},
		arrTickers
	);

	if (spotOrders.length !== 0) {
		// проверка наличия ордера в БД
		for (let i = 0; i < spotOrders.length; i++) {
			const result = await checkOrderInDB(
				spotOrders[i].userId,
				typeOrder,
				spotOrders[i].orderId,
				spotOrders[i].exchange
			);

			// Если ордера нет в БД вставляем
			if (result.isUnique) {
				// если newSpotOrder не пустой объект - сохраняем в БД
				if (Object.keys(spotOrders[i]).length !== 0) {
					await insertOrderToDB('SPOT', spotOrders[i]);
					// console.log(
					// 	`${countOrder} | tradeIdStr: ${spotOrders[i].tradeIdStr} inserted`
					// );
					++countOrder;
				}
			}
			// else console.log(`Order ${spotOrders[i].orderId} is not Unique`);
		}
		if (countOrder === 0) {
			success = false;
			message = `${SHORT_NAME}: ${countOrder} | ${TEXT_CONSTANTS.SPOT_ORDERS_DB_NO}`;
		} else {
			success = true;
			message = `${SHORT_NAME}: ${countOrder} | ${TEXT_CONSTANTS.SPOT_ORDERS_DB_OK}`;
		}
	} else {
		success = false;
		message = `${SHORT_NAME}: ${TEXT_CONSTANTS.SPOT_ORDERS_ER}`;
	}

	// log print
	consoleProcessed(userId, shortName, spotOrders, countOrder, typeOrder);

	return res.status(status).json({
		success,
		message,
	});
});
