<template>
  <div class="pc-layout">
    <div class="game-list-container">
      <el-collapse v-model="activeNames" class="dark-collapse">
        <el-collapse-item v-for="group in gameList" :key="group.id" :name="group.id">
          <template #title>
            <div class="group-header-content">
              <div class="header-left">
                <span class="group-title">{{ locale === 'zh' ? group.name : group.name_en }}</span>
              </div>
              <div class="header-right">
                <span class="group-count">{{ group.children ? group.children.length : 0 }}</span>
              </div>
            </div>
          </template>

          <div class="game-list">
            <div
                class="game-item"
                v-for="item in group.children"
                :key="item.id"
                :class="{ active: selectedBets.some(bet => bet.id === item.id) }"
                @click="toggleBet(item)"
            >
              <span class="name">{{ locale === 'zh' ? item.name : item.name_en }}</span>
              <span class="odds">{{ item.odds }}</span>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>

      <div class="common-bottom"></div>
    </div>

    <div class="pc28-cart-container" :class="{ 'is-collapsed': !isCartExpanded }">

      <div class="cart-collapsed" v-if="!isCartExpanded" @click="isCartExpanded = true">
        <div class="custom-cart-icon">
          <el-icon class="icon-color" size="24"><ShoppingCart /></el-icon>
          <span class="custom-badge" v-if="selectedBets.length > 0">
            {{ selectedBets.length }}
          </span>
        </div>
        <div class="vertical-text">{{ t('彩票注单') }}</div>
      </div>

      <div class="cart-expanded" v-else>

        <div class="cart-header" @click="isCartExpanded = false">
          <div class="header-left">
            <el-icon class="pointer" size="20"><ArrowRight /></el-icon>
            <span class="header-badge" v-if="selectedBets.length > 0">{{ selectedBets.length }}</span>
            <span class="header-text">{{ t('彩票注单') }}</span>
          </div>
          <el-button link type="danger" @click.stop="clearAll" v-if="selectedBets.length > 0">
            {{ t('清空') }}
          </el-button>
        </div>

        <div v-if="selectedBets.length > 0" class="batch-stake-box">
          <span class="batch-label">{{ t('批量设置') }}</span>
          <div class="batch-input-wrapper">
            <el-input v-model="batchAmount" :placeholder="t('金额')" type="number" />
          </div>
          <el-button size="small" type="primary" @click.stop="applyBatchAmount">{{ t('确定') }}</el-button>
        </div>

        <div class="cart-body">
          <el-empty class="dark-empty" v-if="selectedBets.length === 0" :description="t('暂无彩票投注项')" />

          <div class="bet-list" v-else>
            <el-collapse v-model="cartActiveNames" class="cart-collapse">
              <el-collapse-item v-for="group in cartGroups" :key="group.id" :name="group.id">
                <template #title>
                  <div class="cart-group-title">
                    <span class="group-indicator"></span>
                    {{ locale === 'zh' ? group.name : group.name_en }}
                  </div>
                </template>

                <div class="bet-item" v-for="bet in group.selectedItems" :key="bet.id">
                  <div class="item-header">
                    <span class="team-names">{{ locale === 'zh' ? bet.name : bet.name_en }}</span>
                    <span class="close-btn" @click.stop="removeBet(bet.id)" style="font-size: 16px;">×</span>
                  </div>

                  <div class="item-info">
                    <span class="type-name">{{ t('赔率') }}</span>
                    <span class="odds-val">{{ Number(bet.odds).toFixed(2) }}</span>
                  </div>

                  <div class="limit-info" v-if="bet.mininum > 0 || bet.maxinum > 0">
                    <span>{{ t('限额') }}: {{ bet.mininum }} ~ {{ bet.maxinum }}</span>
                  </div>

                  <div class="stake-input-box">
                    <el-button class="stepper-btn" link @click="updateAmount(bet, -1)">-</el-button>
                    <el-input
                        v-model="bet.amount"
                        type="number"
                        class="stake-input"
                        :placeholder="t('本金')"
                    />
                    <el-button class="stepper-btn" link @click="updateAmount(bet, 1)">+</el-button>
                  </div>

                  <div class="item-footer">
                    <div class="potential-win">
                      {{ t('预计可赢') }}: <span class="win-amount">{{ (Number(bet.amount || 0) * Number(bet.odds || 0)).toFixed(2) }}</span>
                    </div>
                  </div>
                </div>

              </el-collapse-item>
            </el-collapse>
          </div>
        </div>

        <div class="cart-footer" v-if="selectedBets.length > 0">
          <div class="total-odds-row">
            <span class="label">{{ t('总投注金额') }}</span>
            <span class="val">{{ totalAmount.toFixed(2) }}</span>
          </div>

          <el-button type="primary" class="w-full bet-action-btn" @click="submit">
            {{ t('立即投注') }}
          </el-button>
        </div>

      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { getSportGameList, submitSportGame } from '@/request/api';
