<template>
  <div class="option-chain-container">
    <div class="header-tabs">
      <div
        v-for="tab in tabs"
        :key="tab.key"
        class="tab-item"
        :class="{ active: currentTab === tab.key }"
        @click="switchTab(tab.key)"
      >
        {{ tab.name }}
        <span v-if="currentTab === tab.key" class="active-line"></span>
      </div>

      <div class="header-icons" @click="showSettings = true">
        <span><img src="@/assets/icon/bitcoin/lanweishezhi.svg" alt="设置"></span>
      </div>
      <div class="header-icons">
        <span><img src="@/assets/icon/bitcoin/shizhong.svg" alt="时钟"></span>
      </div>
    </div>

    <div class="date-scroll-wrapper">
      <div
        v-for="(date, index) in dates"
        :key="index"
        class="date-item"
        :class="{ active: selectedDateIndex === index }"
        @click="selectedDateIndex = index"
      >
        {{ date }}
      </div>
    </div>

    <div class="market-info">
      <div class="index-price">
        <span>指数价格: 231581.5</span>
      </div>
      <div class="expiry-time">
        <span>到期时间: 04:11:50</span>
      </div>
    </div>

    <div class="fs12" v-if="currentTab === 't-quote'" style="display: flex; justify-content: space-between; padding: 0 15px;">
      <span class="text-green" style="font-weight: 600;">看涨期权</span>
      <span class="text-red" style="font-weight: 600;">看跌期权</span>
    </div>

    <div
      v-if="currentTab === 't-quote'"
      class="t-quote-scroll-wrapper"
      ref="tQuoteRef"
    >
      <ul class="t-quote-list">
        <li class="t-row t-header">
           <div class="side-block left">
             <span>卖价</span><span>标记价格</span><span>买价</span>
           </div>
           <div class="center-block sticky-center header-bg">行权价格</div>
           <div class="side-block right">
             <span>买价</span><span>标记价格</span><span>卖价</span>
           </div>
        </li>

        <li
          v-for="(item, index) in mockData"
          :key="index"
          class="t-row"
        >
          <div class="side-block left" :class="{ 'bg-tint-green': index < 5 }">
            <div class="cell">
              <span class="price text-red">{{ item.call_ask.val }}</span>
              <span class="sub">{{ item.call_ask.change }}</span>
            </div>
            <div class="cell">
              <span class="price">{{ item.call_mark.val }}</span>
              <span class="sub">{{ item.call_mark.change }}</span>
            </div>
            <div class="cell">
              <span class="price text-green">{{ item.call_bid.val }}</span>
              <span class="sub">{{ item.call_bid.change }}</span>
            </div>
          </div>

          <div class="center-block sticky-center">
            {{ item.strike }}
          </div>

          <div class="side-block right" :class="{ 'bg-tint-red': index >= 5 }">
            <div class="cell">
              <span class="price text-green">{{ item.put_bid.val }}</span>
              <span class="sub">{{ item.put_bid.change }}</span>
            </div>
            <div class="cell">
              <span class="price">{{ item.put_mark.val }}</span>
              <span class="sub">{{ item.put_mark.change }}</span>
            </div>
            <div class="cell">
              <span class="price text-red">{{ item.put_ask.val }}</span>
              <span class="sub">{{ item.put_ask.change }}</span>
            </div>
          </div>
        </li>
      </ul>
    </div>

    <div v-else class="table-wrapper">
      <table>
        <thead>
          <tr>
            <th
              v-for="(col, index) in standardColumns"
              :key="col.key"
              :class="[
                col.fixed ? 'sticky-col' : '',
                col.align || 'center'
              ]"
            >
              {{ col.label }}
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in mockData" :key="index" @click="router.push({ name: 'OptionTrading' })">
             <td
              v-for="col in standardColumns"
              :key="col.key"
              :class="[
                col.fixed ? 'sticky-col' : '',
                col.align || 'center',
              ]"
             >
               <div v-if="col.key === 'strike'" class="strike-cell">
                 {{ item[col.key] }}
                 <span class="arrow-icon">›</span>
               </div>
               <div v-else-if="col.isDual" >
                 <div :class="item[col.key].trend === 'up' ? 'text-green' : 'text-red'">
                   {{ item[col.key].val }}
                 </div>
                 <div class="sub-text">{{ item[col.key].change }}</div>
               </div>
               <div v-else>
                 {{ item[col.key] }}
               </div>
             </td>
          </tr>
        </tbody>
      </table>
    </div>

    <van-popup
      v-model:show="showSettings"
      position="bottom"
      round
      :style="{ height: '70%' }"
    >
      <ColumnSettings @update:columns="handleColumnChange" />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import { Popup as VanPopup } from 'vant';
