<template>
  <div class="pc28-cart-container"
       :class="{ 'is-collapsed': !betStore.isOpen }"
  >
    <div class="cart-collapsed" v-if="!betStore.isOpen" @click="betStore.setSheetOpen(true)">
      <div class="custom-cart-icon">
        <el-icon size="24" class="icon-color"><Tickets /></el-icon>
        <span class="custom-badge" v-if="betStore.totalBets > 0">
          {{ betStore.totalBets }}
        </span>
      </div>
      <div class="vertical-text">{{ t('六合注单') }}</div>
    </div>

    <div class="cart-expanded" v-else>
      <div class="cart-header" @click="betStore.setSheetOpen(false)">
        <div class="header-left">
          <el-icon class="pointer" size="20"><ArrowRight /></el-icon>
          <span class="header-badge" v-if="betStore.totalBets > 0">{{ betStore.totalBets }}</span>
          <span class="header-text">{{ t('六合注单') }}</span>
        </div>
        <el-button link type="danger" @click.stop="betStore.clearBets" v-if="betStore.totalBets > 0">
          <el-icon><Delete /></el-icon> {{ t('清空') }}
        </el-button>
      </div>

      <div v-if="betStore.totalBets > 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="betStore.totalBets === 0" :description="t('暂无六合彩投注项')" />

        <div class="bet-list" v-else>
          <div class="bet-item" v-for="item in betStore.selectedBets" :key="item.id">

            <div class="item-header">
              <span class="team-names">
                {{ item.gameName }} - {{ item.playName }}
                <strong :class="getTextColorClass(item.color)" style="margin-left: 4px;">{{ item.number }}</strong>
              </span>
              <el-icon class="close-btn" @click.stop="betStore.removeBet(item.id)"><Close /></el-icon>
            </div>

            <div class="item-info">
              <div style="display: flex; align-items: center;">
                <span class="type-name">{{ t('赔率') }}</span>
                <span class="limit-text" style="margin-left: 10px; font-size: 12px; color: #999;">
                  {{ t('单注限额') }} {{ item.mininum !== undefined ? item.mininum : 10 }} ~ {{ item.maxinum !== undefined ? item.maxinum : 10000 }}
                </span>
              </div>
              <span class="odds-val">{{ Number(item.odds).toFixed(2) }}</span>
            </div>

            <div class="stake-input-box" :class="{ 'error-border': (item.amount !== '' && item.amount !== undefined && Number(item.amount) <= 0) || (item.mininum !== undefined && item.amount !== '' && item.amount !== undefined && Number(item.amount) < (item.mininum !== undefined ? Number(item.mininum) : 10)) || (item.maxinum !== undefined && Number(item.amount) > (item.maxinum !== undefined ? Number(item.maxinum) : 10000)) || (Number(item.amount) > userMoney) }">
              <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="item.amount !== '' && item.amount !== undefined && Number(item.amount) <= 0" class="err-msg">
                {{ t('金额不能小于等于0') }}
              </div>
              <div v-else-if="item.amount !== '' && item.amount !== undefined && Number(item.amount) < (item.mininum !== undefined ? Number(item.mininum) : 10)" class="err-msg">
                {{ t('单注最低限制为') }} {{ item.mininum !== undefined ? item.mininum : 10 }}
              </div>
              <div v-else-if="Number(item.amount) > (item.maxinum !== undefined ? Number(item.maxinum) : 10000)" class="err-msg">
                {{ t('单注最高限制为') }} {{ item.maxinum !== undefined ? item.maxinum : 10000 }}
              </div>
              <div v-else-if="Number(item.amount) > userMoney" class="err-msg">
                {{ t('余额不足') }}
              </div>
              <div v-else class="potential-win">
                {{ t('预计可赢') }}: <span class="win-amount">{{ calculateWin(item) }}</span>
              </div>
            </div>

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

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

        <div class="action-buttons">
          <el-button plain type="warning" class="bet-action-btn random-btn" @click="betStore.triggerRandom">
            <el-icon style="margin-right: 4px"><MagicStick /></el-icon>{{ t('机选') }}
          </el-button>
          <el-button type="primary" class="bet-action-btn submit-btn" @click="submitBet">
            {{ t('立即投注') }}
          </el-button>
        </div>
      </div>
    </div>

    <el-dialog v-model="showSafeModal" :title="t('安全验证')" width="400px" center custom-class="dark-dialog" append-to-body>
      <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>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Tickets, ArrowRight, Delete, Close, MagicStick } from '@element-plus/icons-vue';
