<template>
  <div class="wallet-container">

    <div class="wallet-toolbar" role="region" aria-label="钱包操作">
      <el-button 
        type="primary"
        class="create-wallet-btn"
        @click="openCreateWallet"
      >
        <i class="el-icon-plus" style="margin-right:6px;"></i>充值
      </el-button>
    </div>
    <!-- 多个钱包余额卡片 -->
     <section class="wallet-card-section">
    <div class="wallet-card" v-for="w in walletList" :key="w.id">
      <div class="wallet-header">
        <h2 class="wallet-title"> 
          <i class="el-icon-wallet"></i> 我的钱包
          <el-tag size="mini" effect="dark" style="margin-left:8px;">
            {{ (w.fromChain || w.chain || '').toUpperCase() }} {{ (w.fromSymbol || w.coin || '').toUpperCase() }}
          </el-tag>
        </h2>
        <div class="wallet-balance">
          <div class="balance-item">
            <span class="balance-label">可用余额</span>
            <span class="balance-amount">{{ (w.walletBalance || w.balance || 0) }} {{ displaySymbol(w) }}</span>
          </div>
          <div class="balance-item">
            <el-tooltip placement="top" effect="dark">
              <div slot="content">
                冻结金额不能使用或提现，以下情况会冻结钱包余额：<br/>
                1. 下单机器后会冻结订单对应金额<br/>
                2. 提交提现后，金额正在提现中
              </div>
              <i class="el-icon-question balance-tip-icon"></i>
            </el-tooltip>
            <span class="balance-label">冻结余额</span>
            <span class="balance-amount frozen">{{ (w.blockedBalance || 0) }} {{ displaySymbol(w) }}</span>
          </div>
        <el-button 
          type="success" 
          size="mini" 
          class="withdraw-inline-btn"
          @click="handleWithdraw(w)"
        >
          提现
        </el-button>
        </div>
      </div>
    </div>
  </section>
    <!-- 交易记录区域 -->
    <div class="transaction-section">
      <h3 class="section-title">最近交易</h3>
      <div class="transaction-list">
        <div 
          v-for="transaction in recentTransactions" 
          :key="transaction.id"
          class="transaction-item"
        >
          <div class="transaction-info">
            <span class="transaction-type">{{ transaction.type }}</span>
            <span class="transaction-time">{{ transaction.time }}</span>
            <el-tag
              size="mini"
              class="transaction-status"
              :type="transaction.statusTagType || 'info'"
            >
              {{ transaction.statusText || '-' }}
            </el-tag>
          </div>
          <div class="transaction-amount" :class="transaction.amount > 0 ? 'positive' : 'negative'">
            {{ transaction.amount > 0 ? '+' : '' }}{{ transaction.amountText }} USDT
          </div>
        </div>
        <div v-if="recentTransactions.length === 0" class="empty-state">
          暂无交易记录
        </div>
      </div>
    </div>

    <!-- 充值对话框 -->
    <el-dialog
      title="钱包余额充值"
      :visible.sync="rechargeDialogVisible"
      width="660px"
      @close="resetRechargeForm"
    >
      <div class="recharge-content">
        <!-- 钱包地址区域 -->
        <div class="wallet-address-section">
          <h4 class="section-title">钱包地址</h4>
          <div class="charge-meta">
            <el-tag size="small" effect="dark" type="warning" class="meta-tag">
              <i class="el-icon-link"></i>
              <span class="meta-title">充值链：</span>
              <span class="meta-val">{{ (WalletData.fromChain || WalletData.chain || '').toString().toUpperCase() }}</span>
            </el-tag>
            <el-tag size="small" effect="dark" type="warning" class="meta-tag">
              <i class="el-icon-coin"></i>
              <span class="meta-title">充值币种：</span>
              <span class="meta-val">{{ (WalletData.fromSymbol || WalletData.coin || '').toString().toUpperCase() }}</span>
            </el-tag>
          </div>
          <div class="address-container">
            <el-input
              v-model="WalletData.fromAddress"
              readonly
              class="address-input"
              :disabled="true"
            />
            <el-button 
              type="primary" 
              size="small" 
              @click="copyAddress(WalletData.fromAddress)"
              class="copy-btn"
            >
              复制
            </el-button>
          </div>
          <p class="address-tip">请向此地址转账非{{ displaySymbol(WalletData) }}资产，否则资产将无法找回.</p>
        </div>

        <!-- 二维码区域 -->
        <div class="qr-code-section">
          <h4 class="section-title">扫码充值</h4>
          <div class="qr-code-container">
            <div class="qr-code" ref="qrCodeRef">
              <!-- 二维码将在这里生成 -->
            </div>
            <p class="qr-tip">使用支持{{ displaySymbol(WalletData)  }}的钱包扫描二维码</p>
          </div>
        </div>

        <!-- 充值说明 -->
        <div class="recharge-notice">
          <h4 class="section-title">充值说明</h4>
          <ul class="notice-list">
            <li>充值后请耐心等待余额更新或在资金流水页面查看最新充值记录</li>
            <li>最小充值金额：10 {{ displaySymbol(WalletData)  }}</li>        
          </ul>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="rechargeDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 提现对话框 -->
    <el-dialog
      title="USDT提现"
      :visible.sync="withdrawDialogVisible"
      width="720px"
      @close="resetWithdrawForm"
       :close-on-click-modal="false" :close-on-press-escape="false"
    >
      <el-form :model="withdrawForm" :rules="withdrawRules" ref="withdrawForm" label-width="120px">
        <!-- 提现链（只读展示当前钱包链） -->
        <el-form-item label="提现链">
          <el-input 
            :value="(WalletData.fromChain || WalletData.chain || withdrawForm.toChain || '').toString().toUpperCase()"
            :disabled="true"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 提现币种（只读展示当前钱包币种） -->
        <el-form-item label="提现币种">
          <el-input 
            :value="displayWithdrawSymbol"
            :disabled="true"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 提现金额 -->
        <el-form-item label="提现金额" prop="amount">
          <el-input
            v-model="withdrawForm.amount"
            placeholder="请输入提现金额"
            style="width: 100%"
            inputmode="decimal"
            @input="handleAmountInput"
          >
            <template slot="append">{{ displayWithdrawSymbol }}</template>
          </el-input>
          <div class="balance-info">
            <div class="balance-total">钱包总余额：{{ totalBalance }} {{ displayWithdrawSymbol }}</div>
            <div class="balance-row">
              <span>可用余额：{{ availableWithdrawBalance }} {{ displayWithdrawSymbol }}</span>
              <span class="divider">|</span>
              <span class="frozen-info">
                <el-tooltip placement="top" effect="dark">
                  <div slot="content">
                    冻结金额不能使用或提现，以下情况会冻结钱包余额：<br/>
                    1. 下单机器后会冻结订单对应金额<br/>
                    2. 提交提现后，金额正在提现中
                  </div>
                  <i class="el-icon-question frozen-tip-icon"></i>
                </el-tooltip>
                冻结余额：{{ (WalletData.blockedBalance || 0) }} {{ displayWithdrawSymbol }}
                <span class="frozen-tip">（购买机器下单后冻结，不可提现）</span>
              </span>
            </div>
          </div>
        </el-form-item>

        <!-- 手续费 -->
        <el-form-item label="手续费">
          <el-input
            v-model="withdrawForm.fee"
            placeholder="手续费"
            style="width: 100%"
            :disabled="true"
          >
            <template slot="append">{{ displayWithdrawSymbol }}</template>
          </el-input>
          <div class="fee-info">
            网络手续费：{{ withdrawForm.fee || '0.00' }} {{ displayWithdrawSymbol }}
          </div>
        </el-form-item>

        <!-- 实际到账金额 -->
        <el-form-item label="实际到账">
          <el-input
            v-model="actualAmount"
            placeholder="实际到账金额"
            style="width: 100%"
            :disabled="true"
          >
            <template slot="append">{{ displayWithdrawSymbol }}</template>
          </el-input>
          <div class="actual-amount-info">
            实际到账：{{ actualAmount }} {{ displayWithdrawSymbol }}
          </div>
        </el-form-item>

        <!-- 收款地址 -->
        <el-form-item label="收款地址" prop="toAddress">
          <el-input
            v-model="withdrawForm.toAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入收款钱包地址"
            style="width: 100%"
          />
          <div class="address-tip">
            请确保地址正确，错误地址将导致资产丢失
          </div>
        </el-form-item>

        <!-- 谷歌验证码 -->
        <el-form-item label="谷歌验证码" prop="googleCode">
          <el-input
            v-model="withdrawForm.googleCode"
            placeholder="请输入6位谷歌验证码"
            maxlength="6"
            style="width: 100%"
            @input="handleGoogleCodeInput"
            ref="googleCodeInput"
          >
            <template slot="prepend">
              <i class="el-icon-key"></i>
            </template>
          </el-input>
          <div class="google-code-tip">
            为了保障您的账户安全，请输入您的谷歌验证器中的6位验证码
          </div>
        </el-form-item>

      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="withdrawDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmWithdraw" :loading="withdrawLoading">确认提现</el-button>
      </div>
    </el-dialog>

    <!-- 链上充值 对话框 -->
    <el-dialog
      title="链上充值"
      :visible.sync="createDialogVisible"
       :close-on-click-modal="false" :close-on-press-escape="false"
      width="520px"
    >
      <el-form label-width="120px">
        <el-form-item label="选择充值链/币种">
          <el-cascader
            v-model="createValue"
            :options="options"
            style="width: 100%"
          
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCreateWallet" :loading="createLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getWalletInfo, withdrawBalance ,balanceRechargeList,balanceWithdrawList,getRecentlyTransaction} from '@/api/wallet'