import ColumnSettings from './ColumnSettings.vue'; // 确保路径正确
import { useRouter } from 'vue-router'
const router = useRouter()

// --- 1. 静态配置池：所有可用列的详细样式定义 ---
// key 必须与 ColumnSettings.vue 里传出来的 key 一致
const COLUMN_DEFINITIONS = {
  // 固定列
  strike: { label: '行权价格', key: 'strike', fixed: true, align: 'left', width: '90px' },

  // 数据列
  bid: { label: '买价', key: 'bid', isDual: true, align: 'right' },
  mark: { label: '标记价格', key: 'mark', isDual: true, align: 'right' },
  ask: { label: '卖价', key: 'ask', isDual: true, align: 'right' },
  position: { label: '仓位', key: 'position', align: 'center' },
  holding: { label: '持仓量', key: 'holding', align: 'right' }, // 注意：如果弹窗传的是 open_interest，下面逻辑里要做映射
  delta: { label: 'Delta', key: 'delta', align: 'right' },
  gamma: { label: 'Gamma', key: 'gamma', align: 'right' },
  // ... 其他可能的列定义 ...
  vega: { label: 'Vega', key: 'vega', align: 'right' },
  theta: { label: 'Theta', key: 'theta', align: 'right' },
};

// --- 2. 状态管理 ---
const showSettings = ref(false);
const currentTab = ref('all');
const selectedDateIndex = ref(0);
const tQuoteRef = ref(null);

// standardColumns 现在是响应式的，默认初始化显示一部分列
const standardColumns = ref([
  COLUMN_DEFINITIONS.strike,
  COLUMN_DEFINITIONS.bid,
  COLUMN_DEFINITIONS.mark,
  COLUMN_DEFINITIONS.ask,
  COLUMN_DEFINITIONS.position,
  COLUMN_DEFINITIONS.holding,
]);

// --- 3. 核心逻辑：处理列配置变更 ---
const handleColumnChange = (newSettings) => {
  // 1. 始终保持“行权价”在第一位
  const nextCols = [COLUMN_DEFINITIONS.strike];

  // 2. 遍历弹窗传回来的配置数组
  newSettings.forEach(setting => {
    if (setting.checked) {
      // 处理 Key 映射（例如弹窗里叫 open_interest，数据里叫 holding）
      // 这里假设简单处理：如果弹窗的 key 能在 DEFINITIONS 里找到就直接用
      // 实际项目中可以写 switch case 处理特殊映射

      let colKey = setting.key;
      if (colKey === 'open_interest') colKey = 'holding'; // 示例映射

      const colDef = COLUMN_DEFINITIONS[colKey];
      if (colDef) {
        nextCols.push(colDef);
      }
    }
  });

  // 3. 更新表格列，Vue 会自动重新渲染
  standardColumns.value = nextCols;
};

// --- 4. 其他数据与逻辑 ---
const tabs = [
  { name: '全部', key: 'all' },
  { name: '看涨', key: 'call' },
  { name: '看跌', key: 'put' },
  { name: 'T字报价', key: 't-quote' }
];
const dates = ['25-11-09', '25-11-10', '25-11-11', '25-11-12', '25-11-13'];

// 模拟数据生成
const mockData = Array.from({ length: 20 }).map((_, i) => {
  const strike = 100000 + (i * 50);
  const createPrice = (val, change, trend) => ({ val, change, trend });

  return {
    strike: strike,
    type: i % 2 === 0 ? '看跌' : '看涨',
    // 普通表格数据
    bid: createPrice('15.0', '12.2%', 'up'),
    ask: createPrice('12.5', '12.2%', 'down'),
    mark: createPrice('1688.3', '12.2%', 'up'),
    position: '--',
    holding: '2235.50',
    delta: '0.50',
    gamma: '0.02',
    vega: '0.1',
    theta: '-0.5',
    // T字报价数据
    call_ask: createPrice('12.5', '2.2%', 'down'),
    call_mark: createPrice('1688.3', '12.2%', 'up'),
    call_bid: createPrice('15.0', '12.2%', 'up'),
    put_bid: createPrice('14.0', '12.2%', 'up'),
    put_mark: createPrice('1688.3', '12.2%', 'up'),
    put_ask: createPrice('13.5', '12.2%', 'down'),
  };
});

