<template>
  <Dialog :visible="dialogVisible"
    :title="currentStep === 1 ? t('withdraw.dialog.title1') : t('withdraw.dialog.title2')" width="600px"
    :show-footer="false" @close="handleCloseDialog">
    <!-- 第一步：输入金额 -->
    <div v-if="currentStep === 1" class="step1-container">
      <!-- 钱包余额（简化展示） -->
      <div class="wallet-balance">
        <span class="wallet-label">{{ t('withdraw.dialog.walletBalance') }}：</span>
        <span class="wallet-value">{{ walletBalance }}</span>
        <!-- <span class="wallet-currency">{{ currentCurrency }}</span> -->
      </div>

      <!-- 金额输入 -->
      <div class="amount-section">
        <div class="section-label">
          {{ t('withdraw.dialog.amount') }}
          <span class="max-balance">（最大可取：{{ walletBalance }}）</span>
        </div>
        <el-input v-model="withdrawAmount" type="number" :placeholder="t('withdraw.dialog.amountPlaceholder')">
          <!-- <template #prepend>{{ currentCurrency }}</template> -->
        </el-input>
      </div>

      <!-- 快捷金额 -->
      <div class="quick-amounts">
        <el-button v-for="amount in quickAmounts" :key="amount" size="small" @click="handleQuickAmount(amount)">
          {{ amount }}
        </el-button>
      </div>

      <!-- 底部按钮 -->
      <div class="dialog-footer">
        <el-button @click="handleCancel">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" @click="handleNextStep">{{ t('withdraw.dialog.nextStep') }}</el-button>
      </div>
    </div>

    <!-- 第二步：确认表单 -->
    <div v-else class="step2-container">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-position="top">

        <!-- 金额信息（只读） -->
        <div class="amount-info">
          <div class="info-row">
            <span class="info-label">{{ t('withdraw.dialog.withdrawAmount') }}：</span>
            <span class="info-value">{{ withdrawAmount }} </span>
          </div>
        </div>

        <!-- 银行提示（仅 BANK 渠道显示） -->
        <div v-if="isBankChannel" class="bank-tips">
          <div class="tips-title">{{ t('withdraw.dialog.bankTipsTitle') }}</div>
          <div class="tips-content">{{ t('withdraw.dialog.bankTipsContent') }}</div>
        </div>

        <!-- 钱包地址（TRC/ERC 渠道） -->
        <el-form-item v-if="isCryptoChannel" :label="t('withdraw.dialog.walletAddress')" prop="withdraw_address">
          <el-input v-model="formData.withdraw_address" :placeholder="t('withdraw.dialog.walletAddressPlaceholder')" />
        </el-form-item>

        <!-- 银行信息（BANK 渠道） -->
        <template v-if="isBankChannel">
          <el-form-item :label="t('withdraw.dialog.beneficiaryName')" prop="beneficiary_name">
            <el-input v-model="formData.beneficiary_name"
              :placeholder="t('withdraw.dialog.beneficiaryNamePlaceholder')" />
          </el-form-item>
          <el-form-item :label="t('withdraw.dialog.beneficiaryEnname')" prop="beneficiary_enname">
            <el-input v-model="formData.beneficiary_enname"
              :placeholder="t('withdraw.dialog.beneficiaryEnnamePlaceholder')" />
          </el-form-item>
          <el-form-item :label="t('withdraw.dialog.bankName')" prop="beneficiary_bank_name">
            <el-input v-model="formData.beneficiary_bank_name"
              :placeholder="t('withdraw.dialog.bankNamePlaceholder')" />
          </el-form-item>
          <el-form-item :label="t('withdraw.dialog.bankAccount')" prop="beneficiary_bank_account">
            <el-input v-model="formData.beneficiary_bank_account"
              :placeholder="t('withdraw.dialog.bankAccountPlaceholder')" />
          </el-form-item>
        </template>
      </el-form>

      <!-- 底部按钮 -->
      <div class="dialog-footer">
        <el-button @click="handleBack">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">{{ t('withdraw.dialog.confirmWithdraw')
        }}</el-button>
      </div>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import Dialog from '@/components/common/Dialog.vue'
import { getWalletCapital, withdraw } from '@/api/modules/capital/withdraw'

const { t } = useI18n()

interface Props {
  visible: boolean
  channelId?: number
  channelCode?: string
  channelInfo?: {
    id: number
    symbol?: string
    channel_code?: string
    currency?: {
      symbol: string
    }
  }
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

interface WalletInfo {
  amount: string
  bail: string
  freeze: string
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = ref(props.visible)
const currentStep = ref(1)
const withdrawAmount = ref('')
const submitLoading = ref(false)

// 当前货币类型（从渠道信息获取）
// const currentCurrency = computed(() => props.channelInfo?.currency?.symbol || '-')

// 钱包信息（只保留需要的三个字段）
const walletInfo = ref<WalletInfo>({
  amount: '0',
  bail: '0',
  freeze: '0',
})

// 钱包余额 = amount - bail - freeze（直接截取最后2位小数，不四舍五入）
const walletBalance = computed(() => {
  const amount = parseFloat(walletInfo.value.amount || '0')
  const bail = parseFloat(walletInfo.value.bail || '0')
  const freeze = parseFloat(walletInfo.value.freeze || '0')
  const result = amount - bail - freeze
  // 转字符串后直接截取最后两位小数，避开 toFixed 的四舍五入和 JS 浮点精度问题
  const [intPart, decPart = ''] = String(result).split('.')
  const truncatedDec = (decPart + '00').slice(0, 2)
  return `${intPart}.${truncatedDec}`
})

// 快捷金额
const quickAmounts = ['100', '500', '1000', '5000']

// 当前选中的渠道编码
const currentChannelCode = computed(() => {
  return props.channelCode || props.channelInfo?.channel_code || ''
})

// 是否为加密货币渠道（TRC/ERC）
const isCryptoChannel = computed(() => {
  return ['TRC', 'ERC', 'ADJUST'].includes(currentChannelCode.value)
})

// 是否为银行渠道（BANK）
const isBankChannel = computed(() => {
  return currentChannelCode.value === 'BANK'
})

// 表单数据
const formRef = ref<FormInstance>()
const formData = ref({
  withdraw_address: '',
  beneficiary_name: '',
  beneficiary_enname: '',
  beneficiary_bank_name: '',
  beneficiary_bank_account: '',
})

// 表单验证规则
const formRules: FormRules = {
  withdraw_address: [{ required: true, message: '请输入钱包地址', trigger: 'blur' }],
  beneficiary_name: [{ required: true, message: '请输入收款人姓名', trigger: 'blur' }],
  beneficiary_enname: [{ required: true, message: '请输入收款人英文名字', trigger: 'blur' }],
  beneficiary_bank_name: [{ required: true, message: '请输入银行名称', trigger: 'blur' }],
  beneficiary_bank_account: [{ required: true, message: '请输入银行账号', trigger: 'blur' }],
}

// 监听 visible 变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val
  if (val) {
    initData()
  }
})