import { getChainAndList,bindWallet } from "../../api/wallet";
import { rsaEncrypt, rsaEncryptSync } from '@/utils/rsaEncrypt'
export default {
  name: 'WalletPage',
  data() {
    return {
      // 钱包余额
      // 单钱包旧字段（兼容保留，不再直接渲染）
      walletBalance: 0,
      blockedBalance: 0, // 冻结余额
      // 多钱包列表
      walletList: [],
      WalletData: {},
      // 充值对话框相关
      rechargeDialogVisible: false,
      qrCodeGenerated: false,
      
      // 提现对话框相关
      withdrawDialogVisible: false,
      withdrawLoading: false,
      withdrawForm: {
        toChain: 'tron',
        toSymbol: 'USDT',
        amount: '',
        toAddress: '',
        fee: '1.00', // 默认手续费
        googleCode: '' // 谷歌验证码
      },
      withdrawRules: {
        toChain: [
          { required: true, message: '请选择区块链网络', trigger: 'change' }
        ],
        toSymbol: [
          { required: true, message: '请选择提现币种', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入提现金额', trigger: 'blur' },
          { validator: this.validateWithdrawAmount, trigger: 'blur' }
        ],
        toAddress: [
          { required: true, message: '请输入收款地址', trigger: 'blur' },
          { validator: this.validateAddress, trigger: 'blur' }
        ],
        googleCode: [
          { required: true, message: '请输入谷歌验证码', trigger: 'blur' },
          { validator: this.validateGoogleCode, trigger: 'blur' }
        ]
      },
      
      // 链选项
      chainOptions: [
        { label: 'Tron (TRC20)', value: 'tron' },
        // { label: 'Ethereum (ERC20)', value: 'ethereum' },
        // { label: 'BSC (BEP20)', value: 'bsc' },
        // { label: 'Polygon (MATIC)', value: 'polygon' }
      ],
      options: [],
      loading: false,
      // 新建钱包弹窗
      createDialogVisible: false,
      createLoading: false,
      createValue: [],
      // 币种选项（根据链动态变化）
      tokenOptions: {
        tron: [
          { label: 'USDT (TRC20)', value: 'USDT' },
          // { label: 'TRX', value: 'TRX' }
        ],
        // ethereum: [
        //   { label: 'USDT (ERC20)', value: 'USDT' },
        //   { label: 'ETH', value: 'ETH' },
        //   { label: 'USDC (ERC20)', value: 'USDC' }
        // ],
        // bsc: [
        //   { label: 'USDT (BEP20)', value: 'USDT' },
        //   { label: 'BNB', value: 'BNB' },
        //   { label: 'BUSD (BEP20)', value: 'BUSD' }
        // ],
        // polygon: [
        //   { label: 'USDT (MATIC)', value: 'USDT' },
        //   { label: 'MATIC', value: 'MATIC' },
        //   { label: 'USDC (MATIC)', value: 'USDC' }
        // ]
      },
      
      
      // 最近交易记录
      recentTransactions: [
        // {
        //   id: 1,
        //   type: '充值',
        //   amount: 500.00,
        //   time: '2024-01-15 14:30'
        // },
        // {
        //   id: 2,
        //   type: '购买商品',
        //   amount: -89.50,
        //   time: '2024-01-14 10:20'
        // },
        // {
        //   id: 3,
        //   type: '提现',
        //   amount: -200.00,
        //   time: '2024-01-13 16:45'
        // },
        // {
        //   id: 4,
        //   type: '充值',
        //   amount: 1000.00,
        //   time: '2024-01-12 09:15'
        // }
      ]
    }
  },
  
  computed: {
    /**
     * 根据选择的链获取可用的币种
     */
    availableTokens() {
      return this.tokenOptions[this.withdrawForm.toChain] || []
    },

    /**
     * 计算实际到账金额
     */
    actualAmount() {
      // 使用 10^6 精度进行整数计算，避免浮点误差；展示时最多6位小数、去尾零
      const amountInt = this.toScaledInt(this.withdrawForm.amount)
      const feeInt = this.toScaledInt(this.withdrawForm.fee)
      if (!Number.isFinite(amountInt) || !Number.isFinite(feeInt)) return '0'
      const result = amountInt - feeInt
      if (result <= 0) return '0'
      return this.formatDec6FromInt(result)
    },

    /**
     * 计算总余额（可用余额 + 冻结余额）
     */
    totalBalance() {
      const available = parseFloat(this.WalletData.walletBalance || this.WalletData.balance || this.walletBalance || 0) || 0
      const blocked = parseFloat(this.WalletData.blockedBalance || this.blockedBalance || 0) || 0
      return (available + blocked).toFixed(2)
    },
    /**
     * 可用余额（提现对话框时以当前卡片的钱包为准）
     */
    availableWithdrawBalance() {
      return (this.WalletData.walletBalance || this.WalletData.balance || 0)
    },
    /**
     * 提现展示单位（始终大写）：优先当前 WalletData 的 fromSymbol/coin
     */
    displayWithdrawSymbol() {
      const sym = (this.WalletData && (this.WalletData.fromSymbol || this.WalletData.coin || this.withdrawForm.toSymbol)) || ''
      return String(sym).toUpperCase()
    }
  },
  mounted() {
    this.fetchWalletInfo()
    // 初始化手续费
    this.updateFeeByChain()
    this.getChainAndList()
    this.fetchRecentlyTransaction()
  },
  
  methods: {
    /**
     * 统一获取钱包展示单位优先级：fromSymbol > toSymbol > coin > 'USDT'
     */
    displaySymbol(w) {
      const sym = (w && (w.fromSymbol || w.toSymbol || w.coin)) || ''
      return String(sym).toUpperCase()
    },
    openCreateWallet() {
      this.createDialogVisible = true
      if (!Array.isArray(this.options) || this.options.length === 0) {
        this.getChainAndList()
      }
    },
    async confirmCreateWallet() {
      const val = this.createValue || []
      if (!Array.isArray(val) || val.length < 2) {
        this.$message.warning('请先选择链与币种')
        return
      }
      const [chain, coin] = val
      if (!chain || !coin) {
        this.$message.warning('请选择完整的链与币种')
        return
      }
      try {
        this.createLoading = true
        const res = await bindWallet({ chain, coin })
        if (res && (res.code === 0 || res.code === 200)) {
        
          // 后端会返回充值相关信息（地址/二维码等），直接展示充值弹窗
          const data = res.data
          if (data) {
            const walletInfo = Array.isArray(data) ? (data[0] || {}) : data
            this.WalletData = walletInfo
            this.rechargeDialogVisible = true
            this.qrCodeGenerated = false
            this.$nextTick(() => { this.generateQRCode() })
          }
          // 同步刷新钱包列表（异步，不影响弹窗展示）
          this.fetchWalletInfo()
          // 关闭链/币种选择弹窗
          this.createDialogVisible = false
          this.createValue = []
        }
      } catch (e) {
        console.error('获取充值信息失败', e)
      } finally {
        this.createLoading = false
      }
    },
    async getChainAndList() {
      this.loading = true;
      const res = await getChainAndList();
      if (res && (res.code === 0 || res.code === 200) && res.data) {
        this.options = res.data;      
      }

      this.loading = false;
    },
    /**
     * 获取最近交易记录（充值/提现/支付）
     */
    async fetchRecentlyTransaction() {
      try {
        const res = await getRecentlyTransaction()
        if (res && (res.code === 0 || res.code === 200)) {
          const rows = Array.isArray(res.data) ? res.data : []
          const mapped = rows.map((r, idx) => {
            const rawAmt = Number(r && r.amount)
            const amt = Number.isFinite(rawAmt) ? rawAmt : 0
            const type = Number(r && r.type)
            const signAmt = (type === 1) ? Math.abs(amt) : -Math.abs(amt) // 1 充值为正，0 支付/2 提现为负
            const typeLabel = type === 1 ? '充值' : (type === 2 ? '提现' : '支付')
            const status = Number(r && r.status)
            const statusTextMap = { 0: '失败', 1: '成功', 2: '处理中', 3: '校验失败' }
            const statusTagTypeMap = { 0: 'danger', 1: 'success', 2: 'warning', 3: 'danger' }
            return {
              id: `${r && r.updateTime || ''}-${idx}`,
              type: typeLabel,
              amount: signAmt,
              amountText: this.formatDec6(Math.abs(signAmt)),
              time: this.formatApiTime(r && r.updateTime),
              status,
              statusText: statusTextMap[status] || '-',
              statusTagType: statusTagTypeMap[status] || 'info'
            }
          })
          this.recentTransactions = mapped
        }
      } catch (e) {
        // 忽略错误，保留本地占位
        // console.error('获取最近交易失败', e)
      }
    },
    /**
     * 将后端时间格式 2025-10-16T07:57:28 转换为 2025-10-16 07:57:28
     */
    formatApiTime(value) {
      const s = String(value || '')
      if (!s) return ''
      return s.replace('T', ' ').replace('Z', '')
    },
    /**
     * 金额显示：保留最多6位小数，直接截断不四舍五入；不补尾随0
     */
    formatDec6(value) {
      if (value === null || value === undefined || value === '') return '0'
      let s = String(value)
      if (/e/i.test(s)) {
        const n = Number(value)
        if (!Number.isFinite(n)) return '0'
        s = n.toFixed(20).replace(/\.0+$/, '').replace(/(\.\d*?)0+$/, '$1')
      }
      const m = s.match(/^(-?)(\d+)(?:\.(\d+))?$/)
      if (!m) return s
      let intPart = m[2]
      let decPart = m[3] || ''
      if (decPart.length > 6) decPart = decPart.slice(0, 6)
      return decPart ? `${intPart}.${decPart}` : intPart
    },
    /**
     * 将金额字符串转换为“分”为单位的整数
     */
    /**
     * 将金额字符串转为按 10^6 精度的整数
     */
    toScaledInt(amountStr, decimals = 6) {
      if (amountStr === null || amountStr === undefined) return 0
      const normalized = String(amountStr).trim()
      if (normalized === '') return 0
      const re = new RegExp(`^\\d+(?:\\.(\\d{0,${decimals}}))?$`)
      const match = normalized.match(re)
      if (!match) {
        const n = Number(normalized)
        if (!Number.isFinite(n)) return 0
        const scale = Math.pow(10, decimals)
        return Math.round(n * scale)
      }
      const [intPart, decPartRaw] = normalized.split('.')
      const decPart = (decPartRaw || '').padEnd(decimals, '0').slice(0, decimals)
      const scale = Math.pow(10, decimals)
      return Number(intPart) * scale + Number(decPart)
    },

    /**
     * 将“分”为单位的整数转为字符串金额，固定两位小数
     */
    /**
     * 将按 10^6 精度的整数转为字符串金额，固定六位小数
     */
    scaledIntToString(intVal, decimals = 6) {
      const sign = intVal < 0 ? '-' : ''
      const abs = Math.abs(intVal)
      const scale = Math.pow(10, decimals)
      const intPart = Math.floor(abs / scale)
      const decPart = String(abs % scale).padStart(decimals, '0')
      return `${sign}${intPart}.${decPart}`
    },
    /**
     * 将按10^6精度的整数转为最多6位小数字符串（不补零，不四舍五入）
     */
    formatDec6FromInt(intVal) {
      const s = this.scaledIntToString(intVal, 6)
      return s.replace(/\.0+$/, '').replace(/(\.\d*?)0+$/, '$1')
    },
    async fetchWalletInfo(params) {
      try {
        const res = await getWalletInfo(params)
        
        if (res && (res.code === 0 || res.code === 200)) {
          // 兼容两种返回：对象或数组
          const data = res.data
          if (Array.isArray(data)) {
            this.walletList = data
            // 兜底设置第一个钱包到旧字段，兼容现有充值二维码逻辑
            const first = data[0] || {}
            this.walletBalance = first.walletBalance || first.balance || 0
            this.blockedBalance = first.blockedBalance || 0
            // 充值弹窗打开期间，避免覆盖正在展示的 WalletData（会导致“充值币种”显示错误）
            if (!this.rechargeDialogVisible) {
              this.WalletData = first
            }
          } else if (data && typeof data === 'object') {
            this.walletList = [data]
            this.walletBalance = data.walletBalance || data.balance || 0
            this.blockedBalance = data.blockedBalance || 0
            if (!this.rechargeDialogVisible) {
              this.WalletData = data
            }
          } else {
            this.walletList = []
            this.walletBalance = 0
            this.blockedBalance = 0
            this.WalletData = {}
          }
        } 
      } catch (error) {
        console.error('获取钱包信息失败:', error)
      }
    },
    /**
     * 获取余额充值记录列表
     * @param {Object} params - 请求参数
     * @param {number} params.pageNum - 当前页码，默认为1
     * @param {number} params.pageSize - 每页条数，默认为20
     * @param {number} params.status - 记录状态：0-充值失败，1-充值成功，2-充值中
     */
    async fetchBalanceRechargeList(params = {}) {
      try {
        // 设置默认参数
        const requestParams = {
          pageNum: 1,
          pageSize: 20,
          ...params
        }

        console.log('获取充值记录参数:', requestParams)
        
        const res = await balanceRechargeList(requestParams)
        
        if (res && (res.code === 0 || res.code === 200)) {
          // 返回格式化的数据
          const result = {
            list: res.data.rows || [],
            total: res.data.total || 0,
            totalPage: res.data.totalPage || 0,
            currentPage: requestParams.pageNum,
            pageSize: requestParams.pageSize,
            status: requestParams.status
          }
          
          console.log('充值记录获取成功:', result)
          return result
        } else {
          this.$message({
            message: res?.msg || '获取充值记录失败',
            type: 'error',
            showClose: true
          })
          return null
        }
      } catch (error) {
     
        
        console.error('获取充值记录失败:', error)
      
        return null
      }
    },
    //提现记录
    async fetchBalanceWithdrawList(params) {
      const res = await balanceWithdrawList(params)
      if (res && (res.code === 0 || res.code === 200)) {
        this.balanceWithdrawList = res.data
      }
    },
    /**
     * 打开充值对话框
     */
    handleRecharge(wallet) {
      // 切换到被点击钱包的数据作为当前充值来源
      if (wallet && typeof wallet === 'object') {
        this.WalletData = wallet
      }
      this.rechargeDialogVisible = true
      this.qrCodeGenerated = false
      this.$nextTick(() => {
        this.generateQRCode()
      })
    },
    
    /**
     * 打开提现对话框
     */
    handleWithdraw(wallet) {
      // 若需要也可根据点击卡片切换默认链/币种
      if (wallet) {
        // 同步当前选中的钱包，驱动只读展示链与币种
        this.WalletData = wallet
        const chain = wallet.fromChain || wallet.chain || this.withdrawForm.toChain
        const symbol = wallet.fromSymbol || wallet.coin || this.withdrawForm.toSymbol
        this.withdrawForm.toChain = chain
        this.withdrawForm.toSymbol = symbol
        this.updateFeeByChain()
      }
      this.withdrawDialogVisible = true
    },
    
    /**
     * 复制钱包地址
     */
    copyAddress(address) {
      const addressToCopy = address || this.WalletData.fromAddress
      if (!addressToCopy) {
        this.$message({
          message: '钱包地址不存在',
          type: 'error',
          showClose: true
        })
        return
      }
      
      if (navigator.clipboard) {
        navigator.clipboard.writeText(addressToCopy).then(() => {
          this.$message({
            message: '钱包地址已复制到剪贴板',
            type: 'success',
            showClose: true
          })
        }).catch(() => {
          this.fallbackCopyAddress(addressToCopy)
        })
      } else {
        this.fallbackCopyAddress(addressToCopy)
      }
    },
    
    /**
     * 备用复制方法
     */
    fallbackCopyAddress(address) {
      const textArea = document.createElement('textarea')
      textArea.value = address
      document.body.appendChild(textArea)
      textArea.select()
      try {
        document.execCommand('copy')
        this.$message({
          message: '钱包地址已复制到剪贴板',
          type: 'success',
          showClose: true
        })
      } catch (err) {
        console.log('复制失败，请手动复制')
      }
      document.body.removeChild(textArea)
    },
    
    /**
     * 生成二维码
     */
    generateQRCode() {
      if (this.qrCodeGenerated) return
      
      // 使用后台返回的二维码数据
      if (this.WalletData.qrcode) {
        const qrContainer = this.$refs.qrCodeRef
        if (qrContainer) {
          qrContainer.innerHTML = ''
          
          // 创建img元素显示base64二维码
          const img = document.createElement('img')
          img.src = `data:image/png;base64,${this.WalletData.qrcode}`
          img.alt = 'USDT充值二维码'
          img.style.width = '160px'
          img.style.height = '160px'
          img.style.borderRadius = '4px'
          
          // 添加错误处理
          img.onerror = () => {
            qrContainer.innerHTML = '<div style="width: 200px; height: 200px; display: flex; align-items: center; justify-content: center; background: #f5f5f5; border-radius: 4px; color: #f56c6c;">二维码加载失败</div>'
          }
          
          qrContainer.appendChild(img)
          this.qrCodeGenerated = true
        }
      } else {
        // 如果没有二维码数据，显示提示信息
        const qrContainer = this.$refs.qrCodeRef
        if (qrContainer) {
          qrContainer.innerHTML = '<div style="width: 200px; height: 200px; display: flex; align-items: center; justify-content: center; background: #f5f5f5; border-radius: 4px; color: #999;">暂无二维码数据</div>'
        }
      }
    },
    

    
    /**
     * 链选择变化处理
     */
    onChainChange() {
      // 重置币种为USDT（如果该链支持USDT）
      const availableTokens = this.tokenOptions[this.withdrawForm.toChain] || []
      const hasUSDT = availableTokens.some(token => token.value === 'USDT')
      this.withdrawForm.toSymbol = hasUSDT ? 'USDT' : ''
      
      // 根据链设置手续费
      this.updateFeeByChain()
    },

    /**
     * 根据链更新手续费
     */
    updateFeeByChain() {
      // 优先从当前钱包信息中读取提现手续费（后端字段：charge）
      const walletCharge = (this.WalletData && (this.WalletData.charge != null ? this.WalletData.charge : this.WalletData.fee))
      if (walletCharge != null && walletCharge !== '') {
        const n = Number(walletCharge)
        this.withdrawForm.fee = Number.isFinite(n) ? n.toFixed(2) : String(walletCharge)
        return
      }
      // 兜底：按链类型给一个默认手续费
      const feeMap = {
        tron: '1.00',      // TRC20 手续费较低
        ethereum: '5.00',  // ERC20 手续费较高
        bsc: '0.50',       // BEP20 手续费较低
        polygon: '0.10'    // MATIC 手续费最低
      }
      this.withdrawForm.fee = feeMap[this.withdrawForm.toChain] || '1.00'
    },
    
    
    /**
     * 确认提现
     */
    async confirmWithdraw() {
      this.$refs.withdrawForm.validate(async (valid) => {
        if (valid) {
          this.withdrawLoading = true
          
          try {
            /**
             * 提现地址 RSA 加密（与“钱包绑定”页面保持一致：同步优先，异步兜底）
             * - toAddress: 用户输入的收款地址
             * - fromAddress: 当前钱包来源地址（后端可能用于校验来源）
             */
            const toAddressPlain = String(this.withdrawForm.toAddress || '').trim()
            const fromAddressPlain = String((this.WalletData && this.WalletData.fromAddress) || '').trim()

            /** @type {string} */
            let encryptedToAddress = toAddressPlain
            if (encryptedToAddress) {
              const syncEncrypted = rsaEncryptSync(encryptedToAddress)
              if (syncEncrypted) {
                encryptedToAddress = syncEncrypted
              } else {
                const asyncEncrypted = await rsaEncrypt(encryptedToAddress)
                if (asyncEncrypted) {
                  encryptedToAddress = asyncEncrypted
                } else {
                  this.$message.error('钱包地址加密失败，请重试')
                  return
                }
              }
            }

            /** @type {string} */
            let encryptedFromAddress = fromAddressPlain
            if (encryptedFromAddress) {
              const syncEncrypted = rsaEncryptSync(encryptedFromAddress)
              if (syncEncrypted) {
                encryptedFromAddress = syncEncrypted
              } else {
                const asyncEncrypted = await rsaEncrypt(encryptedFromAddress)
                if (asyncEncrypted) {
                  encryptedFromAddress = asyncEncrypted
                } else {
                  this.$message.error('钱包地址加密失败，请重试')
                  return
                }
              }
            }

            // 调用后台提现API，添加谷歌验证码参数
            const res = await withdrawBalance({
              toChain: (this.WalletData && (this.WalletData.fromChain || this.WalletData.chain)) || this.withdrawForm.toChain,
              toSymbol: (this.WalletData && (this.WalletData.fromSymbol || this.WalletData.coin)) || this.withdrawForm.toSymbol,
              amount: parseFloat(this.withdrawForm.amount),
              toAddress: encryptedToAddress,
              fromAddress: encryptedFromAddress,
              code: this.withdrawForm.googleCode // 添加谷歌验证码
            })
            
            if (res && (res.code === 0 || res.code === 200)) {
              this.$message({
                message: '提现申请已提交，请等待处理',
                type: 'success',
                showClose: true
              })
              
              // 重新获取钱包信息
              await this.fetchWalletInfo()
              
              this.withdrawDialogVisible = false
              this.resetWithdrawForm()
            } 
          } catch (error) {
            console.error('提现申请失败:', error)
            console.log('网络错误，请重试')
          } finally {
            this.withdrawLoading = false
          }
        }
      })
    },
    
    /**
     * 重置充值表单
     */
    resetRechargeForm() {
      this.qrCodeGenerated = false
      // 关闭后刷新一次，恢复 WalletData 与列表一致
      this.fetchWalletInfo()
    },
    
    /**
     * 重置提现表单
     */
    resetWithdrawForm() {
      this.withdrawForm = {
        toChain: 'tron',
        toSymbol: 'USDT',
        amount: '',
        toAddress: '',
        fee: '1.00',
        googleCode: '' // 重置谷歌验证码
      }
      this.withdrawLoading = false
      this.$nextTick(() => {
        this.$refs.withdrawForm && this.$refs.withdrawForm.clearValidate()
      })
    },
    
    /**
     * 验证提现金额
     */
    validateWithdrawAmount(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入提现金额'))
        return
      }
      
      // 使用“分”为单位的整数校验
      const amountInt = this.toScaledInt(value)
      if (!Number.isFinite(amountInt) || amountInt <= 0) {
        callback(new Error('请输入有效的金额'))
        return
      }
      // 手续费与总需求按相同精度计算
      const feeInt = this.toScaledInt(this.withdrawForm.fee)
      const totalRequired = amountInt + feeInt
      
      // 钱包余额转分（使用当前选中钱包的可用余额）
      const availableBalance = this.WalletData && (this.WalletData.walletBalance || this.WalletData.balance) || 0
      const balanceInt = this.toScaledInt(availableBalance)
      if (totalRequired > balanceInt) {
        const totalText = this.formatDec6FromInt(totalRequired)
        callback(new Error(`提现金额加上手续费(${totalText} USDT)不能超过钱包余额`))
        return
      }
      
      // 检查最小提现金额
      // 最小提现金额 1 USDT
      if (amountInt < 1000000) {
        callback(new Error('最小提现金额为1 USDT'))
        return
      }
      
      // 检查实际到账金额是否为正数（提现金额必须大于手续费）
      if (amountInt <= feeInt) {
        callback(new Error('提现金额必须大于手续费'))
        return
      }
      
      callback()
    },
    
    /**
     * 处理谷歌验证码输入
     */
    handleGoogleCodeInput(value) {
      // 只允许输入数字
      this.withdrawForm.googleCode = value.replace(/\D/g, '')
    },

    /**
     * 限制提现金额最多两位小数，清理非数字字符并保留首个小数点
     */
    handleAmountInput(value) {
      let v = String(value || '')
      // 仅保留数字和小数点
      v = v.replace(/[^0-9.]/g, '')
      // 保留第一个小数点
      const firstDot = v.indexOf('.')
      if (firstDot !== -1) {
        v = v.slice(0, firstDot + 1) + v.slice(firstDot + 1).replace(/\./g, '')
      }
      // 最多六位小数
      if (firstDot !== -1) {
        const [intPart, decPart] = v.split('.')
        v = intPart + '.' + (decPart ? decPart.slice(0, 6) : '')
      }
      // 限制整数部分长度，避免过大导致显示或后端处理异常，这里限制到 12 位（万亿级）
      const parts = v.split('.')
      if (parts[0] && parts[0].length > 12) {
        parts[0] = parts[0].slice(0, 12)
      }
      v = parts.join('.')
      this.withdrawForm.amount = v
    },

    /**
     * 验证谷歌验证码
     */
    validateGoogleCode(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入谷歌验证码'))
        return
      }
      
      if (!/^\d{6}$/.test(value)) {
        callback(new Error('谷歌验证码必须是6位数字'))
        return
      }
      
      callback()
    },

    /**
     * 验证收款地址
     */
    validateAddress(rule, value, callback) {
      const v = typeof value === 'string' ? value.trim() : ''
      if (!v) {
        callback(new Error('请输入收款地址'))
        return
      }

      // 根据选择的链验证地址格式（使用去空白后的值）
      const chain = this.withdrawForm.toChain
      let isValid = false
      
      switch (chain) {
        case 'tron':
          // Tron地址格式：以T开头，34位字符
          isValid = /^T[A-Za-z1-9]{33}$/.test(v)
          break
        case 'ethereum':
          // Ethereum地址格式：0x开头，40位十六进制
          isValid = /^0x[a-fA-F0-9]{40}$/.test(v)
          break
        case 'bsc':
          // BSC地址格式：0x开头，40位十六进制
          isValid = /^0x[a-fA-F0-9]{40}$/.test(v)
          break
        case 'polygon':
          // Polygon地址格式：0x开头，40位十六进制
          isValid = /^0x[a-fA-F0-9]{40}$/.test(v)
          break
        default:
          isValid = v.length > 10
      }
      
      if (!isValid) {
        callback(new Error('请输入正确的收款地址格式'))
        return
      }
      
      callback()
    },
    
    /**
     * 添加交易记录
     */
    addTransactionRecord(type, amount) {
      const now = new Date()
      const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
      
      this.recentTransactions.unshift({
        id: Date.now(),
        type,
        amount,
        time: timeStr
      })
      
      // 只保留最近10条记录
      if (this.recentTransactions.length > 10) {
        this.recentTransactions = this.recentTransactions.slice(0, 10)
      }
    }
  }
}
</script>

