import * as React from "react"
import { CONSTANTS } from "../constants"
import { getUrlIcon } from "../common"

interface IReportCost {
	reportMerchantOrders: any;
	reportSpotOrders: any;
	activeSpotOrders: any;
}

export const ReportCost: React.FC<IReportCost> = props => {
	const { reportMerchantOrders, reportSpotOrders, activeSpotOrders } = props

	const [stateCost, handlerGetCost] = React.useState(false)

	// получение суммы ордеров и их количества по наименованию крипты и банку
	const getSummOrdersByNameField = (
		byNameField: string,
		ordersArray: any,
		tradeType: string,
		field: any
	) => {
		let quantity = 0
		let sumAmount = 0
		let vol = 0
		if (ordersArray.length !== 0) {
			for (let i = 0; i < ordersArray.length; i++) {
				if (byNameField === "OTC_BUY") {
					if (
						field === ordersArray[i]["asset"] &&
						tradeType === ordersArray[i]["tradeType"]
					) {
						sumAmount += +ordersArray[i]["amount"]
						vol += +ordersArray[i]["volume"]
						quantity++
					}
				} else if (byNameField === "OTC_SELL") {
					if (
						field === ordersArray[i]["asset"] &&
						tradeType === ordersArray[i]["tradeType"]
					) {
						sumAmount += +ordersArray[i]["amount"]
						vol += +ordersArray[i]["volume"]
						quantity++
					}
				} else if (byNameField === "SPOT_SELL_hist") {
					const baseAsset = ordersArray[i].baseAsset
					const quoteAsset = ordersArray[i].quoteAsset
					if (
						field === baseAsset &&
						tradeType === ordersArray[i]["sideType"] &&
						(quoteAsset === "USDT" || quoteAsset === "BUSD")
					) {
						sumAmount += +ordersArray[i]["volume"] * +ordersArray[i]["price"]
						vol += +ordersArray[i]["volume"]
						quantity++
					}
				} else if (byNameField === "SPOT_SELL_actv") {
					if (
						field === ordersArray[i]["baseAsset"] &&
						tradeType === ordersArray[i]["sideType"] &&
						(ordersArray[i]["quoteAsset"] === "USDT" ||
							ordersArray[i]["quoteAsset"] === "BUSD")
					) {
						sumAmount += +ordersArray[i]["volume"] * +ordersArray[i]["price"]
						vol += +ordersArray[i]["volume"]
						quantity++
					}
				}
			}
		}
		return { sumOrders: sumAmount, trades: quantity, volume: vol }
	}

	// получаем массив уникальных значений
	const getArrayUniqueValues = (nameField: string, ordersArray: any) => {
		const commonArray = []
		for (let i = 0; i < ordersArray.length; i++) {
			commonArray.push(ordersArray[i][nameField])
		}
		const uniqueItems = Array.from(new Set(commonArray))
		return uniqueItems
	}

	// расчет P&L
	const getProfitLossByAsset = (
		buyPrice: any,
		sellPrice: any,
		volume: any
	) => {
		const result = isNaN((sellPrice - buyPrice) * volume)
			? 0
			: (sellPrice - buyPrice) * volume
		return result
	}

	// paсчет маржи
	const getMarginByAsset = (pl: any, amount: any) => {
		const result = (pl * 100) / amount
		return result
	}

	// получаем массив уникальных значений нименований крипты
	const arrayAssets = getArrayUniqueValues("asset", reportMerchantOrders)
	const symbolRUB = getUrlIcon("FiatSymbol", "RUB")
	const symbolUSD = getUrlIcon("FiatSymbol", "USD")

	// OTC-SELL-USDT closed orders
	const objOTC_SELL_USDT = getSummOrdersByNameField(
		"OTC_SELL",
		reportMerchantOrders,
		"SELL",
		"USDT"
	)
	// средняя цена продажи USDT OTC
	const avPrice_SELL_USDT =
		objOTC_SELL_USDT.sumOrders / objOTC_SELL_USDT.volume

	let totalOTC_Amount = 0
	let sumTotal_VolumeUSDT = 0
	let totalProfitLoss = 0
	let OTC_Trades = 0
	let SPOT_Trades = 0

	const listItems: any =
		arrayAssets.length === 0 || stateCost ? (
			<tr>
				<td colSpan={10}>{CONSTANTS.ERROR_TEXT}</td>
			</tr>
		) : (
			arrayAssets.map((item: any, index: number) => {
				// OTC-BUY closed orders
				const objOTC_ClOrs = getSummOrdersByNameField(
					"OTC_BUY",
					reportMerchantOrders,
					"BUY",
					item
				)

				// SPOT-SELL closed orders
				const objSPOT_ClOrs = getSummOrdersByNameField(
					"SPOT_SELL_hist",
					reportSpotOrders,
					"SELL",
					item
				)

				// SPOT-SELL open orders
				const objSPOT_OpOrs = getSummOrdersByNameField(
					"SPOT_SELL_actv",
					activeSpotOrders,
					"SELL",
					item
				)

				const SPOT_avPrice_hist =
					item === "USDT" ? 1 : objSPOT_ClOrs.sumOrders / objSPOT_ClOrs.volume
				const total_volumeUSDT_hist = objOTC_ClOrs.volume * SPOT_avPrice_hist
				const factCostRUBUSDT = isNaN(
					objOTC_ClOrs.sumOrders / total_volumeUSDT_hist
				)
					? 0
					: objOTC_ClOrs.sumOrders / total_volumeUSDT_hist

				const SPOT_avPrice_actv =
					item === "USDT" ? 1 : objSPOT_OpOrs.sumOrders / objSPOT_OpOrs.volume
				const total_volumeUSDT_actv = objOTC_ClOrs.volume * SPOT_avPrice_actv
				const awaitCostRUBUSDT = isNaN(
					objOTC_ClOrs.sumOrders / total_volumeUSDT_actv
				)
					? 0
					: objOTC_ClOrs.sumOrders / total_volumeUSDT_actv

				const SPOT_SELL_avPrice = isNaN(SPOT_avPrice_hist)
					? SPOT_avPrice_actv
					: SPOT_avPrice_hist
				const total_SELL_volumeUSDT = isNaN(total_volumeUSDT_hist)
					? total_volumeUSDT_actv
					: total_volumeUSDT_hist

				const buyPrice = isNaN(factCostRUBUSDT)
					? awaitCostRUBUSDT
					: factCostRUBUSDT
				const profitLoss = getProfitLossByAsset(
					buyPrice,
					avPrice_SELL_USDT,
					total_SELL_volumeUSDT
				)
				const margin = getMarginByAsset(profitLoss, objOTC_ClOrs.sumOrders)

				// totalOTC_Amount += objOTC_ClOrs.sumOrders
				// =======================================
				totalOTC_Amount =
					item === "RUB"
						? totalOTC_Amount + 0
						: totalOTC_Amount + objOTC_ClOrs.sumOrders
				// =======================================

				sumTotal_VolumeUSDT = isNaN(total_SELL_volumeUSDT)
					? sumTotal_VolumeUSDT + 0
					: sumTotal_VolumeUSDT + total_SELL_volumeUSDT
				totalProfitLoss += profitLoss
				OTC_Trades += objOTC_ClOrs.trades
				SPOT_Trades += objSPOT_ClOrs.trades

				let classBGtradeType = "warning"
				if (profitLoss > 0) classBGtradeType = "success"
				else if (profitLoss < 0) classBGtradeType = "danger"

				return (
					<tr key={index}>
						<td>{index + 1}</td>
						<td>
							<span className="icon-pay-dots">
								<img
									src={getUrlIcon("iconCurrencyByName", item)}
									className="mr-1"
									alt="-"
									title={item}
								/>
								{item}
							</span>
						</td>
						<td>{`${symbolRUB} ${objOTC_ClOrs.sumOrders.toFixed(2)} (${
							objOTC_ClOrs.trades
						})`}</td>
						<td>{`${symbolRUB} ${(
							objOTC_ClOrs.sumOrders / objOTC_ClOrs.volume
						).toFixed(item === "SHIB" ? 5 : 2)}`}</td>
						<td>
							{item === "USDT" ||
							item === "USDC" ||
							item === "BUSD" ||
							item === "DAI" ||
							item === "DASH" ||
							item === "XRP" ||
							item === "EOS" ||
							item === "HT" ||
							item === "SHIB" ||
							item === "GMT" ||
							item === "RUB"
								? objOTC_ClOrs.volume.toFixed(2)
								: objOTC_ClOrs.volume.toFixed(5)}
						</td>
						<td>
							{isNaN(SPOT_SELL_avPrice)
								? "---"
								: symbolUSD +
								  "  " +
								  SPOT_SELL_avPrice.toFixed(item === "SHIB" ? 5 : 2)}
						</td>
						<td>
							{isNaN(total_SELL_volumeUSDT)
								? "---"
								: `${symbolUSD} ${total_SELL_volumeUSDT.toFixed(2)} (${
										objSPOT_ClOrs.trades
								  })`}
						</td>
						<td>
							<span>
								{factCostRUBUSDT === 0
									? "--- |"
									: `${symbolUSD} ${factCostRUBUSDT.toFixed(2)} |`}
							</span>
							<span>
								{awaitCostRUBUSDT === 0
									? " ---"
									: ` ${symbolUSD} ${awaitCostRUBUSDT.toFixed(2)}`}
							</span>
						</td>
						<td>{margin === 0 ? "---" : margin.toFixed(2) + " %"}</td>
						<td
							style={profitLoss === 0 ? { color: "black" } : { color: "white" }}
							className={`table-${classBGtradeType}`}
						>
							{profitLoss === 0 ? "---" : `${symbolRUB} ${profitLoss.toFixed(2)}`}
						</td>
					</tr>
				)
			})
		)

	return (
		<div className="row">
			<table className="table table-hover table-striped table-sm">
				<thead>
					<tr>
						<th scope="col">#</th>
						<th scope="col">
							<button
								className="btn btn-outline-success btn-sm"
								onClick={() => {
									handlerGetCost(!stateCost)
								}}
							>
								Cost {stateCost ? "+" : "-"}
							</button>
						</th>
						<th scope="col" className="tbl-header">
							<span>OTC Amount</span>
							<span>Trades</span>
						</th>
						<th scope="col" className="tbl-header">
							<span>OTC_BUY</span>
							<span>Average Price</span>
						</th>
						<th scope="col">OTC Vol.</th>
						<th scope="col" className="tbl-header">
							<span>SPOT_SELL</span>
							<span>Average Price</span>
						</th>
						<th scope="col" className="tbl-header">
							<span>SPOT Vol.</span>
							<span>Trades</span>
						</th>
						<th scope="col" className="tbl-header">
							<span>Cost</span>
							<span>Fact | Await</span>
						</th>
						<th scope="col">Margin, %</th>
						<th scope="col">P&L</th>
					</tr>
				</thead>
				<tbody>{listItems}</tbody>
				<tfoot>
					<tr
						style={{
							backgroundColor: "lightskyblue",
							color: "black",
							fontWeight: "bold",
						}}
					>
						<td></td>
						<td>TOTAL:</td>
						<td>{`${symbolRUB} ${totalOTC_Amount.toFixed(
							2
						)} (${OTC_Trades})`}</td>
						<td colSpan={3} className="table-info">
							<span>OTC_avPrice_SELL_USDT:</span>
							<span style={{ color: "brown" }}>{`  ${avPrice_SELL_USDT.toFixed(
								2
							)}`}</span>
						</td>
						<td>{`${symbolUSD} ${sumTotal_VolumeUSDT.toFixed(
							2
						)} (${SPOT_Trades})`}</td>
						<td>{`${symbolUSD} ${(totalOTC_Amount / sumTotal_VolumeUSDT).toFixed(
							2
						)}`}</td>
						<td>
							{getMarginByAsset(totalProfitLoss, totalOTC_Amount).toFixed(2) +
								" %"}
						</td>
						<td>{`${symbolRUB} ${totalProfitLoss.toFixed(2)}`}</td>
					</tr>
				</tfoot>
			</table>
		</div>
	)
}