import { useBetCartStore } from '@/store/hkDigitalCart.js';
import { submitBetCart, getBalance } from '@/request/api.js';
import { useUserStore } from '@/store/user/index.js';
import { useI18n } from "vue-i18n";
import { useRouter, useRoute } from 'vue-router';
const { t } = useI18n()
const router = useRouter()

const betStore = useBetCartStore();
const userStore = useUserStore();
const route = useRoute();

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

const batchStakeValue = ref(localStorage.getItem('hklhcBatchStakeCache') || '');
const userMoney = ref(0);

const fetchBalance = async () => {
  try {
    const res = await getBalance();
    if (res.code === 1) {
      userMoney.value = Number(res.data.money);
    }
  } catch (error) {
    console.error('获取余额失败', error);
  }
};

onMounted(() => {
   if(localStorage.getItem('token')) {
    fetchBalance();
  }
});

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

  if (val === '') {
    betStore.selectedBets.forEach(item => {
      item.amount = '';
    });
    return;
  }

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

  betStore.selectedBets.forEach(item => {
    let itemVal = numVal;
    const min = item.mininum !== undefined ? Number(item.mininum) : 10;
    const max = item.maxinum !== undefined ? Number(item.maxinum) : 10000;
    if (itemVal < min) {
      itemVal = min;
    }
    if (itemVal > max) {
      itemVal = max;
    }
    if (itemVal > userMoney.value) {
      itemVal = userMoney.value;
      ElMessage.warning(t('余额不足'));
    }
    item.amount = itemVal;
  });
};

// 辅助：获取字体颜色类名
const getTextColorClass = (colorName) => {
  if (colorName === '红') return 'text-red';
  if (colorName === '蓝') return 'text-blue';
  if (colorName === '绿') return 'text-green';
  return 'text-normal';
};

// 计算可赢金额
const calculateWin = (item) => {
  const amount = Number(item.amount) || 0;
  const odds = Number(item.odds) || 0;
  return (amount * odds).toFixed(2);
};

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

  if (val < 0) {
    val = 0;
    item.amount = '';
    return;
  }

  if (val > 0 && val < min) {
    val = min;
    ElMessage.warning(t('单注最低') + ` ${min}`);
  } else if (val > max) {
    val = max;
    ElMessage.warning(t('单注最高') + ` ${max}`);
  } else if (val > userMoney.value) {
    val = userMoney.value;
    ElMessage.warning(t('余额不足'));
  }
  item.amount = val || '';
};

const validateAmount = (item) => {
  let val = Number(item.amount);
  const min = item.mininum !== undefined ? item.mininum : 10;
  const max = item.maxinum !== undefined ? item.maxinum : 10000;

  if (isNaN(val) || val <= 0) {
    item.amount = '';
  } else if (val < min) {
    ElMessage.warning(t('单注最低') + ` ${min}`);
    item.amount = min;
  } else if (val > max) {
    ElMessage.warning(t('单注最高') + ` ${max}`);
    item.amount = max;
  } else if (val > userMoney.value) {
    ElMessage.warning(t('余额不足'));
    item.amount = userMoney.value;
  }
};