<style scoped>
/* 钱包容器 */
.wallet-container {
  width: 70vw;
  margin: 0 auto;
  padding: 20px;
}

/* 顶部工具栏 */
.wallet-toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 12px;
}
.create-wallet-btn {
  background: linear-gradient(135deg, #409eff 0%, #36cfc9 100%);
  border: none;
  color: #fff;
  font-weight: 600;
  border-radius: 8px;
  box-shadow: 0 6px 18px rgba(64, 158, 255, 0.25);
}
.create-wallet-btn:hover {
  filter: brightness(1.05);
}

.wallet-card-section{
  max-height: 600px;
  /* height: 600px; */
  overflow-y: auto;
 padding: 8px;
}

/* 钱包卡片样式 */
.wallet-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  color: white;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.wallet-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.wallet-title {
  font-size: 18px;
  font-weight: 700;
  margin: 0;
}

.wallet-balance {
  text-align: right;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 16px;
}

.balance-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
}

.balance-label {
  display: inline-block;
  font-size: 16px;
  opacity: 0.85;
  margin: 0;
}

.balance-amount {
  font-size: 20px;
  font-weight: 700;
  font-family: 'Monaco', 'Menlo', monospace;
}

.balance-amount.frozen {
  font-size: 20px;
  opacity: 0.9;
  color: #ffa940;
}