const switchTab = (key) => {
  currentTab.value = key;
  if (key === 't-quote') {
    nextTick(() => {
      if (tQuoteRef.value) {
        const el = tQuoteRef.value;
        el.scrollLeft = (el.scrollWidth - el.clientWidth) / 2;
      }
    });
  }
};
</script>

<style scoped>
/* 全局基础 */
.option-chain-container { width: 100%; background: #fff; font-size: 12px; color: #1d2129;
  font-family: -apple-system, sans-serif; }
.text-green { color: #00b42a; } .text-red { color: #f53f3f; }
.sub-text { font-size: 10px;
  color: #86909c; margin-top: 2px; }

/* 头部 */
.header-tabs { display: flex; align-items: center; justify-content: space-between;
  padding: 0 15px; height: 44px; }
.tab-item { margin-right: 0px; font-weight: 600; color: #86909c; padding: 10px 0;
  position: relative; }
.tab-item.active { color: #1d2129; font-size: 16px; }
.active-line { position: absolute; bottom: 0; left: 50%; transform: translateX(-50%);
  width: 20px; height: 3px; background: #1d2129; border-radius: 2px; }
.header-icons { margin-left: 0; display: flex; gap: 12px; font-size: 18px; color: #86909c; }
.date-scroll-wrapper { display: flex; overflow-x: auto; padding: 10px 12px; gap: 20px;
  scrollbar-width: none; }
.market-info { display: flex; justify-content: space-between; padding: 0 15px ;
  color: #86909c; font-size: 11px; }

/* === 场景 A: T字报价 样式 === */
.t-quote-scroll-wrapper { width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch;
  position: relative; }
.t-quote-list { list-style: none; padding: 0; margin: 0; width: max-content; min-width: 100%; }

.t-row { display: flex; height: 52px; border-bottom: 1px solid #f7f8fa; }
.t-header { height: 30px; color: #86909c; font-size: 11px; background: #fff; }
.t-header .side-block { justify-content: space-around; background: #fff; }
.header-bg { background: #fff !important; }

.side-block { width: 210px; display: flex; align-items: center; }
.cell { flex: 1; display: flex; flex-direction: column; align-items: center;
  justify-content: center; white-space: nowrap; }
.price { font-size: 13px; font-weight: 500; }
.sub { font-size: 10px; color: #86909c; margin-top: 1px; }

.center-block { width: 90px; flex-shrink: 0; display: flex; align-items: center;
  justify-content: center; background-color: #f7f8fa; font-weight: 600; color: #4e5969; font-size: 14px; }
.sticky-center { position: sticky; left: calc(50vw - 45px); z-index: 10; border-left: 1px solid #fff;
  border-right: 1px solid #fff; }
.t-header .sticky-center { background: #fff; z-index: 20; }
.t-row:not(.t-header) .sticky-center { background-color: #f7f8fa; }

.bg-tint-green { background-color: rgba(0, 180, 42, 0.03); }
.bg-tint-red { background-color: rgba(245, 63, 63, 0.03); }

/* === 场景 B: 普通表格 === */
.table-wrapper { width: 100%; overflow-x: auto; }
table { border-collapse: collapse; width: 100%; min-width: 100%; }
th, td { padding: 8px 10px; white-space: nowrap; background: #fff; font-size: 11px; }
td { padding: 10px 10px; border-bottom: 1px solid #f2f3f5; height: 50px; box-sizing: border-box; }
.sticky-col { position: sticky; left: 0; z-index: 10; background-color: #f7f8fa;
  border-right: 1px solid #e5e6eb; }
th.sticky-col { background-color: #fff; z-index: 11; }
.strike-cell { display: flex; align-items: center; justify-content: space-between;
  font-weight: 500; color: #4e5969; }
.arrow-icon { color: #c9cdd4; font-size: 14px; }
</style>