<template>
  <el-container class="pc-layout-container">
    <el-header class="pc-header" height="64px">
      <div class="header-left">
        <div class="logo-container" @click="goToHome">
          <img src="@/assets/image/logo.png" alt="Logo" style="width: 100px;aspect-ratio: 104 / 16;">
        </div>

        <div class="top-nav-menu">
          <div :class="{ active: route.path.includes('/Home') }" class="nav-item"
               @click="router.push('/Home')">
            {{ t('首页') }}
          </div>
          <div :class="{ active: route.path.includes('/EntertainmentList') }" class="nav-item"
               @click="router.push('/EntertainmentList')">
            {{ t('彩票') }}
          </div>
          <div :class="{ active: route.path.includes('/LotteryDraw') }" class="nav-item"
               @click="router.push('/LotteryDraw')">
            {{ t('开奖') }}
          </div>
<!--          <div :class="{ active: route.path.includes('/SportsBetting') }" class="nav-item"-->
<!--               @click="router.push('/SportsBetting')">-->
<!--            {{ t('赛事') }}-->
<!--          </div>-->
<!--           <div :class="{ active: route.path.includes('/WorldCup') }" class="nav-item"-->
<!--               @click="router.push('/WorldCup')">-->
<!--            <img src="@/assets/image/layout/sjb.gif" alt="" style="width: 50px;">-->
<!--          </div>-->


<!--          <div :class="{ active: route.path.includes('/TotalSoccerAdvance') }" class="nav-item"-->
<!--               @click="router.push('/TotalSoccerAdvance')">-->
<!--            {{ t('冠军') }}-->
<!--          </div>-->

          <el-popover
            placement="bottom"
            width="400px"
          >
            <Promotion />
            <template #reference>
              <div :class="{ active: route.path.includes('/Promotion') }" class="nav-item"
               @click="router.push('/Promotion')">
                {{ t('活动') }}
              </div>
            </template>
          </el-popover>

          <el-popover
            placement="bottom"
          >
            <ul class="nav-links">
