<template>
  <div class="wallet-page">
    <!-- 导航栏 -->
    <s-header name="我的钱包" :noback="false" :isBorder="false"></s-header>

    <div class="wallet-content">
      <!-- 新增提示栏 -->
      <van-notice-bar
        v-if="showNotice"
        left-icon="info"
        color="#ed6a0c"
        background="#fef6e6"
        scrollable
      >
        温馨提示：今日收款金额
        {{ formatAmount(receivableBalance) }} 元将于T+1日结算后可提现
      </van-notice-bar>
      <!-- 余额概览 -->
      <div class="balance-section">
        <div class="section-title">
          <van-icon name="balance-list" color="#2d88c9" size="18" />
          <span>资金账户</span>
        </div>

        <div class="balance-cards">
          <!-- 今日收款卡片 -->
          <div class="balance-card today-card" v-if="user.payPlatform === '0'">
            <div class="card-header">
              <van-icon name="cash-back-record" color="white" size="18" />
              <div class="card-title">
                <h3>今日收款余额（元）</h3>
              </div>
            </div>
            <div class="amount">{{ formatAmount(receivableBalance) }}</div>
            <van-button icon="cash-back-record" @click="handleRecharge">
              立即充值
            </van-button>
          </div>

          <!-- 可提现卡片 -->
          <div class="balance-card withdraw-card">
            <div class="card-header">
              <van-icon name="cash-on-deliver" color="white" size="18" />
              <div class="card-title">
                <h3>可提现余额（元）</h3>
              </div>
            </div>
            <div class="amount">{{ formatAmount(withdrawableBalance) }}</div>
            <van-button icon="cash-on-deliver" @click="handleWithdraw">
              立即提现
            </van-button>
          </div>
        </div>
      </div>

      <!-- 记录入口 -->
      <div class="record-section">
        <div class="section-title">
          <van-icon name="records" color="#2d88c9" size="18" />
          <span>交易记录</span>
        </div>
        <div class="record-cards">
          <!-- <div class="record-card" @click="goToAutoRecord">
                        <div class="card-icon auto">
                            <van-icon name="passed" size="24" />
                        </div>
                        <div class="card-content">
                            <h3>自动结算</h3>
                            <p>查看系统自动结算记录</p>
                        </div>
                        <van-icon name="arrow" size="16" color="#ccc" />
                    </div> -->

          <div class="record-card" @click="jumpTo('/withdrawList')">
            <div class="card-icon manual">
              <van-icon name="cash-on-deliver" size="24" />
            </div>
            <div class="card-content">
              <h3>手动提现</h3>
              <p>查看手动提现操作记录</p>
            </div>
            <van-icon name="arrow" size="16" color="#ccc" />
          </div>
        </div>
      </div>

      <!-- 银行卡管理 -->
      <div class="bank-section">
        <div class="section-title">
          <van-icon name="credit-pay" color="#2d88c9" size="18" />
          <span>银行卡管理</span>
        </div>

        <div class="bank-cards">
          <!-- 已绑卡状态 -->
          <div class="bank-card" v-if="hasBankCard">
            <div
              @click="
                jumpTo(user.payPlatform === '1' ? '/huifuBind' : '/joinPayBind')
              "
            >
              <div class="card-header">
                <van-icon name="card" size="20" />
                <span>已绑定</span>
              </div>
              <div class="card-number">{{ bankCardNo }}</div>
            </div>
            <div class="auto-settle-hint">
              <van-switch
                :model-value="autoSettle"
                size="20px"
                active-color="#2d88c9"
                @update:model-value="changeSettle"
              />
              <span v-if="autoSettle">已启用自动结算</span>
              <span v-else>已关闭自动结算</span>
            </div>
          </div>

          <!-- 未绑卡状态 -->
          <div
            class="bank-card empty-state"
            @click="
              jumpTo(user.payPlatform === '1' ? '/huifuBind' : '/joinPayBind')
            "
            v-else
          >
            <div class="empty-content">
              <p class="empty-title">尚未绑定银行卡</p>
              <p class="empty-desc">绑定后可享受快捷支付服务</p>
              <van-button type="primary" round size="small" class="bind-btn">
                <van-icon name="plus" size="16" />
                立即绑卡
              </van-button>
            </div>
          </div>
        </div>
      </div>
      <div class="bottom-spacer"></div>
      <!--提现弹窗-->
      <van-popup
        v-model:show="showWithdrawPopup"
        position="bottom"
        round
        :style="{ height: '40%' }"
      >
        <div class="withdraw-popup">
          <h3 class="popup-title">提现金额</h3>

          <div class="amount-input">
            <span class="currency-symbol">¥</span>
            <van-field
              v-model="withdrawAmount"
              type="number"
              placeholder="请输入提现金额"
              :formatter="formatterAmount"
            />
          </div>

          <div class="balance-hint">
            可提现余额 {{ formatAmount(withdrawableBalance) }} 元
          </div>

          <van-button
            type="primary"
            block
            round
            class="confirm-btn"
            @click="confirmWithdraw"
          >
            确认提现
          </van-button>
        </div>
      </van-popup>
    </div>
  </div>
