<script lang='ts' setup>
import { tradeWebSocket } from "@/tradingview/websocket";

interface Item {
  asks: Array<{
    price: string;
    size: string;
  }>;
  bids: Array<{
    price: string;
    size: string;
  }>;
}

const props = defineProps<{ symbol: string }>();

const { t } = useI18n();
const data = ref<Item>({
  asks: [],
  bids: [],
});

// 计算买单和卖单的最大数量，用于计算占比
const maxBidAmount = computed(() => {
  if (!data.value?.bids)
    return 0;
  return Math.max(...data.value.bids.map(item => Number(item.price)));
});

const maxAskAmount = computed(() => {
  if (!data.value?.asks)
    return 0;
  return Math.max(...data.value.asks.map(item => Number(item.price)));
});

// 计算每个订单的占比百分比
function getBidPercentage(amount: string) {
  const num = Number(amount);
  return maxBidAmount.value > 0 ? (num / maxBidAmount.value) * 100 : 0;
}

function getAskPercentage(amount: string) {
  const num = Number(amount);
  return maxAskAmount.value > 0 ? (num / maxAskAmount.value) * 100 : 0;
}

// 格式化价格
function formatPrice(price: string) {
  return Number(price).toFixed(2);
}

// 格式化数量
function formatAmount(amount: string) {
  return Number(amount).toFixed(4);
}
function subscribe() {
  tradeWebSocket.subscribeChannel([{
    name: "depth",
    symbol: props.symbol,
  }]);
}
function unsubscribe() {
  useTimeoutFn(() => {
    console.log("unsubscribe order book: ", props.symbol);
    tradeWebSocket.unsubscribeChannel([{
      name: "depth",
      symbol: props.symbol,
    }]);
  }, 3000);
}

// 监听订单簿更新
tradeWebSocket.subscribe((message) => {
  if ("bids" in message.data) {
    if (!data.value?.bids.length) {
      data.value.bids = [];
    }
    const bids = message.data.bids.sort((a, b) => Number(b.price) - Number(a.price));

    data.value.bids.unshift(...bids);
    data.value.bids = data.value.bids.slice(0, 5);
  }
  if ("asks" in message.data) {
    if (!data.value?.asks.length) {
      data.value.asks = [];
    }
    const asks = message.data.asks.sort((a, b) => Number(b.price) - Number(a.price));

    data.value.asks.unshift(...asks);
    data.value.asks = data.value.asks.slice(0, 5);
  }
});

watch(() => props.symbol, (newSymbol, oldSymbol) => {
  if (newSymbol === oldSymbol)
    return;
  unsubscribe();
  subscribe();
});

onMounted(() => {
  subscribe();
});

onUnmounted(() => {
  unsubscribe();
});
</script>

<template>
  <div class="h-full w-full overflow-hidden bg-(--ion-background-color)">
    <div class="grid h-full grid-cols-2 gap-0.5">
      <!-- 买单区域 (Bids) -->
      <div class="flex flex-col">
        <!-- 标题 -->
        <div class="grid grid-cols-2 gap-2 border-b border-(--ion-border-color) px-3 py-2 text-xs text-(--ion-color-medium)">
          <div class="text-left">
            {{ t("tradeTokenized.orderBook.price") }}
          </div>
          <div class="text-right">
            {{ t("tradeTokenized.orderBook.quantity") }}
          </div>
        </div>

        <!-- 买单列表 -->
        <div class="flex-1 overflow-y-auto">
          <div
            v-for="(bid, index) in data?.bids"
            :key="index"
            class="relative grid grid-cols-2 gap-2 px-3 py-1 text-xs"
          >
            <!-- 背景色显示占比 -->
            <div
              class="absolute inset-y-0 right-0 bg-(--ion-color-success)/10"
              :style="{ width: `${getBidPercentage(bid.price)}%` }"
            />

            <!-- 价格 -->
            <div class="relative z-1 text-left text-(--ion-color-success)">
              {{ formatPrice(bid.price) }}
            </div>

            <!-- 数量 -->
            <div class="relative z-1 text-right text-(--ion-color-step-600)">
              {{ formatAmount(bid.size) }}
            </div>
          </div>
        </div>
      </div>

      <!-- 卖单区域 (Asks) -->
      <div class="flex flex-col">
        <!-- 标题 -->
        <div class="grid grid-cols-2 gap-2 border-b border-(--ion-border-color) px-3 py-2 text-xs text-(--ion-color-medium)">
          <div class="text-left">
            {{ t("tradeTokenized.orderBook.price") }}
          </div>
          <div class="text-right">
            {{ t("tradeTokenized.orderBook.quantity") }}
          </div>
        </div>

        <!-- 卖单列表 -->
        <div class="flex-1 overflow-y-auto">
          <div
            v-for="(ask, index) in data?.asks"
            :key="index"
            class="relative grid grid-cols-2 gap-2 px-3 py-1 text-xs"
          >
            <!-- 背景色显示占比 -->
            <div
              class="absolute inset-y-0 right-0 bg-(--ion-color-danger)/10"
              :style="{ width: `${getAskPercentage(ask.price)}%` }"
            />

            <!-- 价格 -->
            <div class="relative z-1 text-left text-(--ion-color-danger)">
              {{ formatPrice(ask.price) }}
            </div>

            <!-- 数量 -->
            <div class="relative z-1 text-right text-(--ion-color-step-600)">
              {{ formatAmount(ask.size) }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang='css' scoped></style>
