<script setup lang="ts">
import { computed, ref } from "vue";

import type { MarketInsightData } from "../../../shared/api/market";
import DataTable from "../../../shared/components/DataTable.vue";
import EmptyState from "../../../shared/components/EmptyState.vue";
import { exportCsv, formatNumber, sortRows, type SortDirection } from "../../../shared/market/table";

const props = defineProps<{ data: MarketInsightData }>();
const dataset = ref<"focus" | "watchlist" | "all" | "one-price">("focus");
const expectation = ref("all");
const query = ref("");
const sortKey = ref("attention_score");
const sortDirection = ref<SortDirection>("desc");
const summary = computed(() => props.data.summary ?? {});
const phaseLabels = {
  pending: "待开始",
  observing: "观察中",
  selection: "筛选确认",
  finalized: "已归档",
  archive: "历史归档",
};
const sources = computed(() => ({
  focus: props.data.focus_rows ?? [],
  watchlist: props.data.watchlist_rows ?? [],
  all: props.data.rows ?? [],
  "one-price": props.data.one_price_rows ?? [],
}));
const rows = computed(() => {
  const normalized = query.value.trim().toLocaleLowerCase();
  const selected = sources.value[dataset.value].filter((row) => {
    if (expectation.value !== "all" && row.expectation !== expectation.value) return false;
    if (!normalized) return true;
    return [row.code, row.name, row.sector, row.source_label]
      .some((value) => String(value ?? "").toLocaleLowerCase().includes(normalized));
  });
  return sortRows(selected, sortKey.value, sortDirection.value);
});
const columns = [
  { key: "code", label: "代码", code: true, sortable: true },
  { key: "name", label: "股票", sortable: true },
  { key: "source_label", label: "候选身份", wide: true, sortable: true },
  { key: "sector", label: "板块", sortable: true },
  { key: "expectation", label: "预期", sortable: true },
  { key: "change", label: "竞价涨幅（%）", numeric: true, sortable: true, format: number },
  { key: "expected_change", label: "预期中枢（%）", numeric: true, sortable: true, format: number },
  { key: "attention_score", label: "关注分", numeric: true, sortable: true, format: oneDecimal },
  { key: "volume_ratio", label: "量比", numeric: true, sortable: true, format: number },
  { key: "amount_million", label: "竞价额（百万）", numeric: true, sortable: true, format: number },
];
const maxAmount = computed(() => Math.max(1, ...(props.data.amount_history ?? []).map((row) => Number(row.amount_billion ?? 0))));
const fiveDayAverage = computed(() => {
  const values = (props.data.amount_history ?? []).slice(-5).map((row) => Number(row.amount_billion ?? 0));
  return values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : 0;
});

function sort(key: string): void {
  if (sortKey.value === key) sortDirection.value = sortDirection.value === "asc" ? "desc" : "asc";
  else { sortKey.value = key; sortDirection.value = "desc"; }
}
function number(value: unknown): string { return formatNumber(value, 2); }
function oneDecimal(value: unknown): string { return formatNumber(value, 1); }
function download(): void {
  const lines = [["代码", "股票", "身份", "板块", "预期", "竞价涨幅（%）", "预期中枢（%）", "关注分", "量比", "竞价额（百万）"]];
  for (const row of rows.value) lines.push([
    String(row.code ?? ""), String(row.name ?? ""), String(row.source_label ?? ""),
    String(row.sector ?? ""), String(row.expectation ?? ""), String(row.change ?? ""),
    String(row.expected_change ?? ""), String(row.attention_score ?? ""),
    String(row.volume_ratio ?? ""), String(row.amount_million ?? ""),
  ]);
  exportCsv(`集合竞价-${props.data.trade_date}.csv`, lines);
}
</script>