</template>

<script>
import sHeader from "../../components/SimpleHeader";
import {
  getBalance,
  withdraw,
  updateSettlement,
  updateMchSettle,
} from "../../service/purse/index";
import { onMounted, ref, reactive } from "vue";
import { getOneJoinPayMch } from "../../service/joinpayMch";
import {
  getHuifuId,
  getMerchantBusiness,
  addWithdraw,
} from "@/service/huifuMch";
import { getLoginUser } from "../../common/js/utils";
import { useRouter } from "vue-router";
import {
  showConfirmDialog,
  showFailToast,
  showSuccessToast,
  showToast,
} from "vant";
import { useI18n } from "vue-i18n";

export default {
  components: { sHeader },
  setup() {
    const { t } = useI18n();
    const user = getLoginUser();
    const router = useRouter();
    const receivableBalance = ref(0.0); // 今日收款余额
    const withdrawableBalance = ref(0.0); // 可提现余额
    const autoSettle = ref(false);
    const hasBankCard = ref(false);
    const bankCardInfo = ref(null);
    const bankCardNo = ref("");
    // 通知栏显示控制
    const showNotice = ref(false);
    // 提现弹窗数据
    const showWithdrawPopup = ref(false);
    const withdrawAmount = ref("");
    const withdrawaParams = ref({
      adminId: user.id,
      amount: 0,
      payPlatform: user.payPlatform,
      companyType: user.companyType,
    });
    const handleRecharge = () => {
      showToast({ message: "暂未开放" });
    };

    // 新增金额格式化方法
    const formatterAmount = (value) => {
      // 只允许输入数字和小数点
      value = value.replace(/[^\d.]/g, "");

      // 处理多个小数点的情况
      const pointIndex = value.indexOf(".");
      if (pointIndex > -1) {
        value = value.slice(0, pointIndex + 3); // 限制小数点后两位
      }

      return value;
    };

    // 新增确认提现方法
    const confirmWithdraw = async () => {
      const amount = Number(withdrawAmount.value);

      if (!amount || amount <= 0) {
        showToast("请输入有效的提现金额");
        return;
      }

      if (amount > withdrawableBalance.value) {
        showToast("提现金额不可超过可用余额");
        return;
      }
      withdrawaParams.value.amount = amount;
      console.log("withdrawaParams", withdrawaParams.value);
      showConfirmDialog({
        message: "确定要提现 " + amount + " 元吗？",
      }).then(async () => {
        const { data } = await withdraw(withdrawaParams.value);
        if (data.code === "00000") {
          showSuccessToast("申请成功");
          setTimeout(async () => {
            await queryBalance();
          }, 1500);
        }
      });
      showWithdrawPopup.value = false;
    };

    // 点击提现
    const handleWithdraw = () => {
      if (!hasBankCard.value) {
        showConfirmDialog({
          title: "未绑定银行卡",
          message: "提现需要先绑定银行卡，是否立即绑定？",
          confirmButtonColor: "#2d88c9",
        }).then(() => {
          router.push(user.payPlatform === "1" ? "/huifuBind" : "/joinPayBind");
        });
        return;
      }
      if (
        bankCardInfo.value.settMode === 1 ||
        bankCardInfo.value.settType === 1
      ) {
        showToast("当前银行卡为自动结算，请先切换成手动提现");
        return;
      }

      showWithdrawPopup.value = true;
    };

    const goToAutoRecord = () => {
      showToast({ message: "暂未开放" });
    };

    const goToManualRecord = () => {
      showToast({ message: "暂未开放" });
    };
    onMounted(async () => {
      await getBankCard();
      await queryBalance();
      if (
        user.payPlatform === "0" &&
        bankCardInfo.value &&
        (bankCardInfo.value.settMode === 2 || bankCardInfo.value.settType === 2)
      ) {
        showNotice.value = true;
      }

      // 查询汇付是否开启取现功能
      if (
        user.payPlatform === "1" &&
        bankCardInfo.value.huifuId != null &&
        bankCardInfo.value.tokenNo == null
      ) {
        const { data } = await getMerchantBusiness({ adminId: user.id });
        if (data.code === "00000") {
          if (data.data === null || data.data === "") {
            const { res } = await addWithdraw({ adminId: user.id });
            if (res.code === "00000") {
              console.log("res", res.data);
            }
          }
        }
      }
    });

    // 查询余额
    const queryBalance = async () => {
      try {
        const { data } = await getBalance({ adminId: user.id });
        if (data.code === "00000") {
          if (data.data.receivableBalance != null) {
            receivableBalance.value = data.data.receivableBalance;
          }
          if (data.data.withdrawableBalance != null) {
            withdrawableBalance.value = data.data.withdrawableBalance;
          }
        }
      } catch (error) {
        console.log("error", error);
      }
    };

    // 格式化金额
    const formatAmount = (amount) => {
      return new Intl.NumberFormat("en-US", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(Number(amount));
    };

    // 获取绑定银行卡
    const getBankCard = async () => {
      if (user.payPlatform && user.payPlatform == "1") {
        // 汇付
        const { data } = await getHuifuId({ adminId: user.id });
        if (data.code === "00000" && data.data) {
          bankCardInfo.value = data.data;
          if (bankCardInfo.value.cardNo != null) {
            bankCardNo.value = formatBankCard(bankCardInfo.value.cardNo);
            hasBankCard.value = true;
          }
          if (data.data.settType === 1) {
            autoSettle.value = true;
          }
        }
      } else {
        // 汇聚
        const { data } = await getOneJoinPayMch({ adminId: user.id });
        if (data.code === "00000" && data.data) {
          bankCardInfo.value = data.data;
          if (bankCardInfo.value.bankAccountNo != null) {
            bankCardNo.value = formatBankCard(bankCardInfo.value.bankAccountNo);
            hasBankCard.value = true;
          }
          if (data.data.settMode === 1) {
            autoSettle.value = true;
          }
        }
      }
    };

    // 格式化银行卡号
    const formatBankCard = (cardNumber) => {
      if (!cardNumber) return "未获取卡号";
      const cleaned = cardNumber.toString().replace(/\D/g, "");

      // 动态分组逻辑
      const lastFour = cleaned.slice(-4);
      const starCount = Math.max(cleaned.length - 4, 0);
      const starGroups = Array(Math.ceil(starCount / 4))
        .fill("****")
        .join(" ");

      return `${starGroups} ${lastFour}`.trim();
    };

    // 跳转绑卡页面
    const jumpTo = (value) => {
      router.push({ path: value });
    };

    // 切换订单通知开关
    const changeSettle = (value) => {
      showConfirmDialog({
        title: t("user.tips"),
        message: autoSettle.value
          ? "确定关闭自动结算吗？"
          : "确定开启自动结算吗？",
      })
        .then(async () => {
          if (user.payPlatform === "1") {
            // 汇付
            const params = reactive({
              adminId: user.id,
              settType: value ? 1 : 2,
            });
            const { data } = await updateSettlement(params);
            if (data.code === "00000") {
              showSuccessToast(
                value ? t("user.openSuccess") : t("user.closeSuccess")
              );
              setTimeout(() => {
                router.go(0);
              }, 1500);
            } else {
              showFailToast(data.message);
            }
          }
          if (user.payPlatform === "0") {
            // 汇聚
            const params = reactive({
              adminId: user.id,
              settMode: value ? 1 : 2,
            });
            const { data } = await updateMchSettle(params);
            if (data.code === "00000") {
              showSuccessToast(
                value ? t("user.openSuccess") : t("user.closeSuccess")
              );
              setTimeout(() => {
                router.go(0);
              }, 1500);
            } else {
              showFailToast(data.message);
            }
          }
        })
        .catch((error) => {
          console.error(error);
        });
    };

    return {
      handleRecharge,
      goToAutoRecord,
      goToManualRecord,
      receivableBalance,
      withdrawableBalance,
      formatAmount,
      bankCardInfo,
      hasBankCard,
      autoSettle,
      formatBankCard,
      jumpTo,
      changeSettle,

      // 提现
      handleWithdraw,
      showWithdrawPopup,
      withdrawAmount,
      formatterAmount,
      confirmWithdraw,

      // 通知栏
      showNotice,

      // 数据
      bankCardNo,
      user,
    };
  },
};
</script>

<style lang="less" scoped>
/* 公共样式 */
.wallet-page {
  background: #f8f9ff;
}

.wallet-content {
  background: #f5f6fa;
  height: calc(100% - 50px);
  overflow: auto;
  overflow-x: hidden;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 10px 10px;
  font-size: 18px;
  color: #2d88c9;
  font-weight: 700;
}

/**
余额卡片
 */
.balance-section {
  margin: 10px 0px;
}

.balance-cards {
  display: grid;
  gap: 15px;
  padding: 0 12px;
}

/* 基础卡片样式 */
.balance-card {
  border-radius: 16px;
  padding: 15px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 8px 24px -6px rgba(0, 0, 0, 0.12);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  min-height: 180px;
}

/* 卡片悬停动效 */
.balance-card:hover {
  transform: translateY(-5px);
}

/* 今日收款卡片 */
.today-card {
  background: linear-gradient(135deg, #4f6cdf 0%, #6b8cff 100%);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.15);
  --start-color: #4f6cdf;
  --end-color: #6b8cff;
}

/* 可提现卡片 */
.withdraw-card {
  background: linear-gradient(135deg, #38b48d 0%, #5cd4b0 100%);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.15);
  --start-color: #38b48d;
  --end-color: #5cd4b0;
}

/* 装饰性光斑 */
.balance-card::after {
  content: "";
  position: absolute;
  width: 200px;
  height: 200px;
  background: radial-gradient(
    circle,
    rgba(255, 255, 255, 0.15) 0%,
    rgba(255, 255, 255, 0) 70%
  );
  top: -50px;
  right: -50px;
}

/* 卡片内容样式 */
.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  position: relative;
  z-index: 1;
}

.card-header .van-icon {
  background: rgba(255, 255, 255, 0.15);
  padding: 5px;
  border-radius: 10px;
}

.card-title h3 {
  margin: 0;
  font-size: 15px;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.amount {
  font-size: 30px;
  font-weight: 600;
  margin: 10px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
}

/* 按钮样式 */
/* 限定在卡片内的按钮 */
.balance-card .van-button {
  backdrop-filter: blur(8px);
  background: rgba(255, 255, 255, 0.15) !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
  color: white !important;
  border-radius: 20px;
  transition: all 0.3s ease;
  width: auto;
}

/* 仅影响卡片内的按钮悬停状态 */
.balance-card .van-button:hover {
  background: rgba(255, 255, 255, 0.25) !important;
  transform: scale(1.05);
}

/* 提示文字 */
.hint-text {
  font-size: 12px;
  opacity: 0.9;
  margin-top: 12px;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .amount {
    font-size: 28px;
  }

  .balance-card {
    min-height: 140px;
    padding: 16px;
  }
}

/* 动态光效增强 */
@keyframes glow {
  0% {
    opacity: 0.5;
  }

  50% {
    opacity: 0.8;
  }

  100% {
    opacity: 0.5;
  }
}

.balance-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    45deg,
    transparent 40%,
    rgba(255, 255, 255, 0.1) 50%,
    transparent 60%
  );
  animation: glow 3s infinite;
  pointer-events: none;
}

/* 记录入口 */
.record-section {
  margin-top: 5px;
}

.record-cards {
  display: grid;
  gap: 12px;
}

.record-card {
  background: white;
  border-radius: 12px;
  padding: 0 10px;
  margin: 0 10px;
  display: flex;
  align-items: center;
  gap: 12px;
  box-shadow: 0 2px 8px rgba(77, 106, 221, 0.05);
  transition: transform 0.2s ease;

  &:active {
    transform: scale(0.98);
  }
}

.card-icon {
  width: 44px;
  height: 44px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;

  &.auto {
    background: rgba(77, 106, 221, 0.1);
    color: #2d88c9;
  }

  &.manual {
    background: rgba(255, 152, 0, 0.1);
    color: #ff9500;
  }
}

.card-content {
  flex: 1;

  h3 {
    font-size: 15px;
    color: #333;
    margin-bottom: 4px;
  }

  p {
    font-size: 12px;
    color: #999;
  }
}

/* 银行卡管理 */
.bank-section {
  margin-top: 5px;
}

.bank-cards {
  display: grid;
  gap: 12px;
}

.bank-card {
  background: white;
  border-radius: 12px;
  padding: 10px 5px;
  margin: 0 10px;
  box-shadow: 0 4px 12px rgba(77, 106, 221, 0.08);
  position: relative;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 4px;
    background: #2d88c9;
  }

  &.backup::before {
    background: #6a82ee;
  }
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;

  span {
    font-size: 14px;
    color: #666;
  }

  .van-tag {
    transform: scale(0.9);
  }
}