<!--                <li>{{ t('博彩责任') }}</li>-->
<!--                <li>{{ t('隐私政策') }}</li>-->
<!--                <li>{{ t('条款与协议') }}</li>-->
              <li @click="openGameRules">{{ t('玩法规则') }}</li>
              <li @click="openRulesAndTerms">{{ t('规则条款') }}</li>
              <li @click="openAbout">{{ t('关于我们') }}</li>
            </ul>
             <template #reference>
              <div class="nav-item">
                {{ t('更多') }}
                <el-icon><CaretBottom /></el-icon>
              </div>
            </template>
          </el-popover>
          </div>
      </div>

      <div class="header-right">
        <template v-if="token">
          <el-button class="money-btn" size="default" type="primary" @click="showRechargeModal = true">
            {{ userStore.balance }} {{ $currency || 'CNY' }}
          </el-button>
          <div :title="t('个人中心')" class="nav-btn" @click="router.push({ name: 'My' })">
            <img src="@/assets/image/layout/person-outline.png" alt="" class="right-top-icon">
          </div>
           <div :title="t('投注历史')" class="nav-btn" @click="router.push({ name: 'AllHistory' })">
           <img src="@/assets/image/layout/time-outline.png" alt="" class="right-top-icon">
          </div>
          <div :title="t('客服')" class="nav-btn" @click="router.push({ name: 'CustomerService' })">
            <img src="@/assets/image/layout/headset.png" alt="" class="right-top-icon">
          </div>
        </template>

        <div v-else style="display: flex;gap: 10px;">
          <div class="login-link" @click="testGame">
            {{ t('免费试玩') }}
          </div>
          <div class="login-link" @click="router.push({name: 'register'})">
            {{ t('注册') }}
          </div>
          <div class="login-link" @click="router.push({name: 'login'})">
            {{ t('登录') }}
          </div>
        </div>

        <selectLang />

      </div>
    </el-header>

    <el-container class="pc-body-container">
      <leftDraw v-if="route.path.includes('/SportsBetting') || route.path.includes('/WorldCup')" />

      <el-main :class="[max1200Routers.indexOf(route.name) !== -1 ? 'max-1200' :'']"
               class="main-content"
      >
        <div v-if="showNavBar && navTitle" class="sub-navbar">
          <el-icon v-if="navLeftArrow" class="sub-nav-back" @click="onClickLeft">
            <ArrowLeft/>
          </el-icon>
          <span class="sub-nav-title">{{ $t(navTitle) }}</span>
          <div class="sub-navbar-right">
            <slot name="navBarRight"></slot>
          </div>
        </div>

        <div class="scroll-content">
          <router-view v-slot="{ Component, route }">
            <transition mode="out-in" name="el-fade-in">
              <keep-alive include="SportsBetting">
                <component :is="Component" :key="route.fullPath"/>
              </keep-alive>
            </transition>
          </router-view>
          <el-backtop :right="100" :visibility-height="300" target=".scroll-content"/>
        </div>
      </el-main>



      <Pc28SidebarCart v-if="route.name === 'Entertainment'"/>
      <ExtremeSpeed28SidebarCart v-if="route.name === 'ExtremeSpeed28'"/>

      <el-aside
      v-if="route.path.toLowerCase().includes('/sports')
      || route.path.toLowerCase().includes('/sportdetail')
      || route.path.includes('/WorldCup')" :class="['right-sidebar', orderStore.isOpen ? 'is-open' : 'is-closed']"
                width="auto">
        <div v-if="!orderStore.isOpen" class="cart-collapsed" @click="openSheet">
          <div class="custom-cart-icon">
            <el-icon class="tmc" size="24">
              <ShoppingCart/>
            </el-icon>
            <span v-if="orderStore.selectedCount > 0" class="custom-badge bmc">
              {{ orderStore.selectedCount }}
            </span>
          </div>
          <div class="vertical-text">{{ t('赛事注单') }}</div>
        </div>

        <div v-else class="cart-expanded">
          <div class="cart-header" @click="closeSheet">
            <div class="header-left">
              <el-icon class="pointer" size="20">
                <ArrowRight/>
              </el-icon>
              <span v-if="orderStore.selectedCount > 0" class="header-badge bmc">
                {{ orderStore.selectedCount }}
              </span>
              <span class="header-text">{{ t('赛事注单') }}</span>
            </div>

            <el-button v-if="orderStore.selectedCount > 0" link type="danger" @click.stop="clearSportCart">
              <el-icon>
                <Delete/>
              </el-icon>
              {{ t('清空') }}
            </el-button>
          </div>

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

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

            <div v-else class="bet-list">
              <div
                  v-for="(item, index) in orderStore.selectOrders"
                  :key="index"
                  :class="{
                    'is-locked': checkIsLocked(item),
                    'is-error': item.errorMsg
                  }"
                  class="bet-item"
              >
                <div v-if="checkIsLocked(item)" class="lock-overlay">
                  <el-icon color="#fff" size="24">
                    <Lock/>
                  </el-icon>
                  <span class="lock-text">{{ t('盘口已失效或关闭') }}</span>
                </div>

                <div class="item-header">
                  <div class="team-names">
                    <div style="margin-bottom: 6px;display: flex;align-items: center;gap: 4px;">
                      <el-tag size="small" type="success">{{ t('主') }}</el-tag>
                      {{ locale === 'zh' ? item.homeTeam : item.home_team_en }}
                    </div>
                    <div style="display: flex;align-items: center;gap: 4px;">
                      <el-tag size="small" type="danger">{{ t('客') }}</el-tag>
                      {{ locale === 'zh' ? item.guestTeam : item.guest_team_en }}
                    </div>
                  </div>
                  <el-icon class="close-btn" @click.stop="orderStore.removeOrderItem(item.uniqueKey)">
                    <Close/>
                  </el-icon>
                </div>

                <div class="item-info">
                  <span class="type-name">
                    {{ locale === 'zh' ? item.betType : item.betTypeEn }}: {{ locale === 'zh' ? item.betTypeName : item.betTypeNameEn }}
                    <span v-if="item.handicap_text" style="color: #f8b932;">[{{ item.handicap_text }}]</span>
                  </span>
                  <span class="odds-val tmc">{{ item.odds }}</span>
                </div>

                <div class="league-info">
                  <span>{{  locale === 'zh' ? item.league : item.league_en }}</span>
                  <span v-if="item.score" class="live-score">{{ t('比分') }}: {{ item.score }}</span>
                </div>

                <div class="limit-info" style="font-size: 12px; color: #999; margin-bottom: 8px; display: flex; justify-content: space-between;" v-if="item.mininum !== undefined && item.maxinum !== undefined">
                  <span>{{ t('单注限额') }}</span>
                  <span>{{ item.mininum }} ~ {{ item.maxinum }}</span>
                </div>

                <div :class="{ 'error-border': item.errorMsg || (!checkIsLocked(item) && item.stake !== '' && item.stake !== undefined && Number(item.stake) <= 0) || (!checkIsLocked(item) && Number(item.stake) > Number(userStore.balance)) || (!checkIsLocked(item) && item.mininum !== undefined && item.stake !== '' && item.stake !== undefined && Number(item.stake) < Number(item.mininum)) || (!checkIsLocked(item) && item.maxinum !== undefined && Number(item.stake) > Number(item.maxinum)) }"
                     class="stake-input-box">
                  <el-button class="stepper-btn" link @click="changeStake(item, -10)">-</el-button>
                  <el-input
                      v-model="item.stake"
                      :disabled="checkIsLocked(item)"
                      class="stake-input"
                      :placeholder="t('本金')"
                      type="number"
                      @input="(val) => onInputStake(val, item)"
                  />
                  <el-button class="stepper-btn" link @click="changeStake(item, 10)">+</el-button>
                </div>

                <div class="item-footer">
                  <div v-if="item.errorMsg" class="err-msg fail-reason">
                    <el-icon class="mr-1">
                      <Warning/>
                    </el-icon>
                    {{ t(item.errorMsg) }}
                  </div>
                  <div v-else-if="!checkIsLocked(item) && item.stake !== '' && item.stake !== undefined && Number(item.stake) <= 0" class="err-msg">
                    {{ t('金额不能小于等于0') }}
                  </div>
                  <div v-else-if="!checkIsLocked(item) && item.mininum !== undefined && item.stake !== '' && item.stake !== undefined && Number(item.stake) < Number(item.mininum)" class="err-msg">
                    {{ t('单注最低限制为') }} {{ item.mininum }}
                  </div>
                  <div v-else-if="!checkIsLocked(item) && item.maxinum !== undefined && Number(item.stake) > Number(item.maxinum)" class="err-msg">
                    {{ t('单注最高限制为') }} {{ item.maxinum }}
                  </div>
                  <div v-else-if="!checkIsLocked(item) && Number(item.stake) > Number(userStore.balance)"
                       class="err-msg">
                    {{ t('投注额超过您的余额') }}
                  </div>
                  <div v-else class="potential-win">
                    {{ t('潜在赢利') }}
                    <span class="win-amount">{{ (Number(item.stake) * Number(item.odds)).toFixed(2) }} {{
                        $currency
                      }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="cart-footer">
            <div v-if="orderStore.selectedCount > 0" class="total-odds-row">
<span class="label">{{ t('总金额') }}</span>
<span class="val tmc">{{ validTotalAmount.toFixed(2) }}</span>
            </div>

            <div class="auto-accept-box">
              <el-checkbox v-model="isAutoAccept" @change="handleAutoAcceptChange">
                <span class="auto-accept-text">{{ t('自动接受更好的赔率') }}</span>
              </el-checkbox>
            </div>

            <el-button v-if="validTotalStake > userStore.balance" class="w-full bet-action-btn" type="primary"
                       @click="topUp">
              {{ t('存款') }}
            </el-button>
            <el-button v-else class="w-full bet-action-btn" type="primary" @click="submitBet">
              {{ t('投注') }}
            </el-button>
          </div>
        </div>
      </el-aside>

      <DigitalBetCart v-if="route.path === '/Digital'"/>
      <HKDigitalBetCart v-else-if="route.path === '/HKDigital'"/>
      <NewDigitalBetCart v-else-if="route.path === '/NewDigital'"/>
      <SpeedDigitalBetCart v-else-if="route.path === '/SpeedDigital'"/>
    </el-container>

    <el-dialog v-model="showSafeModal" :title="t('安全验证')" center custom-class="dark-dialog" width="500px">
      <div class="safe-modal-content">
        <p class="safe-tips">{{ t('为保障您的资金安全，请输入资金密码') }}</p>
        <el-input v-model="safeWord" :placeholder="t('请输入资金密码')" class="dark-input" show-password
                  type="password"/>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button class="cancel-btn" @click="showSafeModal = false">{{ t('取消') }}</el-button>
          <el-button type="primary" @click="confirmSubmitBet">{{ t('确定投注') }}</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="showRetryModal" :title="t('投注失败提示')" center custom-class="dark-dialog" width="500px">
      <div class="retry-modal-content">
        <p class="safe-tips">
          {{ hasRetryableOrders ? t('以下注单提交失败，是否重新尝试？') : t('以下注单提交失败') }}
        </p>
        <div class="failed-list">
          <div class="failed-item" v-for="(item, index) in failedOrdersToRetry" :key="index">
            <div v-if="item.is_submit !== 1" class="retry-lock-overlay">
              <span class="retry-lock-text">{{ t('不可重新提交') }}</span>
            </div>

            <div class="failed-item-top">
              <div class="bet-info">
                <span class="bet-value">{{ locale === 'zh' ? item.value_text : item.value }}</span>
                <span v-if="item.handicap" class="bet-handicap">[{{item.handicap}}]</span>
                <span class="fail-detail">@{{ item.odd }}</span>
              </div>
              <span class="fail-msg">{{ t(item.msg) }}</span>
            </div>

            <div class="failed-item-bottom" v-if="item.remaind">
              <span class="remain-text">
                {{ t('剩余可投注金额') }}: <span class="remain-amount">{{ item.remaind }}</span>
              </span>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button class="cancel-btn" @click="showRetryModal = false">{{ t('取消') }}</el-button>
          <el-button v-if="hasRetryableOrders" type="primary" :loading="isRetrying" @click="confirmRetrySubmit">
            {{ t('重新提交') }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <RechargeModal v-model="showRechargeModal" @success="handleRechargeSuccess"/>

    <el-dialog v-model="GameRulesShow" width="80%" center :title="t('玩法规则')">
      <div style="height: 70vh;overflow-y: auto;">
        <div v-html="GameRulesHTML"></div>
      </div>
    </el-dialog>

    <el-dialog v-model="RulesAndTermsShow" width="80%" center :title="t('规则条款')">
      <div style="height: 70vh;overflow-y: auto;">
        <div v-html="RulesAndTermsHTML"></div>
      </div>
    </el-dialog>

    <el-dialog v-model="AboutShow" width="80%" center :title="t('关于我们')">
      <div style="height: 70vh;overflow-y: auto;">
        <div v-html="AboutHTML"></div>
      </div>
    </el-dialog>

    <ConfirmRechargeModal />
  </el-container>
</template>

<script setup>
import {ref, computed, onMounted, onUnmounted, watch} from 'vue';
import {useRouter, useRoute} from 'vue-router';
import {useI18n} from "vue-i18n";
import {ElMessage, ElNotification, ElMessageBox} from 'element-plus';
import {
  User, Service, ArrowLeft, ArrowRight, ShoppingCart,
  Close, Lock, Delete, Warning, Clock, CaretBottom
} from '@element-plus/icons-vue';
import selectLang from '@/components/selectLang/index.vue';

import {useOrderStore} from '@/store/bettingSheet.js';
import {useUserStore} from '@/store/user/index.js';
import {usePc28CartStore} from '@/store/pc28Cart.js';
import {getBalance, submitOrder, userGuestRegister} from "@/request/api.js";
import { useRechargeStore } from '@/store/rechargeStore.js'

import socket from '@/utils/websocket.js';

import leftDraw from './components/leftDraw/index.vue'
import Promotion from './components/Promotion/index.vue'
import RechargeModal from "@/businessComponents/RechargeModal/index.vue";
import Pc28SidebarCart from "@/businessComponents/Pc28SidebarCart/index.vue";
import ExtremeSpeed28SidebarCart from "@/businessComponents/ExtremeSpeed28SidebarCart/index.vue";
import DigitalBetCart from "@/businessComponents/DigitalBetCart/index.vue";
import HKDigitalBetCart from "@/businessComponents/HKDigitalBetCart/index.vue";
import NewDigitalBetCart from "@/businessComponents/NewDigitalBetCart/index.vue";
import SpeedDigitalBetCart from "@/businessComponents/SpeedDigitalBetCart/index.vue";
import ConfirmRechargeModal from "@/businessComponents/ConfirmRechargeModal/index.vue";
import {AboutHTML, GameRulesHTML, RulesAndTermsHTML} from "@/businessComponents/pcFooter/dataConfig.js";

const {t, locale} = useI18n();
const router = useRouter();
const route = useRoute();
const orderStore = useOrderStore();
const userStore = useUserStore();
const pc28CartStore = usePc28CartStore();
const rechargeStore = useRechargeStore()

const props = defineProps({
  navTitle: {type: String, default: ''},
  navLeftArrow: {type: Boolean, default: true},
  showNavBar: {type: Boolean, default: true}
});

const max1200Routers = ref(['SportsBetting'])
const token = ref(null);
const showSafeModal = ref(false);
const safeWord = ref('');
const batchStakeValue = ref(localStorage.getItem('sportBatchStakeCache') || '');

// 自动接受更好的赔率状态控制
const isAutoAccept = ref(localStorage.getItem('autoAcceptOdds') !== 'false');
const handleAutoAcceptChange = (val) => {
  localStorage.setItem('autoAcceptOdds', val);
};

// 【新增】重试机制相关状态
const showRetryModal = ref(false);
const failedOrdersToRetry = ref([]);
const isRetrying = ref(false);

// 【新增】计算是否有可以重新提交的订单
const hasRetryableOrders = computed(() => {
  return failedOrdersToRetry.value.some(item => item.is_submit === 1);
});

// ==========================================
// 1. 路由监听：智能收起/展开购物车
// ==========================================
watch(
    () => route.path,
    (newPath) => {
      const path = newPath.toLowerCase();

      if (path.includes('/entertainment')) {
        orderStore.setSheetOpen(false);
        pc28CartStore.setSheetOpen(true);
      } else if (path.includes('/sportsbetting') || path.includes('/sportdetail')) {
        pc28CartStore.setSheetOpen(false);
        orderStore.setSheetOpen(true);
      } else if (path.includes('/digital')) {
        pc28CartStore.setSheetOpen(false);
        orderStore.setSheetOpen(false);
      }
    },
    {immediate: true}
);

// ==========================================
// 2. 核心：WebSocket 实时数据同步与拒单拦截
// ==========================================
const handleGlobalSocketMessage = (e) => {
  try {
    const data = e.detail || e.data;
    const res = typeof data === 'string' ? JSON.parse(data) : data;

    if (res.type === 'order_failure' && res.message && res.message.data) {
      const failData = res.message.data;
      orderStore.markOrderFailure(failData, failData.msg);

      // 默认错误提示
      let detailMsg = t(`您的一笔注单被退回：`) + t(failData.msg);
      let useHtml = false;

      // 如果包含 sport_info，则拼接详细的赛事与盘口信息
      if (failData.sport_info) {
        const home = locale.value === 'zh' ? failData.sport_info.home_team || failData.sport_info.home_team_en : failData.sport_info.home_team_en;
        const guest = locale.value === 'zh' ? failData.sport_info.guest_team || failData.sport_info.guest_team_en : failData.sport_info.guest_team_en;
        const handicapStr = failData.handicap ? ` [${failData.handicap}]` : '';

        detailMsg = `
          <div style="font-weight: bold; margin-bottom: 4px;">${home} vs ${guest}</div>
          <div style="color: #f8b932; font-family: DIN, monospace; margin-bottom: 4px;">
            ${locale.value === 'zh' ? failData.value_text || failData.value : failData.value}${handicapStr} @${failData.odd}
          </div>
          <div style="color: #f56c6c;">${t('原因')}: ${t(failData.msg)}</div>
        `;
        useHtml = true;
      }

      ElNotification({
        title: t('注单被拒'),
        message: detailMsg,
        dangerouslyUseHTMLString: useHtml,
        type: 'error',
        duration: 5000
      });
    }

    if (res.type === 'sport_list' && Array.isArray(res.message)) {
      let isCartUpdated = false;

      res.message.forEach((newMatch) => {
        orderStore.selectOrders.forEach((cartItem) => {
          if (cartItem.data_id === newMatch.data_id) {
            isCartUpdated = true;

            cartItem.score = newMatch.score;
            cartItem.state = newMatch.state;
            cartItem.status = newMatch.status;
            cartItem.is_roll = newMatch.is_roll;
            cartItem.is_locked = newMatch.is_locked;

            if (newMatch.odds && Array.isArray(newMatch.odds)) {
              const targetMarket = newMatch.odds.find(m => m.id === cartItem.marketId);

              if (targetMarket && targetMarket.values) {
                const targetOption = targetMarket.values.find(opt => {
                  const isValueMatch = opt.value === cartItem.optionValue;
                  const isHandicapMatch = cartItem.handicap
                      ? opt.handicap === cartItem.handicap
                      : true;
                  return isValueMatch && isHandicapMatch;
                });

                if (targetOption) {
                  cartItem.odds = targetOption.odd;
                }
              }
            }
          }
        });
      });

      if (isCartUpdated && typeof orderStore.saveToStorage === 'function') {
        orderStore.saveToStorage();
      }
    }

     if(res.type === 'rgcz') {
      rechargeStore.showModal(res.message);
   }
  } catch (err) {
    console.error('全局WebSocket解析失败:', err);
  }
};

onMounted(() => {
  token.value = localStorage.getItem('token');
  if (token.value) {
    getData();
  }
  socket.eventBus.addEventListener('onSocketMessage', handleGlobalSocketMessage);
});

onUnmounted(() => {
  socket.eventBus.removeEventListener('onSocketMessage', handleGlobalSocketMessage);
});

// ==========================================
// 3. 业务逻辑 (购物车状态计算与提交)
// ==========================================
const checkIsLocked = (item) => {
  if (Number(item.is_locked) === 1) return true;
  if (item.status !== undefined && Number(item.status) !== 1) return true;
  if (!item.odds || item.odds === '-' || Number(item.odds) <= 0) return true;

  if (item.state !== undefined) {
    const state = Number(item.state);
    const isRoll = Number(item.is_roll);
    if (isRoll === 1) {
      if (![0, 1, 3].includes(state)) return true;
    } else {
      if (![0, 1].includes(state)) return true;
    }
  }
  return false;
};

const validOrders = computed(() => {
  const orders = orderStore.selectOrders || [];
  return orders.filter(item => !checkIsLocked(item));
});

const validTotalOdds = computed(() => {
  if (validOrders.value.length === 0) return 0;
  return validOrders.value.reduce((sum, item) => sum + (Number(item.odds) || 0), 0);
});

const validTotalAmount = computed(() => {
  if (validOrders.value.length === 0) return 0;
  return validOrders.value.reduce((sum, item) => sum + (Number(item.stake) || 0), 0);
});

const validTotalStake = computed(() => {
  return validOrders.value.reduce((sum, item) => sum + (Number(item.stake) || 0), 0);
});

const openSheet = () => {
  orderStore.setSheetOpen(true);
};
const closeSheet = () => {
  orderStore.setSheetOpen(false);
};

const clearSportCart = () => {
  orderStore.selectOrders = [];
  orderStore.setSheetOpen(false);
  if (typeof orderStore.saveToStorage === 'function') orderStore.saveToStorage();
}

const applyBatchStake = () => {
  let val = batchStakeValue.value;
  localStorage.setItem('sportBatchStakeCache', val);

  if (val === '') {
    validOrders.value.forEach(item => {
      orderStore.updateStake(item.uniqueKey, '');
      item.errorMsg = '';
    });
    return;
  }

  let numVal = Number(val);
  if (isNaN(numVal) || numVal <= 0) {
    return ElMessage.warning(t('请输入大于0的有效金额'));
  }

  validOrders.value.forEach(item => {
    let itemVal = numVal;
    if (item.mininum !== undefined && itemVal < Number(item.mininum)) {
      itemVal = Number(item.mininum);
    }
    if (item.maxinum !== undefined && itemVal > Number(item.maxinum)) {
      itemVal = Number(item.maxinum);
    }
    orderStore.updateStake(item.uniqueKey, itemVal);
    item.errorMsg = '';
  });
};

const changeStake = (item, delta) => {
  if (checkIsLocked(item)) return;
  let val = Number(item.stake) || 0;
  val += delta;
  if (val < 0) val = 0;
  // 新增：步进控制不超过最大额
  if (item.maxinum !== undefined && val > Number(item.maxinum)) {
    val = Number(item.maxinum);
  }
  orderStore.updateStake(item.uniqueKey, val);
};

const onInputStake = (val, item) => {
  if (checkIsLocked(item)) return;
  orderStore.updateStake(item.uniqueKey, val);
};

const goToHome = () => {
  router.push('/');
};
const onClickLeft = () => {
  router.back();
};

const testGame = () => {
  if(localStorage.getItem('youke_token')) {
    return ElMessage.warning(t('您已登录'))
  }
  userGuestRegister().then((res) => {
    localStorage.setItem('youke_token', res.data.token);
    localStorage.setItem('token', res.data.token);

    nextTick(() => {
      location.reload();
    })
  })
}

const submitBet = () => {
  const orders = orderStore.selectOrders || [];
  if (orders.length === 0) {
    return ElMessage.warning(t('请选择投注单'));
  }
  if (validOrders.value.length === 0) {
    return ElMessage.warning(t('暂无有效投注项，请移除锁定盘口或重新选择'));
  }

  // 新增：限额校验拦截
  for (let i = 0; i < validOrders.value.length; i++) {
    const item = validOrders.value[i];
    const stake = Number(item.stake);
    if (!stake || stake <= 0) {
      return ElMessage.warning(t('请输入大于0的有效投注金额'));
    }
    if (item.mininum !== undefined && stake < Number(item.mininum)) {
      return ElMessage.warning(`${t('最低投注限额为')} ${item.mininum}`);
    }
    if (item.maxinum !== undefined && stake > Number(item.maxinum)) {
      return ElMessage.warning(`${t('最高投注限额为')} ${item.maxinum}`);
    }
  }

  if (validTotalStake.value > userStore.balance) {
    return ElMessage.error(t('余额不足'));
  }
  safeWord.value = '';
  // showSafeModal.value = true;
  confirmSubmitBet()
};

// ==========================================
// 4. 【新增】核心提炼：抽离统一提交和结果处理逻辑
// ==========================================
const executeSubmit = (ordersData, isRetry = false) => {
  if(isRetry) isRetrying.value = true;

  submitOrder({
    data: ordersData,
    safe_word: safeWord.value,
    is_auto: isAutoAccept.value ? 1 : 0
  }).then(res => {
    if(isRetry) isRetrying.value = false;

    if (res.code === 1) {
      showSafeModal.value = false;
      getData(); // 刷新余额

      const failures = res.data?.failure || [];

      // 1. 清除成功的注单（没在 failures 里的就是成功的）
      validOrders.value.forEach(o => {
        const isFailed = failures.some(f =>
            String(f.data_id) === String(o.data_id) &&
            String(f.id) === String(o.marketId) &&
            String(f.value) === String(o.optionValue) &&
            String(f.handicap || '') === String(o.handicap || '')
        );
        if (!isFailed) {
          orderStore.removeOrderItemByKey(o.uniqueKey);
        }
      });

      // 2. 如果存在失败注单，触发提示并保留在购物车
      if (failures.length > 0) {
        failures.forEach(failItem => {
          orderStore.markOrderFailure(failItem, failItem.msg);
        });

        // 赋值并弹起“重试”窗口
        failedOrdersToRetry.value = failures;
        showRetryModal.value = true;

        if (isRetry) {
          // 如果是再次重试依旧有失败的
          // ElMessage.warning(t(`仍有 ${failures.length} 个注单失败，请检查。`));
        }
      } else {
        // 全部成功
        showRetryModal.value = false; // 关闭重试弹窗
        if (orderStore.selectOrders.length === 0) {
          closeSheet();
        }
        // ElMessage.success(t('所有注单下注成功！'));
        safeWord.value = ''; // 完全成功后清空安全密码
      }
    }
  }).catch(err => {
    if(isRetry) isRetrying.value = false;
    console.error(err);
  });
};

const confirmSubmitBet = async () => {
  // if (!safeWord.value) {
  //   return ElMessage.warning(t('请输入资金密码'));
  // }
 try {
    await ElMessageBox.confirm(t('确认提交吗？'), t('提示'), {
      confirmButtonText: t('确定'),
      cancelButtonText: t('取消'),
      type: 'warning',
    });
  } catch {
    return; // 用户点击取消，阻止后续执行
  }

  const ordersData = validOrders.value.map(item => {
    const payload = {
      data_id: item.data_id,
      amount: item.stake,
      id: item.marketId,
      // value: item.optionValue,
      value: item.selection.submit_value || item.submit_value,
      value_text: item.selection.value_text,
      odd: item.odds
    };
    if (item.handicap !== null && item.handicap !== undefined && item.handicap !== '') {
      payload.handicap = item.handicap;
    }
    return payload;
  });

  executeSubmit(ordersData, false);
};

// 【新增】确认重新提交
const confirmRetrySubmit = () => {
  // 筛选仅允许 is_submit === 1 的进行重试
  const validRetries = failedOrdersToRetry.value.filter(f => f.is_submit === 1);

  if (validRetries.length === 0) {
    showRetryModal.value = false;
    isRetrying.value = false;
    return;
  }

  // 从 validOrders 重新取数据，保证用的是最新的赔率和金额
  const ordersData = [];
  validRetries.forEach(f => {
    const matchedOrder = validOrders.value.find(o =>
        String(o.data_id) === String(f.data_id) &&
        String(o.marketId) === String(f.id) &&
        String(o.optionValue) === String(f.value) &&
        String(o.handicap || '') === String(f.handicap || '')
    );

    if (matchedOrder) {
      const payload = {
        data_id: matchedOrder.data_id,
        amount: matchedOrder.stake,
        id: matchedOrder.marketId,
        value: matchedOrder.optionValue,
          value_text: matchedOrder.value_text,
        odd: matchedOrder.odds
      };
      if (matchedOrder.handicap !== null && matchedOrder.handicap !== undefined && matchedOrder.handicap !== '') {
        payload.handicap = matchedOrder.handicap;
      }
      ordersData.push(payload);
    }
  });

  if (ordersData.length === 0) {
    showRetryModal.value = false;
    isRetrying.value = false;
    return;
  }

  executeSubmit(ordersData, true);
};

function getData() {
  getBalance().then(res => {
    userStore.balance = res.data.money;
  }).catch(err => {
    console.error('获取余额失败：', err);
  });
}

function topUp() {
  if (localStorage.getItem('token')) {
    showRechargeModal.value = true
  } else {
    ElMessage.warning(t('请先登录'))
    router.push({name: 'login'});
  }
}

const GameRulesShow = ref(false)
const RulesAndTermsShow = ref(false)
const AboutShow = ref(false)

function openGameRules() {
  GameRulesShow.value =true
}
function openRulesAndTerms() {
  RulesAndTermsShow.value =true
}
function openAbout() {
  AboutShow.value =true
}

const showRechargeModal = ref(false);
const handleRechargeSuccess = () => {}

defineExpose({
  getData
});
</script>

<style lang="scss" scoped>
$bg-header: #212121;
$bg-main: #141414;
$bg-sidebar: #1e1e1e;
$bg-sidebar-hover: #2a2a2a;
$border-color: rgba(255, 255, 255, 0.08);
$text-primary: #e5e5e5;
$text-secondary: #999;
$main-color: #f8b932;

.pc-layout-container {
  height: 100vh;
  width: 100vw;
  //min-width: 1000px;
  overflow: hidden;
  box-sizing: border-box;
  background-color: $bg-main;
}

.pc-header {
  background-color: $bg-header;
  color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.4);
  z-index: 10;
  border-bottom: 1px solid $border-color;

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

    .logo-container {
      display: flex;
      align-items: center;
      cursor: pointer;
      margin-right: 40px;

      svg {
        width: 100px;
        height: 40px;
      }
    }

    .top-nav-menu {
      display: flex;
      align-items: center;
      gap: 30px;

      .nav-item {
        font-size: 15px;
        color: #dcdfe6;
        cursor: pointer;
        font-weight: 500;
        transition: all 0.3s;
        padding: 8px 12px;
        border-radius: 6px;

        &:hover {
          color: $main-color;
        }

        &.active {
          color: $main-color;
          background-color: rgba(248, 185, 50, 0.1);
          font-weight: bold;
        }
      }
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 16px;

    .money-btn {
      font-weight: bold;
      color: #000;
    }

    .nav-btn {
      cursor: pointer;
      padding: 6px;
      border-radius: 50%;
      transition: background 0.3s;
      height: 24px;

      &:hover {
        background-color: rgba(255, 255, 255, 0.1);
        color: $main-color;
      }
    }

    .login-link {
      color: #ccc;
      text-decoration: underline;
      cursor: pointer;

      &:hover {
        color: $main-color;
      }
    }
  }
}

.pc-body-container {
  height: calc(100vh - 64px);
  overflow-x: hidden;
}

.max-1200 {
  //width: 90%;
  //max-width: 1200px;
  //margin: 0 auto;
}

.main-content {
  padding: 0;
  display: flex;
  flex-direction: column;
  background: $bg-main;
  box-sizing: border-box;


  .sub-navbar {
    display: flex;
    align-items: center;
    height: 40px;
    padding: 0 20px;
    background-color: $bg-sidebar;
    border-bottom: 1px solid $border-color;
    color: $text-primary;

    .sub-nav-back {
      cursor: pointer;
      margin-right: 10px;
      font-size: 18px;

      &:hover {
        color: $main-color;
      }
    }

    .sub-nav-title {
      font-weight: 600;
    }

    .sub-navbar-right {
      margin-left: auto;
    }
  }

  .scroll-content {
    flex: 1;
    overflow-y: auto;
    box-sizing: border-box;
  }
}

.right-sidebar {
  background-color: $bg-sidebar;
  border-left: 1px solid $border-color;
  transition: width 0.3s ease;
  position: relative;
  overflow: visible;

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

    &:hover {
      background-color: $bg-sidebar-hover;
    }

    .custom-cart-icon {
      position: relative;
      margin-bottom: 20px;
      display: flex;
      justify-content: center;
      align-items: center;

      .custom-badge {
        position: absolute;
        top: -6px;
        right: -10px;
        color: #fff;
        font-size: 12px;
        line-height: 1;
        padding: 2px 5px;
        border-radius: 10px;
        border: 2px solid $bg-sidebar;
        font-weight: bold;
        transform: scale(0.9);
      }
    }

    .vertical-text {
      writing-mode: vertical-rl;
      letter-spacing: 4px;
      font-weight: bold;
    }
  }

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

    .cart-header {
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 16px;
      border-bottom: 1px solid $border-color;
      background-color: $bg-sidebar;
      cursor: pointer;
      transition: background 0.2s;

      &:hover {
        background-color: $bg-sidebar-hover;
      }

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

        .pointer {
          color: $text-secondary;
          display: flex;
          align-items: center;
          transition: transform 0.2s;
        }

        .header-badge {
          color: #fff;
          font-size: 12px;
          height: 18px;
          line-height: 18px;
          padding: 0 6px;
          border-radius: 9px;
          font-weight: bold;
        }

        .header-text {
          font-weight: bold;
          color: $text-primary;
        }
      }

      .settings-btn {
        font-size: 12px;
        color: $text-secondary;
        padding: 4px 8px;
        border-radius: 4px;
        transition: all 0.2s;

        &:hover {
          color: $main-color;
          background: rgba(248, 185, 50, 0.1);
        }
      }
    }

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

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

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

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

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

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

      .bet-item {
        position: relative;
        background-color: $bg-sidebar;
        border-radius: 8px;
        padding: 12px;
        margin-bottom: 12px;
        border: 1px solid $border-color;
        transition: all 0.3s;

        &:hover:not(.is-error) {
          border-color: rgba(248, 185, 50, 0.3);
        }

        &.is-error {
          border-color: #f56c6c !important;
          background-color: rgba(245, 108, 108, 0.05) !important;
          animation: shake 0.4s ease-in-out;
        }

        .lock-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.8);
          z-index: 10;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          border-radius: 8px;

          .lock-text {
            color: #fff;
            margin-top: 6px;
            font-weight: bold;
            font-size: 13px;
          }
        }

        .item-header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;

          .team-names {
            font-weight: bold;
            font-size: 14px;
            color: $text-primary;
          }

          .close-btn {
            cursor: pointer;
            z-index: 11;
            color: $text-secondary;
            position: relative;

            &:hover {
              color: #f56c6c;
            }
          }
        }

        .item-info {
          display: flex;
          justify-content: space-between;
          font-size: 13px;
          margin-bottom: 6px;

          .type-name {
            color: $text-secondary;
          }

          .odds-val {
            font-weight: bold;
            font-size: 16px;
          }
        }

        .league-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 $border-color;
          border-radius: 4px;
          height: 32px;
          overflow: hidden;
          background: #1a1a1a;

          &.error-border {
            border-color: #f56c6c;
          }

          .stepper-btn {
            height: 100%;
            width: 32px;
            border: none;
            background: #262626;
            color: $text-primary;
            margin: 0;
            padding: 0;

            &:hover {
              color: $main-color;
            }
          }

          :deep(.el-input__wrapper) {
            box-shadow: none !important;
            background: transparent;
            padding: 0;
          }

          :deep(.el-input__inner) {
            text-align: center;
            font-weight: bold;
            color: $text-primary;
          }
        }

        .item-footer {
          margin-top: 10px;
          text-align: right;
          font-size: 12px;
          color: $text-secondary;

          .err-msg {
            color: #f56c6c;
          }

          .fail-reason {
            font-weight: bold;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 4px;
            font-size: 12px;
          }

          .potential-win .win-amount {
            color: #67c23a;
            font-weight: bold;
            margin-left: 4px;
            font-size: 14px;
          }
        }
      }
    }

    .cart-footer {
      padding: 16px;
      border-top: 1px solid $border-color;
      background: $bg-sidebar;

      .total-odds-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;
        font-size: 14px;
        color: $text-primary;

        .label {
          font-weight: bold;
        }

        .val {
          font-weight: bold;
          font-size: 18px;
        }
      }

      .auto-accept-box {
        margin-bottom: 12px;
        :deep(.el-checkbox__label) {
          font-size: 13px;
          color: $text-secondary;
        }
      }

      .bet-action-btn {
        width: 100%;
        height: 44px;
        font-size: 16px;
        font-weight: bold;
        color: #000;
      }
    }
  }
}

