<template>
  <div class="withdraw-page">
    <el-card class="page-card">
      <template #header>
        <span class="page-title">{{ t('提现') }}</span>
      </template>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="info-card">
            <template #header>
              <span>{{ t('账户余额') }}</span>
            </template>
            <div class="balance-display">
              <span class="balance-amount">¥{{ balance }}</span>
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card class="info-card">
            <template #header>
              <span>{{ t('提现范围') }}</span>
            </template>
            <div class="range-info">
              <p>{{ t('最低提现') }}: ¥{{ minWithdraw }}</p>
              <p>{{ t('最高提现') }}: ¥{{ maxWithdraw }}</p>
              <p>{{ t('手续费比例') }}: {{ feeRate }}%</p>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card class="form-card">
            <template #header>
              <span>{{ t('提现信息') }}</span>
            </template>
            <el-form :model="withdrawForm" :rules="rules" ref="formRef" label-width="120px">
              <el-form-item :label="t('提现方式')" prop="withdraw_type">
                <el-radio-group v-model="withdrawForm.withdraw_type">
                  <el-radio label="bank">{{ t('银行卡') }}</el-radio>
                  <el-radio label="crypto">{{ t('加密货币') }}</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item :label="t('提现币种')" prop="currency_id" v-if="withdrawForm.withdraw_type === 'crypto'">
                <el-select v-model="withdrawForm.currency_id" placeholder="选择币种" style="width: 100%;">
                  <el-option
                    v-for="item in currencyList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item :label="t('提现网络')" prop="network" v-if="withdrawForm.withdraw_type === 'crypto'">
                <el-select v-model="withdrawForm.network" placeholder="选择区块链网络" style="width: 100%;">
                  <el-option
                    v-for="item in networkList"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>

              <el-form-item :label="t('提现地址')" prop="address" v-if="withdrawForm.withdraw_type === 'crypto'">
                <el-input v-model="withdrawForm.address" placeholder="请输入提现地址" />
              </el-form-item>

              <el-form-item :label="t('收款名字')" prop="account_name" v-if="withdrawForm.withdraw_type === 'bank'">
                <el-input v-model="withdrawForm.account_name" placeholder="请输入收款名字" />
              </el-form-item>

              <el-form-item :label="t('银行名称')" prop="bank_name" v-if="withdrawForm.withdraw_type === 'bank'">
                <el-input v-model="withdrawForm.bank_name" placeholder="请输入银行名称" />
              </el-form-item>

              <el-form-item :label="t('银行账号')" prop="bank_account" v-if="withdrawForm.withdraw_type === 'bank'">
                <el-input v-model="withdrawForm.bank_account" placeholder="请输入银行账号" />
              </el-form-item>

              <el-form-item :label="t('银行地址')" prop="bank_address" v-if="withdrawForm.withdraw_type === 'bank'">
                <el-input v-model="withdrawForm.bank_address" placeholder="请输入银行地址" />
              </el-form-item>

              <el-form-item :label="t('国际代码')" prop="bank_code" v-if="withdrawForm.withdraw_type === 'bank'">
                <el-input v-model="withdrawForm.bank_code" placeholder="请输入国际代码" />
              </el-form-item>

              <el-form-item :label="t('提现金额')" prop="amount">
                <el-input-number v-model="withdrawForm.amount" :min="minWithdraw" :max="maxWithdraw" :precision="2" style="width: 100%;" />
              </el-form-item>

              <el-form-item :label="t('资金密码')" prop="fund_password">
                <el-input v-model="withdrawForm.fund_password" type="password" placeholder="请输入资金密码" />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :loading="submitLoading" @click="handleSubmit" style="width: 100%;">
                  {{ t('确认提现') }}
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card class="info-card">
            <template #header>
              <span>{{ t('预计到账金额') }}</span>
            </template>
            <div class="estimate-info">
              <p class="estimate-amount">¥{{ estimatedAmount }}</p>
              <p class="fee-amount">{{ t('手续费') }}: ¥{{ estimatedFee }}</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { getBalance, getRechargeAddressAndWithdrawCurrencyList } from '@/request/api'
import { useUserStore } from '@/store/user'

const { t } = useI18n()
const userStore = useUserStore()
const formRef = ref(null)
const balance = ref(0)
const currencyList = ref([])
const networkList = ref(['ERC20', 'TRC20', 'BSC'])
const minWithdraw = ref(100)
const maxWithdraw = ref(10000)
const feeRate = ref(2)
const submitLoading = ref(false)

const withdrawForm = reactive({
  withdraw_type: 'crypto',
  currency_id: '',
  network: 'ERC20',
  address: '',
  account_name: '',
  bank_name: '',
  bank_account: '',
  bank_address: '',
  bank_code: '',
  amount: 0,
  fund_password: ''
})

const estimatedAmount = computed(() => {
  const amount = Number(withdrawForm.amount) || 0
  const fee = amount * (feeRate.value / 100)
  return Math.max(0, amount - fee).toFixed(2)
})

const estimatedFee = computed(() => {
  const amount = Number(withdrawForm.amount) || 0
  return (amount * (feeRate.value / 100)).toFixed(2)
})

const rules = {
  amount: [
    { required: true, message: t('请输入提现金额'), trigger: 'blur' },
    { type: 'number', message: t('请输入有效的提现金额'), trigger: 'blur' }
  ],
  fund_password: [
    { required: true, message: t('请输入资金密码'), trigger: 'blur' }
  ]
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
  } catch (error) {
    return
  }

  if (withdrawForm.amount < minWithdraw.value) {
    ElMessage.warning(t('提现金额不能小于 0'))
    return
  }

  if (withdrawForm.amount > maxWithdraw.value) {
    ElMessage.warning(t('提现金额不能大于账户余额'))
    return
  }

  submitLoading.value = true
  try {
    ElMessage.success(t('提现成功'))
    await getBalance()
  } catch (error) {
    ElMessage.error(t('提现失败'))
  } finally {
    submitLoading.value = false
  }
}

onMounted(async () => {
  try {
    const [balanceRes, currencyRes] = await Promise.all([
      getBalance(),
      getRechargeAddressAndWithdrawCurrencyList()
    ])

    if (balanceRes.code === 1) {
      balance.value = balanceRes.data.money || 0
    }

    if (currencyRes.code === 1) {
      currencyList.value = currencyRes.data || []
      if (currencyList.value.length > 0) {
        withdrawForm.currency_id = currencyList.value[0].id
      }
    }
  } catch (error) {
    console.error('获取数据失败', error)
  }
})
</script>

<style scoped>
.withdraw-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-card {
  border-radius: 12px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.info-card {
  border-radius: 12px;
  height: 100%;
}

.balance-display {
  text-align: center;
  padding: 20px 0;
}

.balance-amount {
  font-size: 36px;
  font-weight: bold;
  color: #f8b932;
}

.range-info {
  font-size: 14px;
  color: #666;
  line-height: 2;
}

.range-info p {
  margin: 8px 0;
}

.form-card {
  border-radius: 12px;
  height: 100%;
}

.estimate-info {
  font-size: 14px;
  color: #666;
  line-height: 2;
}

.estimate-amount {
  font-size: 24px;
  font-weight: bold;
  color: #19be6b;
  margin-bottom: 10px;
}

.fee-amount {
  font-size: 16px;
  color: #fa3534;
}
</style>