.card-number {
  font-family: monospace;
  font-size: 18px;
  color: #333;
  letter-spacing: 2px;
  margin: 16px 10px;
}

.card-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #999;
  padding: 0 10px;
  font-size: 12px;
}

/* 统一按钮样式 */
:deep(.van-button) {
  font-weight: 500;
  letter-spacing: 0.5px;
}

.auto-settle-hint {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px dashed #eee;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 13px;
  padding: 10px 5px;
}

/* 未绑卡状态样式 */
.bank-card.empty-state {
  background: linear-gradient(135deg, #ffffff 0%, #f6f7fc 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-content {
  text-align: center;
  padding: 10px;
}

.empty-icon {
  margin-bottom: 12px;
  filter: drop-shadow(0 2px 4px rgba(77, 106, 221, 0.1));
}

.empty-title {
  color: #2d3447;
  font-size: 16px;
  margin-bottom: 8px;
}

.empty-desc {
  color: #a3aac7;
  font-size: 12px;
  margin-bottom: 16px;
}

.bind-btn {
  background: #2d88c9;
  padding: 8px 24px;
  box-shadow: 0 3px 8px rgba(77, 106, 221, 0.2);
}

.bind-btn .van-icon {
  margin-right: 6px;
  vertical-align: -2px;
}

/* 占位元素样式 */
.bottom-spacer {
  height: 50px;
  height: calc(60px + env(safe-area-inset-bottom));
  pointer-events: none;
  /* 防止遮挡点击 */
}

/**
 * 提现弹窗样式
 */
.withdraw-popup {
  padding: 20px;
  display: flex;
  flex-direction: column;

  .popup-title {
    text-align: center;
    font-size: 18px;
    color: #333;
    margin-bottom: 20px;
  }

  .amount-input {
    display: flex;
    align-items: center;
    margin: 15px 0;
    border-bottom: 1px solid #eee;

    .currency-symbol {
      font-size: 24px;
      color: #333;
      margin-right: 8px;
    }

    :deep(.van-field) {
      padding: 10px 0;
      font-size: 22px;

      input {
        font-size: 22px;
        font-weight: 500;
      }
    }
  }

  .balance-hint {
    font-size: 12px;
    color: #999;
    margin-bottom: auto;
  }

  .confirm-btn {
    margin-top: 20px;
    background: #2d88c9;
    border: none;

    &:active {
      opacity: 0.9;
    }
  }
}
</style>