// 提交逻辑
const submitBet = () => {
   if(!localStorage.getItem('token')) {
    ElMessage.warning(t('请先登录'));
    router.push({ name: 'login' });
    return;
  }
  if (betStore.totalBets === 0) return ElMessage.warning(t('请选择投注单'));
  
  if (betStore.totalAmount > userMoney.value) {
    return ElMessage.warning(t('总投注金额超过可用余额'));
  }

  const invalidItems = betStore.selectedBets.filter(item => {
    const val = Number(item.amount);
    const min = item.mininum !== undefined ? item.mininum : 10;
    const max = item.maxinum !== undefined ? item.maxinum : 10000;
    return !val || val < min || val > max || val > userMoney.value;
  });

  if (invalidItems.length > 0) {
    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 = betStore.selectedBets.map(item => ({
    id: item.id,
    amount: Number(item.amount)
  }));

  isSubmitting.value = true;
  try {
    let obj = { type: 2 }
    const res = await submitBetCart({ data: ordersData, safe_word: safeWord.value, ...obj });
    if (res && res.code === 1) {
      // ElMessage.success(t('投注成功'));
      betStore.clearBets();
      showSafeModal.value = false;
      // 刷新用户余额
      const balanceRes = await getBalance();
      if (balanceRes.code === 1) {
        userStore.balance = balanceRes.data.money;
        userMoney.value = Number(balanceRes.data.money);
      }
    }
  } catch (error) {
    console.error(t('投注失败'), error);
  } finally {
    isSubmitting.value = false;
  }
};
</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;

.text-red { color: #f11717; }
.text-blue { color: #0e86e3; }
.text-green { color: #38be4f; }
.text-normal { color: #e5e5e5; }

.pc28-cart-container {
  height: 100%;
  background-color: $bg-sidebar;
  border-left: 1px solid $border-color;
  display: flex;
  flex-direction: column;
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 2000;
  box-shadow: -4px 0 20px rgba(0, 0, 0, 0.5);
  width: 320px;
}

.is-collapsed{ width: 50px;}

.cart-collapsed {
  min-width: 50px;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  //justify-content: center;
  cursor: pointer;
  padding-top: 20px;
  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 {
  min-width: 320px;
  display: flex;
  flex-direction: column;
  height: 100%;

  .cart-header {
    height: 60px; 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: 12px;
        .type-name { color: $text-secondary; }
        .odds-val { font-weight: bold; color: $main-color; font-size: 16px; font-family: DIN; }
      }

      .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: $main-color; font-family: DIN; }
      }
      .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; font-family: DIN; }
      }
    }
  }

  .cart-footer {
    padding: 16px; border-top: 1px solid $border-color; background: $bg-sidebar;
    .total-odds-row {
      display: flex; justify-content: space-between; margin-bottom: 16px; font-size: 14px; color: $text-primary;
      .label { font-weight: bold; }
      .val { color: $main-color; font-weight: bold; font-size: 18px; font-family: DIN; }
    }

    .action-buttons {
      display: flex; gap: 10px;
      .bet-action-btn { height: 44px; font-size: 15px; font-weight: bold; }
      .random-btn { flex: 1; border-color: $main-color; color: $main-color; background: transparent; &:hover { background: rgba(248, 185, 50, 0.1); } }
      .submit-btn { flex: 2; color: #000; background-color: $main-color; border-color: $main-color; }
    }
  }
}

: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; }
}

/* ====================================================
   响应式适配
   ==================================================== */
@media screen and (max-width: 1600px) {
  .pc28-cart-container .cart-expanded .cart-header { height: 50px; padding: 0 12px; }
  .pc28-cart-container .cart-expanded .cart-body { padding: 10px; }
  .pc28-cart-container .cart-expanded .cart-footer { padding: 12px; }
}

@media screen and (max-width: 1350px) {
  .pc28-cart-container .cart-expanded .cart-header .header-text { font-size: 13px; }
  .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 .stake-input-box { height: 28px; }
  .pc28-cart-container .cart-expanded .cart-footer { padding: 10px; }
  .pc28-cart-container .cart-expanded .cart-footer .action-buttons .bet-action-btn { height: 36px; font-size: 14px; }
}

@media screen and (max-width: 1200px) {
  .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 .stake-input-box { height: 24px !important; }
  .pc28-cart-container .cart-expanded .cart-footer .action-buttons .bet-action-btn { height: 32px; font-size: 13px; }

  .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; }
}
</style>