/* 操作按钮区域 */
.wallet-actions {
  display: flex;
  gap: 16px;
  justify-content: right;
}

.action-btn {
  width: 100px;
  height: 30px;
 
  font-size: 13px;
  font-weight: 600;
  border-radius: 8px;
  border: none;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.recharge-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.recharge-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.withdraw-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.withdraw-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

/* 内联提现按钮（余额行末尾） */
.withdraw-inline-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2px solid rgba(255, 255, 255, 0.3);
}
.withdraw-inline-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

/* 交易记录区域 */
.transaction-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 16px 0;
  color: #333;
  text-align: left;
}

.transaction-list {
  /* API 仅返回 <=5 条，使用自适应高度，避免滚动条 */
  max-height: none;
  overflow-y: visible;
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding-top: 4px;
  padding-bottom: 4px;
}

.transaction-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s ease;
}

.transaction-item:hover {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding-left: 6px;
  padding-right: 6px;
}

.transaction-item:last-child {
  border-bottom: none;
}

.transaction-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.transaction-status { align-self: flex-start; }

.transaction-type {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.transaction-time {
  font-size: 12px;
  color: #999;
}

.transaction-amount {
  font-weight: 600;
  font-size: 16px;
  font-family: 'Monaco', 'Menlo', monospace;
}

.transaction-amount.positive {
  color: #52c41a;
}

.transaction-amount.negative {
  color: #ff4d4f;
}

.empty-state {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-size: 14px;
}

/* 对话框样式优化 */
.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .wallet-container {
    padding: 16px;
  }
  
  .wallet-card {
    padding: 20px;
  }
  
  .wallet-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .wallet-balance {
    text-align: left;
    align-items: flex-start;
  }
  
  .balance-item {
    align-items: flex-start;
  }
  
  .balance-amount {
    font-size: 28px;
  }
  
  .wallet-actions {
    flex-direction: column;
  }
  
  .action-btn {
    width: 100%;
  }
}