// 引入所需的图标
import { ShoppingCart, ArrowRight } from '@element-plus/icons-vue';

const { locale, t } = useI18n();

// 原有状态管理
const gameList = ref([]);
const selectedBets = ref([]);
const batchAmount = ref('');

// UI 控制状态
const activeNames = ref([]);
const isCartExpanded = ref(true); // 默认一直是展开状态
const cartActiveNames = ref([]); // 控制购物车内分组折叠展开的数组

// 计算属性：将选中的注单反向映射到它们各自的组别中
const cartGroups = computed(() => {
  const groups = [];
  gameList.value.forEach(group => {
    // 找出当前组下被选中的子项
    const matches = selectedBets.value.filter(bet =>
        group.children && group.children.some(child => child.id === bet.id)
    );
    if (matches.length > 0) {
      groups.push({
        id: group.id,
        name: group.name,
        name_en: group.name_en,
        selectedItems: matches
      });
    }
  });
  return groups;
});

// 监听购物车分组，当有新分组被加入购物车时，默认将其展开
watch(cartGroups, (newGroups) => {
  newGroups.forEach(g => {
    if (!cartActiveNames.value.includes(g.id)) {
      cartActiveNames.value.push(g.id);
    }
  });
}, { deep: true, immediate: true });

// 初始化读取缓存
onMounted(() => {
  const cached = localStorage.getItem('sport_selected_bets');
  if (cached) {
    try {
      selectedBets.value = JSON.parse(cached);
    } catch (e) {
      console.error('Failed to parse cached bets', e);
    }
  }
});

// 监听 selectedBets 变化并更新缓存
watch(selectedBets, (newVal) => {
  localStorage.setItem('sport_selected_bets', JSON.stringify(newVal));
}, { deep: true });

getSportGameList().then(res => {
  if (res?.data) {
    gameList.value = res.data.map(group => ({
      ...group,
      isCollapsed: true
    }));

    // 默认展开列表第一组
    if (res.data.length > 0) {
      activeNames.value = [res.data[0].id];
    }
  }
});

// 选择/取消选择注单
const toggleBet = (item) => {
  const index = selectedBets.value.findIndex(bet => bet.id === item.id);
  if (index > -1) {
    selectedBets.value.splice(index, 1);
  } else {
    const defaultAmount = (item.mininum && item.mininum > 0) ? item.mininum : '';
    selectedBets.value.push({ ...item, amount: defaultAmount });
    isCartExpanded.value = true; // 确保添加时右侧处于展开状态
  }
};

// 移除单个已选注单
const removeBet = (id) => {
  const index = selectedBets.value.findIndex(bet => bet.id === id);
  if (index > -1) {
    selectedBets.value.splice(index, 1);
  }
};

// 清空全部
const clearAll = () => {
  selectedBets.value = [];
  batchAmount.value = '';
};

// 批量设置金额
const applyBatchAmount = () => {
  const amount = Number(batchAmount.value);
  if (amount > 0) {
    selectedBets.value.forEach(bet => {
      bet.amount = amount;
    });
  }
};

// 步进器更改金额
const updateAmount = (bet, step) => {
  const current = Number(bet.amount) || 0;
  const next = current + step;
  if (next >= 0) {
    bet.amount = next;
  }
};

// 计算总投注额
const totalAmount = computed(() => {
  return selectedBets.value.reduce((total, bet) => {
    return total + (Number(bet.amount) || 0);
  }, 0);
});

// 提交数据 - 数据格式完全未变动
const submit = () => {
  if (selectedBets.value.length === 0) return;

  const payload = {
    data: selectedBets.value.map(bet => ({
      id: bet.id,
      amount: Number(bet.amount) || 0
    }))
  };

  submitSportGame(payload).then(() => {
    clearAll();
  });
};
</script>

