<template>
  <div class="pc28-cart-container" :class="{ 'is-collapsed': !cartStore.isOpen }">

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

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

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

      <div v-if="cartStore.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 class="dark-empty" v-if="cartStore.selectedCount === 0" :description="t('暂无彩票投注项')" />

        <div class="bet-list" v-else>
          <div class="bet-item" v-for="item in cartStore.selectOrders" :key="item.uniqueKey">

            <div class="item-header">
              <span class="team-names">{{ item.groups }} - {{ item.keywords }}</span>
              <el-icon class="close-btn" @click.stop="cartStore.removeOrderItem(item.uniqueKey)"><Close /></el-icon>
            </div>

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

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

            <div class="stake-input-box" :class="{ 'error-border': Number(item.amount) > Number(userStore.balance) }">
              <el-button class="stepper-btn" link @click="changeAmount(item, -10)">-</el-button>
              <el-input
                  v-model="item.amount"
                  type="number"
                  class="stake-input"
                  @blur="validateAmount(item)"
                  :placeholder="t('本金')"
              />
              <el-button class="stepper-btn" link @click="changeAmount(item, 10)">+</el-button>
            </div>

            <div class="item-footer">
              <div v-if="Number(item.amount) > Number(userStore.balance)" class="err-msg">
                {{ t('投注额超过您的余额') }}
              </div>
              <div v-else class="potential-win">
                {{ t('预计可赢') }}: <span class="win-amount">{{ (Number(item.amount) * Number(item.odds)).toFixed(2) }}</span>
              </div>
            </div>

          </div>
        </div>
      </div>

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

        <el-button v-if="cartStore.totalStake > userStore.balance" type="primary" class="w-full bet-action-btn" @click="setShowRechargeModal">
          {{ t('余额不足，去存款') }}
        </el-button>
        <el-button v-else type="primary" class="w-full bet-action-btn" @click="submitBet">
          {{ t('立即投注') }}
        </el-button>
      </div>

    </div>

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

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

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { Tickets, ArrowRight, Delete, Close } from '@element-plus/icons-vue';

import { useExtremeSpeed28CartStore } from '@/store/ExtremeSpeed28Cart.js';
import { useUserStore } from '@/store/user/index.js';
import { submitGameBet, getBalance } from "@/request/api.js";
import RechargeModal from "@/businessComponents/RechargeModal/index.vue";

const { t } = useI18n();
const router = useRouter();

const cartStore = useExtremeSpeed28CartStore();
const userStore = useUserStore();

const showSafeModal = ref(false);
const safeWord = ref('');
const isSubmitting = ref(false);
const showRechargeModal = ref(false);

const batchStakeValue = ref(localStorage.getItem('extremeSpeed28BatchStakeCache') || '');

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

  if (val === '') {
    cartStore.selectOrders.forEach(item => {
      cartStore.updateStake(item.uniqueKey, '');
    });
    return;
  }

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

  cartStore.selectOrders.forEach(item => {
    let itemVal = numVal;
    const min = Number(item.mininum) || 0;
    const max = Number(item.maxinum) || 9999999;
    if (itemVal < min) {
      itemVal = min;
    }
    if (itemVal > max) {
      itemVal = max;
    }
    cartStore.updateStake(item.uniqueKey, itemVal);
  });
};

// 金额调节与失焦验证
const changeAmount = (item, delta) => {
  let val = Number(item.amount) || 0;
  const min = Number(item.mininum) || 0;
  const max = Number(item.maxinum) || 9999999;

  val += delta;

  if (val < min) { val = min; ElMessage.warning(`${t('已达最低投注')} ${min}`); }
  else if (val > max) { val = max; ElMessage.warning(`${t('已达最高投注')} ${max}`); }

  cartStore.updateStake(item.uniqueKey, val);
};

const validateAmount = (item) => {
  let val = Number(item.amount) || 0;
  const min = Number(item.mininum) || 0;
  const max = Number(item.maxinum) || 9999999;

  if (val < min) { val = min; ElMessage.warning(`${t('最低投注')} ${min}`); }
  else if (val > max) { val = max; ElMessage.warning(`${t('最高投注')} ${max}`); }

  cartStore.updateStake(item.uniqueKey, val);
};

// 提交逻辑
const submitBet = () => {
  if (cartStore.selectedCount === 0) return ElMessage.warning(t('请选择投注单'));
  if (cartStore.selectOrders.some(item => Number(item.amount) <= 0)) return ElMessage.warning(t('投注金额不能为0'));
  if (cartStore.totalStake > userStore.balance) return ElMessage.warning(t('余额不足'));

  safeWord.value = '';
  // showSafeModal.value = true;
  confirmSubmitBet()
};

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 = cartStore.selectOrders.map(item => ({
    id: item.id,
    amount: item.amount
  }));

  isSubmitting.value = true;
  try {
    const res = await submitGameBet({ data: ordersData, safe_word: safeWord.value, pc28: 1 });
    if (res && res.code === 1) {
      cartStore.clearAllOrders();
      showSafeModal.value = false;
      // 刷新用户余额
      const balanceRes = await getBalance();
      if (balanceRes.code === 1) userStore.balance = balanceRes.data.money;
    }
  } catch (error) {
    console.error('彩票投注失败', error);
  } finally {
    isSubmitting.value = false;
  }
};

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

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