<template>
  <header class="page-header market-page-header">
    <div><h1>集合竞价中心</h1><p class="page-subtitle">{{ phaseLabels[data.phase ?? "archive"] }} · 数据日期 {{ data.trade_date }}</p></div>
    <span class="tag" :class="{ warning: !data.current_available }">{{ data.message || `竞价覆盖 ${Number(data.coverage ?? 0) * 100}%` }}</span>
  </header>
  <section class="auction-layout">
    <article class="card auction-main">
      <div class="auction-dataset-bar">
        <div class="seg-control auction-datasets">
          <button type="button" :class="{ active: dataset === 'focus' }" @click="dataset = 'focus'">重点异动 <b>{{ data.focus_rows?.length ?? 0 }}</b></button>
          <button type="button" :class="{ active: dataset === 'watchlist' }" @click="dataset = 'watchlist'">我的自选 <b>{{ data.watchlist_rows?.length ?? 0 }}</b></button>
          <button type="button" :class="{ active: dataset === 'all' }" @click="dataset = 'all'">全部候选 <b>{{ data.rows?.length ?? 0 }}</b></button>
          <button type="button" :class="{ active: dataset === 'one-price' }" @click="dataset = 'one-price'">竞价一字 <b>{{ data.one_price_rows?.length ?? 0 }}</b></button>
        </div>
        <dl class="auction-inline-summary">
          <div><dt>竞价覆盖</dt><dd>{{ summary.stock_count ?? 0 }}</dd></div>
          <div><dt>重点异动</dt><dd>{{ summary.focus_count ?? 0 }}</dd></div>
          <div><dt>竞价一字</dt><dd>{{ summary.one_price_count ?? 0 }}</dd></div>
          <div><dt>竞价成交额</dt><dd>{{ number(summary.amount_billion) }} 亿</dd></div>
        </dl>
      </div>
      <div class="auction-toolbar">
        <div class="seg-control">
          <button v-for="item in [['all','全部'],['超预期','超预期'],['符合预期','符合预期'],['低于预期','低于预期']]" :key="item[0]" type="button" :class="{ active: expectation === item[0] }" @click="expectation = item[0]">{{ item[1] }}</button>
        </div>
        <label class="search-control"><span>搜索</span><input v-model="query" type="search" placeholder="代码、名称或板块"></label>
        <button class="btn btn-small" type="button" @click="download">导出 CSV</button>
      </div>
      <DataTable v-if="rows.length" :columns="columns" :rows="rows" :sort-key="sortKey" :sort-direction="sortDirection" @sort="sort" />
      <EmptyState v-else title="没有符合条件的竞价候选" :description="dataset === 'watchlist' ? '当前账号还没有可用的自选竞价结果。' : '调整预期筛选或搜索条件后再查看。'" />
    </article>
    <aside class="auction-side">
      <article class="card"><header class="card-header"><h2>题材承接</h2><span class="faint">昨日强势方向</span></header><div class="auction-evidence-list"><div v-for="item in data.themes?.carry ?? []" :key="String(item.name)"><strong>{{ item.name }}</strong><span>{{ item.status }}</span><small>{{ item.matched_count }}只 · 中位 {{ item.median_change ?? '' }}%</small></div><p v-if="!data.themes?.carry?.length" class="faint">暂无可核验承接结果</p></div></article>
      <article class="card"><header class="card-header"><h2>今日新线索</h2></header><div class="auction-evidence-list"><div v-for="item in data.themes?.new_themes ?? []" :key="String(item.name)"><strong>{{ item.name }}</strong><span>{{ item.stock_count }}只</span><small>{{ (item.leaders as string[])?.join('、') }}</small></div><p v-if="!data.themes?.new_themes?.length" class="faint">尚未形成新的聚集方向</p></div></article>
      <article class="card auction-amount-card"><header class="card-header"><h2>竞价成交额对比</h2><span class="faint">5日均值 {{ fiveDayAverage.toFixed(2) }} 亿</span></header><div class="auction-bars"><div v-for="item in data.amount_history ?? []" :key="String(item.trade_date)"><span>{{ String(item.trade_date).slice(5) }}</span><i><b :style="{ width: `${Number(item.amount_billion ?? 0) / maxAmount * 100}%` }"></b></i><strong>{{ number(item.amount_billion) }}</strong></div></div></article>
    </aside>
  </section>
</template>