/* 充值弹窗样式 */
.recharge-content {
  padding: 0;
}

.wallet-address-section,
.qr-code-section,
.recharge-notice {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
}

.address-container {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.address-input {
  flex: 1;
}

.address-input .el-input__inner {
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 12px;
  background-color: #f8f9fa;
}

/* 充值链/币种信息 */
.charge-meta {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 10px;
  flex-wrap: wrap;
}
.meta-tag { border-radius: 14px; }
.meta-title { margin-left: 4px; opacity: .9; }
.meta-val { margin-left: 2px; font-weight: 700; letter-spacing: .3px; }

.copy-btn {
  flex-shrink: 0;
}

.address-tip {
  font-size: 12px;
  color: #666;
  margin: 0;
  line-height: 1.4;
}

.qr-code-container {
  text-align: center;
}

.qr-code {
  display: inline-block;
  padding: 16px;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-bottom: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.qr-code canvas {
  display: block;
  border-radius: 4px;
}

.qr-tip {
  font-size: 12px;
  color: #666;
  margin: 0;
}

.recharge-notice {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.notice-list {
  margin: 0;
  padding-left: 16px;
  font-size: 13px;
  color: #666;
  line-height: 1.6;
}

.notice-list li {
  margin-bottom: 4px;
  text-align: left;
}

.notice-list li:last-child {
  margin-bottom: 0;
}

/* 提现弹窗样式 */
.balance-info {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
  text-align: left;
}

.balance-total { margin-bottom: 4px; font-weight: 600; }
.balance-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.divider { color: #ccc; }
.frozen-info {
  color: #e6a23c;
}
.balance-tip-icon, .frozen-tip-icon {
  margin-right: 4px;
  color: #ffd666;
  cursor: pointer;
}

.frozen-tip {
  font-size: 11px;
  color: #999;
  margin-left: 4px;
}

.fee-info {
  font-size: 12px;
  color: #e6a23c;
  margin-top: 4px;
  text-align: left;
}

.actual-amount-info {
  font-size: 12px;
  color: #67c23a;
  margin-top: 4px;
  text-align: left;
  font-weight: 500;
}

.address-tip {
  font-size: 12px;
  color: #f56c6c;
  margin-top: 4px;
  line-height: 1.4;
  text-align: left;
}

.google-code-tip {
  font-size: 12px;
  color: #409eff;
  margin-top: 4px;
  line-height: 1.4;
  text-align: left;
}


/* 表单样式优化 */
.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: 500;
  color: #333;
}

.el-textarea__inner {
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 12px;
  line-height: 1.4;
}

.el-input-group__append {
  background: #f8f9fa;
  color: #666;
  font-weight: 500;
}

/* 滚动条样式 */
.transaction-list::-webkit-scrollbar {
  width: 6px;
}

.transaction-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.transaction-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.transaction-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}


::v-deep .el-input.is-disabled .el-input__inner{
  color: rgba(0, 0, 0, 0.65);
}
</style>