.pc28-cart-container {
  height: 100%;
  background-color: $bg-sidebar;
  border-left: 1px solid $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: $bg-sidebar-hover; }

  .custom-cart-icon {
    position: relative;
    margin-bottom: 20px;
    display: flex; justify-content: center; align-items: center;
    .icon-color { color: $main-color; }
    .custom-badge {
      position: absolute; top: -6px; right: -10px;
      color: #fff; background-color: $main-color; font-size: 12px;
      padding: 2px 5px; line-height: 1; 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; color: $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 $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; color: $text-primary;
      .pointer { color: $text-secondary; display: flex; align-items: center; transition: transform 0.2s; }
      .header-badge { color: #fff; background-color: $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: $text-primary; font-size: 15px; }
    }
  }

  .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: 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: $text-primary; } .close-btn { cursor: pointer; z-index: 11; position: relative; color: $text-secondary; &: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; color: $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 $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; }
        .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 { color: $main-color; font-weight: bold; font-size: 18px; } }
    .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 { color: $main-color; border-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; } } .dark-input .el-input__inner { color: $text-primary; } }


/* ====================================================
   响应式适配 (与 Layout 完美同步)
   ==================================================== */
@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-body::-webkit-scrollbar { width: 8px; }
  .pc28-cart-container .cart-expanded .cart-body::-webkit-scrollbar-track { background: #2c2c2c; border-radius: 10px; }
  .pc28-cart-container .cart-expanded .cart-body::-webkit-scrollbar-thumb { background: #9f9f9f; border-radius: 10px; }
  .pc28-cart-container .cart-expanded .cart-body::-webkit-scrollbar-thumb:hover { background: #d1d1d1; cursor: pointer; }

  .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; }
  .pc28-cart-container .cart-expanded .cart-header .el-button { font-size: 11px !important; }
  .pc28-cart-container .cart-collapsed .custom-cart-icon .el-icon { font-size: 20px !important; }
}

@media screen and (max-width: 992px) {
  .pc28-cart-container:not(.is-collapsed) { width: 220px !important; }
  .pc28-cart-container.is-collapsed { width: 44px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-header .team-names { font-size: 10px; }
  .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: 10px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .limit-info { font-size: 10px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-info .odds-val { font-size: 10px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-footer .potential-win { font-size: 10px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-footer .potential-win .win-amount { font-size: 10px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-header { margin-bottom: 5px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-info { margin-bottom: 4px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .stake-input-box { height: 22px !important; }
  .pc28-cart-container .cart-expanded .cart-footer .total-odds-row { font-size: 10px; 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: 28px; font-size: 12px; }

  .pc28-cart-container .cart-expanded .cart-body::-webkit-scrollbar { width: 6px; }
  .pc28-cart-container .cart-expanded .cart-header { height: 36px; }
  .pc28-cart-container .cart-expanded .cart-header .header-badge { font-size: 10px !important; height: 12px !important; line-height: 12px !important; padding: 0 4px !important; }
}

@media screen and (max-width: 800px) {
  .pc28-cart-container:not(.is-collapsed) { width: 200px !important; }
  .pc28-cart-container.is-collapsed { width: 40px !important; }
  .pc28-cart-container .cart-collapsed .vertical-text { font-size: 12px; letter-spacing: 2px; }

  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-header .team-names { font-size: 8px; }
  .pc28-cart-container .cart-expanded .cart-header .header-text { font-size: 10px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-info .type-name { font-size: 9px; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .limit-info { font-size: 9px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-info .odds-val { font-size: 9px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-footer .potential-win { font-size: 9px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-footer .potential-win .win-amount { font-size: 9px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-header { margin-bottom: 4px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .item-info { margin-bottom: 3px !important; }
  .pc28-cart-container .cart-expanded .cart-body .bet-item .stake-input-box { height: 20px !important; }
  .pc28-cart-container .cart-expanded .cart-footer .bet-action-btn { height: 26px; font-size: 10px; }

  .pc28-cart-container .cart-expanded .cart-body::-webkit-scrollbar { width: 4px; }
  .pc28-cart-container .cart-expanded .cart-header { height: 32px; }
  .pc28-cart-container .cart-expanded .cart-header .header-badge { font-size: 9px !important; }
}
</style>