<style scoped lang="scss">
/* ====== 左侧全局变量 ====== */
$primary-color: #f8b932;
$bg-main: #141414;
$bg-sidebar: #1e1e1e;
$border-color: #2a2a2a;
$text-main: #e0e0e0;
$text-gray: #7a7a7a;

/* ====== 右侧购物车新样式变量 ====== */
$cart-bg-sidebar: #1e1e1e;
$cart-bg-sidebar-hover: #2a2a2a;
$cart-bg-main: #141414;
$cart-border-color: rgba(255, 255, 255, 0.08);
$cart-text-primary: #e5e5e5;
$cart-text-secondary: #999;
$cart-main-color: #f8b932;

/* ====== 整体布局 ====== */
.pc-layout {
  display: flex;
  width: 100%;
  height: 100%;
  background-color: $bg-main;
  overflow: hidden;
}

/* ====== 左侧：赛事及盘口区 ====== */
.game-list-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;

  :deep(.dark-collapse) {
    border-top: none;
    border-bottom: none;

    .el-collapse-item {
      background: $bg-sidebar;
      border: 1px solid $border-color;
      border-radius: 6px;
      margin-bottom: 16px;
      overflow: hidden;
    }

    .el-collapse-item__header {
      background: $bg-sidebar;
      border-bottom: 1px solid $border-color;
      color: #fff;
      height: 48px;
      padding: 0 16px;

      &.is-active {
        border-bottom-color: $border-color;
      }
    }

    .el-collapse-item__wrap {
      background: transparent;
      border-bottom: none;
    }

    .el-collapse-item__content {
      padding-bottom: 0;
    }

    .group-header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      padding-right: 12px;

      .header-left {
        display: flex;
        align-items: center;

        &::before {
          content: '';
          display: inline-block;
          width: 3px;
          height: 14px;
          background-color: $primary-color;
          margin-right: 10px;
          border-radius: 1.5px;
        }

        .group-title {
          font-size: 14px;
          font-weight: bold;
        }
      }

      .header-right {
        color: $text-gray;
        font-size: 13px;
      }
    }
  }

  .game-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    padding: 16px;
    background-color: rgba(0, 0, 0, 0.1);

    .game-item {
      flex: 1 1 calc(25% - 10px);
      min-width: 140px;
      background: $bg-main;
      border: 1px solid $border-color;
      border-radius: 4px;
      padding: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover { border-color: #555; }

      &.active {
        background-color: $primary-color;
        border-color: $primary-color;
        .name { color: #000; font-weight: bold; }
        .odds { color: #000; }
      }

      .name {
        font-size: 13px;
        color: $text-main;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .odds {
        color: $primary-color;
        font-weight: bold;
        font-size: 14px;
      }
    }
  }
}

/* ====================================================
   右侧购物车
   ==================================================== */
.pc28-cart-container {
  height: 100%;
  background-color: $cart-bg-sidebar;
  border-left: 1px solid $cart-border-color;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
  position: relative;
  overflow: visible;

  &.is-collapsed { width: 50px !important; }
  &:not(.is-collapsed) { width: 320px !important; }
}

.cart-collapsed {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
  cursor: pointer;
  transition: background 0.3s;
  &:hover { background-color: $cart-bg-sidebar-hover; }

  .custom-cart-icon {
    position: relative;
    margin-bottom: 20px;
    display: flex; justify-content: center; align-items: center;
    .icon-color { color: $cart-main-color; }
    .custom-badge {
      position: absolute; top: -6px; right: -10px;
      color: #fff; background-color: $cart-main-color; font-size: 12px;
      padding: 2px 5px; line-height: 1; border-radius: 10px; border: 2px solid $cart-bg-sidebar; font-weight: bold; transform: scale(0.9);
    }
  }
  .vertical-text { writing-mode: vertical-rl; letter-spacing: 4px; font-weight: bold; color: $cart-text-primary; }
}

.cart-expanded {
  display: flex;
  flex-direction: column;
  height: 100%;

  .cart-header {
    height: 50px; display: flex; justify-content: space-between; align-items: center; padding: 0 16px;
    border-bottom: 1px solid $cart-border-color; background-color: $cart-bg-sidebar; cursor: pointer; transition: background 0.2s;
    &:hover { background-color: $cart-bg-sidebar-hover; }
    .header-left {
      display: flex; align-items: center; gap: 8px; color: $cart-text-primary;
      .pointer { color: $cart-text-secondary; display: flex; align-items: center; transition: transform 0.2s; }
      .header-badge { color: #000; background-color: $cart-main-color; font-size: 12px; height: 18px; line-height: 18px; padding: 0 6px; border-radius: 9px; font-weight: bold; }
      .header-text { font-weight: bold; color: $cart-text-primary; font-size: 15px; }
    }
  }

  .batch-stake-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 12px;
    background-color: $cart-bg-sidebar;
    border-bottom: 1px solid $cart-border-color;

    .batch-label {
      font-size: 13px;
      color: $cart-text-primary;
      white-space: nowrap;
    }

    .batch-input-wrapper {
      flex: 1;
      margin: 0 10px;

      :deep(.el-input__wrapper) {
        background-color: #1a1a1a !important;
        box-shadow: 0 0 0 1px $cart-border-color inset !important;
        height: 28px;
        padding: 0;
      }
      :deep(.el-input__inner) {
        color: $cart-text-primary !important;
        text-align: center;
        font-size: 13px;
      }
    }

    .el-button--primary {
      background-color: $cart-main-color;
      border-color: $cart-main-color;
      color: #000;
      font-weight: bold;
      &:hover { opacity: 0.9; }
    }
  }

  .cart-body {
    flex: 1; overflow-y: auto; padding: 12px; background-color: $cart-bg-main;

    :deep(.dark-empty .el-empty__description p) { color: $cart-text-secondary; }

    /* 购物车内的分组折叠面板样式 */
    .cart-collapse {
      border-top: none;
      border-bottom: none;

      :deep(.el-collapse-item__header) {
        background-color: transparent;
        color: $cart-text-secondary;
        border-bottom: none;
        height: 36px;
        line-height: 36px;
      }

      :deep(.el-collapse-item__wrap) {
        background-color: transparent;
        border-bottom: none;
      }

      :deep(.el-collapse-item__content) {
        padding-bottom: 0;
      }

      .cart-group-title {
        display: flex;
        align-items: center;
        font-size: 13px;
        font-weight: bold;
        color: #bbb;
        width: 100%;

        .group-indicator {
          display: inline-block;
          width: 3px;
          height: 12px;
          background-color: $cart-main-color;
          margin-right: 8px;
          border-radius: 2px;
        }
      }
    }

    .bet-item {
      position: relative; background-color: $cart-bg-sidebar; border-radius: 8px; padding: 12px; margin-bottom: 12px; border: 1px solid $cart-border-color;
      transition: border-color 0.3s;
      &:hover { border-color: rgba(248, 185, 50, 0.3); }

      .item-header {
        display: flex; justify-content: space-between; margin-bottom: 8px;
        .team-names { font-weight: bold; font-size: 14px; color: $cart-text-primary; }
        .close-btn { cursor: pointer; z-index: 11; position: relative; color: $cart-text-secondary; &:hover { color: #f56c6c; } }
      }

      .item-info {
        display: flex; justify-content: space-between; font-size: 13px; margin-bottom: 6px;
        .type-name { color: $cart-text-secondary; }
        .odds-val { font-weight: bold; color: $cart-main-color; font-size: 16px; }
      }

      .limit-info {
        display: flex; justify-content: space-between; font-size: 12px; color: #777; margin-bottom: 12px;
      }

      .stake-input-box {
        display: flex; align-items: center; border: 1px solid $cart-border-color; border-radius: 4px; height: 32px; overflow: hidden; background: #1a1a1a;
        .stepper-btn { height: 100%; width: 32px; border: none; background: #262626; color: $cart-text-primary; margin: 0; padding: 0; font-size: 16px; cursor: pointer; &:hover { color: $cart-main-color; } }
        :deep(.el-input__wrapper) { box-shadow: none !important; background: transparent !important; padding: 0; }
        :deep(.el-input__inner) { text-align: center; font-weight: bold; color: $cart-text-primary !important; font-family: monospace; }
      }

      .item-footer {
        margin-top: 10px; text-align: right; font-size: 12px; color: $cart-text-secondary;
        .potential-win .win-amount { color: #67c23a; font-weight: bold; margin-left: 4px; font-size: 14px; }
      }
    }

    /* 滚动条美化 */
    &::-webkit-scrollbar { width: 6px; }
    &::-webkit-scrollbar-track { background: transparent; }
    &::-webkit-scrollbar-thumb { background: #333; border-radius: 10px; }
    &::-webkit-scrollbar-thumb:hover { background: #555; }
  }

  .cart-footer {
    padding: 16px; border-top: 1px solid $cart-border-color; background: $cart-bg-sidebar;
    .total-odds-row {
      display: flex; justify-content: space-between; margin-bottom: 12px; font-size: 14px; color: $cart-text-primary;
      .label { font-weight: bold; }
      .val { color: $cart-main-color; font-weight: bold; font-size: 18px; }
    }
    .bet-action-btn {
      width: 100%; height: 44px; font-size: 16px; font-weight: bold; color: #000; background-color: $cart-main-color; border-color: $cart-main-color;
      &:hover { opacity: 0.9; }
    }
  }
}

/* 移除数字输入框滚轮原生箭头 */
:deep(.stake-input input::-webkit-outer-spin-button),
:deep(.stake-input input::-webkit-inner-spin-button),
:deep(.batch-input-wrapper input::-webkit-outer-spin-button),
:deep(.batch-input-wrapper input::-webkit-inner-spin-button) {
  -webkit-appearance: none;
  margin: 0;
}
:deep(.stake-input input[type="number"]),
:deep(.batch-input-wrapper input[type="number"]) {
  -moz-appearance: textfield;
}

/* ====================================================
   响应式适配 (从您的代码完整继承)
   ==================================================== */
@media screen and (max-width: 1600px) {
  .pc28-cart-container:not(.is-collapsed) { width: 280px !important; }
  .pc28-cart-container .cart-expanded .cart-header { height: 44px; padding: 0 12px; }
  .pc28-cart-container .cart-expanded .cart-header .header-text { font-size: 14px; }
  .pc28-cart-container .cart-expanded .cart-body { padding: 10px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item { padding: 10px; margin-bottom: 10px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-header .team-names { font-size: 13px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-info .odds-val { font-size: 15px; }
  .pc28-cart-container .cart-expanded .cart-footer { padding: 12px; }
  .pc28-cart-container .cart-expanded .cart-footer .bet-action-btn { height: 40px; font-size: 15px; }
}

@media screen and (max-width: 1350px) {
  .pc28-cart-container:not(.is-collapsed) { width: 250px !important; }
  .pc28-cart-container .cart-expanded .cart-header .header-text { font-size: 13px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-info .type-name { font-size: 12px; }
  .pc28-cart-container .cart-expanded .cart-body { padding: 8px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item { padding: 8px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-header .team-names { font-size: 12px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-info { font-size: 12px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-info .odds-val { font-size: 14px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .limit-info { font-size: 11px; margin-bottom: 8px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .stake-input-box { height: 28px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-footer { font-size: 11px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-footer .potential-win .win-amount { font-size: 13px; }
  .pc28-cart-container .cart-expanded .cart-footer { padding: 10px; }
  .pc28-cart-container .cart-expanded .cart-footer .total-odds-row { font-size: 12px; margin-bottom: 8px; }
  .pc28-cart-container .cart-expanded .cart-footer .total-odds-row .val { font-size: 14px; }
  .pc28-cart-container .cart-expanded .cart-footer .bet-action-btn { height: 36px; font-size: 14px; }
  .pc28-cart-container .cart-expanded .cart-header { height: 40px; padding: 0 10px; }
}

@media screen and (max-width: 1200px) {
  .pc28-cart-container:not(.is-collapsed) { width: 230px !important; }
  .pc28-cart-container.is-collapsed { width: 46px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-header .team-names { font-size: 11px; }
  .pc28-cart-container .cart-expanded .cart-header .header-text { font-size: 11px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-info .type-name { font-size: 11px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .limit-info { font-size: 11px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-info .odds-val { font-size: 11px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-footer .potential-win { font-size: 11px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-footer .potential-win .win-amount { font-size: 11px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-header { margin-bottom: 6px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-info { margin-bottom: 5px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .stake-input-box { height: 24px !important; }
  .pc28-cart-container .cart-expanded .cart-footer .total-odds-row { font-size: 11px; margin-bottom: 6px; }
  .pc28-cart-container .cart-expanded .cart-footer .total-odds-row .val { font-size: 12px; }
  .pc28-cart-container .cart-expanded .cart-footer .bet-action-btn { height: 32px; font-size: 14px; }
  .pc28-cart-container .cart-expanded .cart-header { height: 38px; }
  .pc28-cart-container .cart-expanded .cart-header .header-badge { font-size: 11px !important; height: 16px !important; line-height: 16px !important; }
}
</style>