// 初始化数据
const initData = async () => {
  currentStep.value = 1
  withdrawAmount.value = ''
  formData.value = {
    withdraw_address: '',
    beneficiary_name: '',
    beneficiary_enname: '',
    beneficiary_bank_name: '',
    beneficiary_bank_account: '',
  }

  // 获取钱包信息
  try {
    const res: any = await getWalletCapital()
    if (res) {
      walletInfo.value = {
        amount: res.amount || '0',
        bail: res.bail || '0',
        freeze: res.freeze || '0',
      }
    }
  } catch (error) {
    console.error('获取钱包信息失败', error)
  }
}

// 快捷金额
const handleQuickAmount = (amount: string) => {
  withdrawAmount.value = amount
}

// Dialog 关闭事件（不带参数）
const handleCloseDialog = () => {
  emit('update:visible', false)
}

// 取消
const handleCancel = () => {
  dialogVisible.value = false
  emit('update:visible', false)
}

// 返回上一步
const handleBack = () => {
  currentStep.value = 1
}

// 下一步
const handleNextStep = () => {
  const amount = parseFloat(withdrawAmount.value)
  if (!withdrawAmount.value || isNaN(amount) || amount <= 0) {
    ElMessage.warning('请输入取款金额')
    return
  }

  const maxBalance = parseFloat(walletBalance.value)
  if (amount > maxBalance) {
    ElMessage.warning(`输入金额不能超过钱包余额 ${walletBalance.value}`)
    return
  }

  currentStep.value = 2
}

// 提交
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
  } catch {
    return
  }

  submitLoading.value = true

  try {
    const params: any = {
      channel_id: props.channelId,
      amount: +withdrawAmount.value,
    }

    if (isCryptoChannel.value) {
      // 加密货币渠道 - 只传钱包地址，其他字段默认 --
      params.withdraw_address = formData.value.withdraw_address
      params.beneficiary_name = '--'
      params.beneficiary_enname = '--'
      params.beneficiary_bank_name = '--'
      params.beneficiary_bank_account = '--'
      params.swift_bic_code = '--'
      params.beneficiary_bank_address = '--'
    } else if (isBankChannel.value) {
      // 银行渠道 - 传银行相关字段，不需要钱包地址
      params.withdraw_address = '--'
      params.beneficiary_name = formData.value.beneficiary_name
      params.beneficiary_enname = formData.value.beneficiary_enname
      params.beneficiary_bank_name = formData.value.beneficiary_bank_name
      params.beneficiary_bank_account = formData.value.beneficiary_bank_account
      params.swift_bic_code = '--'
      params.beneficiary_bank_address = '--'
    }

    await withdraw(params)

    ElMessage.success('取款申请已提交')
    dialogVisible.value = false
    emit('update:visible', false)
    emit('success')
  } catch (error) {
    console.error('提交失败', error)
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped lang="scss">
.step1-container {
  .wallet-balance {
    display: flex;
    align-items: baseline;
    padding: 16px 20px;
    margin-bottom: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 8px;
    color: #fff;

    .wallet-label {
      margin-right: 8px;
      font-size: 14px;
      color: rgba(255, 255, 255, 0.85);
    }

    .wallet-value {
      font-size: 24px;
      font-weight: 700;
      color: #fff;
    }

    .wallet-currency {
      margin-left: 6px;
      font-size: 14px;
      color: rgba(255, 255, 255, 0.85);
    }
  }

  .amount-section {
    margin-bottom: 16px;

    .section-label {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      font-size: 14px;
      font-weight: 500;
      color: #303133;

      .max-balance {
        margin-left: 8px;
        font-size: 12px;
        color: #909399;
        font-weight: normal;
      }
    }
  }

  .quick-amounts {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    margin-bottom: 8px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.step2-container {
  .amount-info {
    margin-bottom: 24px;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 4px;

    .info-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }

      .info-label {
        color: #606266;
      }

      .info-value {
        font-weight: 500;
        color: #303133;
      }
    }
  }

  .bank-tips {
    margin-bottom: 20px;
    padding: 12px 16px;
    background: #fffbe6;
    border: 1px solid #ffe58f;
    border-radius: 4px;

    .tips-title {
      margin-bottom: 8px;
      font-size: 14px;
      font-weight: 500;
      color: #d48806;
    }

    .tips-content {
      font-size: 13px;
      color: #8c8c8c;
      line-height: 1.6;
    }
  }
}
</style>