:deep(.dark-dialog) {
  background-color: $bg-sidebar;
  border: 1px solid $border-color;

  .el-dialog__title {
    color: $text-primary;
    font-weight: bold;
  }

  .el-dialog__headerbtn .el-dialog__close {
    color: $text-secondary;

    &:hover {
      color: $main-color;
    }
  }



  .dialog-footer {
    .cancel-btn {
      background: transparent;
      color: $text-primary;
      border: 1px solid $border-color;

      &:hover {
        border-color: $main-color;
        color: $main-color;
      }
    }
  }
}

.safe-modal-content {
  text-align: center;

  .safe-tips {
    margin-bottom: 16px;
    color: $text-secondary;
    font-size: 14px;
  }

  .dark-input {
    .el-input__wrapper {
      background-color: #1a1a1a;
      box-shadow: 0 0 0 1px $border-color inset;

      &:hover, &.is-focus {
        box-shadow: 0 0 0 1px $main-color inset;
      }
    }

    .el-input__inner {
      color: $text-primary;
    }
  }
}

/* 【新增】重试弹窗特有样式 */
.retry-modal-content {
  .failed-list {
    background: transparent;
    border: none;
    padding: 0 4px; /* 留出一点边距防止滚动条贴紧 */
    margin-top: 15px;
    max-height: 240px; /* 稍微增加可视区域 */
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 12px; /* 卡片之间的间距 */

    /* 优化滚动条样式 */
    &::-webkit-scrollbar {
      width: 4px;
    }
    &::-webkit-scrollbar-thumb {
      background: #333;
      border-radius: 4px;
    }

    .failed-item {
      display: flex;
      flex-direction: column;
      background: #262626; /* 独立卡片底色 */
      border-radius: 8px;
      padding: 12px;
      border: 1px solid rgba(255, 255, 255, 0.05);
      position: relative;
      overflow: hidden;
      transition: all 0.3s ease;

      &:hover {
        border-color: rgba(248, 185, 50, 0.3); /* 悬浮时边框亮起主色调 */
        background: #2a2a2a;
      }

      .failed-item-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        margin-bottom: 10px;

        .bet-info {
          display: flex;
          gap: 8px;
          align-items: center;

          .bet-value {
            color: $text-primary;
            font-size: 14px;
            font-weight: bold;
          }
          .bet-handicap {
            color: $main-color;
            font-size: 13px;
          }
          .fail-detail {
            color: $main-color;
            font-family: DIN, monospace;
            font-weight: bold;
            background: rgba(248, 185, 50, 0.1);
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 13px;
          }
        }

        .fail-msg {
          color: #f56c6c;
          font-weight: bold;
          font-size: 12px;
          background: rgba(245, 108, 108, 0.1); /* 错误信息做成小胶囊形状 */
          padding: 4px 8px;
          border-radius: 4px;
        }
      }

      .failed-item-bottom {
        display: flex;
        justify-content: flex-start;

        .remain-text {
          font-size: 12px;
          color: $text-secondary;
          background: #1a1a1a; /* 底部信息块底色 */
          padding: 4px 8px;
          border-radius: 4px;

          .remain-amount {
            color: $text-primary;
            font-weight: bold;
            font-family: DIN, monospace;
            margin-left: 4px;
          }
        }
      }

      /* 不可再次提交蒙层样式优化 */
      .retry-lock-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        // backdrop-filter: blur(1.5px); /* 增加微弱的毛玻璃效果 */
        z-index: 10;
        display: flex;
        justify-content: center;
        align-items: center;

        .retry-lock-text {
          color: #ffffff;
          font-size: 13px;
          font-weight: bold;
          letter-spacing: 1px;
          background: rgba(245, 108, 108, 0.85); /* 红色警示背景 */
          padding: 4px 12px;
          border-radius: 12px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
        }
      }
    }
  }
}

.el-backtop {
  z-index: 9999;
}

@keyframes shake {
  0%, 100% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(-4px);
  }
  75% {
    transform: translateX(4px);
  }
}

/* ====================================================
   响应式适配 (1920px -> 800px)
   ==================================================== */
@media screen and (max-width: 1600px) {
  .pc-header .header-left .logo-container {
    margin-right: 20px;
  }
  .pc-header .header-left .top-nav-menu {
    gap: 20px;
  }
  .is-open {
    width: 300px !important;
  }
}

@media screen and (max-width: 1200px) {
  .pc-header {
    padding: 0 16px;
  }
  .pc-header .header-left .top-nav-menu .nav-item {
    font-size: 14px;
    padding: 6px 10px;
  }
  .pc-header .header-right {
    gap: 10px;
  }
  .is-open {
    width: 290px !important;
  }
}

@media screen and (max-width: 992px) {
  .pc-header .header-left .logo-container svg {
    width: 80px;
    height: 32px;
  }
  .pc-header .header-left .top-nav-menu {
    gap: 10px;
  }
  .pc-header .header-left .top-nav-menu .nav-item {
    font-size: 13px;
    padding: 4px 8px;
  }
  .pc-header .header-right .money-btn {
    padding: 6px 12px;
    font-size: 13px;
  }
  .is-open {
    width: 280px !important;
  }

  .right-sidebar .cart-expanded .cart-body .bet-item .item-header .team-names {
    font-size: 13px;
  }
  .right-sidebar .cart-expanded .cart-body .bet-item .item-info .odds-val {
    font-size: 14px;
  }
  .right-sidebar .cart-expanded .cart-body .bet-item .stake-input-box {
    height: 28px;
  }
}

@media screen and (max-width: 800px) {
  .pc-header {
    padding: 0 10px;
  }
  .pc-header .header-left .logo-container {
    margin-right: 10px;
  }
  .pc-header .header-left .top-nav-menu .nav-item {
    font-size: 12px;
    padding: 4px 6px;
  }
  .pc-header .header-right {
    gap: 6px;
  }
  .is-open {
    width: 260px !important;
  }

  .right-sidebar .cart-collapsed .vertical-text {
    font-size: 12px;
    letter-spacing: 2px;
  }
}

.is-closed {
  width: 50px;
}

.is-open {
  width: 320px;
}

.nav-links{
  display: flex;
  flex-direction: column;
  gap: 10px;
  li{
    list-style: none;
    cursor: pointer;
    transition: .3s;
  }
  li:hover{
    color: $main-color;
  }
}
.right-top-icon{
  width: 24px;
}
.is-closed{
   height: calc(100% - 20px);
}
</style>
