<template>
  <el-dialog
      v-model="dialogVisible"
      :title="t('提现')"
      width="560px"
      center
      class="custom-dark-dialog withdraw-dialog"
      align-center
      append-to-body
      @closed="resetForm"
  >
    <div class="withdraw-modal-body">
      <el-form
          :model="withdrawForm"
          :rules="rules"
          ref="elFormRef"
          label-position="top"
          class="dark-form"
      >

        <el-form-item :label="t('提现方式')" prop="withdrawMethod">
          <el-select
              v-model="withdrawForm.withdrawMethod"
              class="dark-select w-full"
              :teleported="false"
              @change="onMethodChange"
          >
            <el-option
                v-for="item in methodList"
                :key="item.value"
                :label="t(item.label)"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <template v-if="withdrawForm.withdrawMethod === 'bank'">
          <el-form-item :label="t('收款名字')" prop="receiverName">
            <el-input v-model="withdrawForm.receiverName" :placeholder="t('请输入收款名字')" class="dark-input" />
          </el-form-item>
          <el-form-item :label="t('银行名称')" prop="bankName">
            <el-input v-model="withdrawForm.bankName" :placeholder="t('请输入银行名称')" class="dark-input" />
          </el-form-item>
          <el-form-item :label="t('银行账号')" prop="bankAccount">
            <el-input v-model="withdrawForm.bankAccount" :placeholder="t('请输入银行账号')" class="dark-input" />
          </el-form-item>
          <el-form-item :label="t('银行地址')" prop="bankAddress">
            <el-input v-model="withdrawForm.bankAddress" :placeholder="t('请输入银行地址')" class="dark-input" />
          </el-form-item>

          <el-form-item :label="t('提现金额')" prop="bankAmount">
            <div class="custom-amount-box">
              <el-input-number
                  v-model="withdrawForm.bankAmount"
                  :min="0"
                  :max="Number(walletBalance)"
                  :precision="2"
                  :step="100"
                  class="dark-input-number"
                  :controls="true"
                  @blur="validateBankAmountBoundary"
              />
              <div class="max-btn" @click="setBankMaxAmount">{{ t('最大') }}</div>
              <span class="unit-text">{{ $currency }}</span>
            </div>
            <div class="amount-hints">
              <div class="hint-item">{{ t('提款范围') }} &gt; 0 {{ $currency }}</div>
              <div class="hint-item balance">{{ t('钱包余额') }}: {{ walletBalance }} {{ $currency }}</div>
            </div>
          </el-form-item>
        </template>

        <template v-else>
          <div class="flex-row">
            <el-form-item :label="t('提现币种')" prop="coinType" class="flex-half">
              <el-select
                  v-model="withdrawForm.coinType"
                  class="dark-select w-full"
                  :teleported="false"
                  @change="onCoinChange"
              >
                <el-option
                    v-for="item in allCurrencies"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item :label="t('提现网络')" prop="network" class="flex-half">
              <el-select
                  v-model="withdrawForm.network"
                  class="dark-select w-full"
                  :teleported="false"
              >
                <el-option
                    v-for="item in networkOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </div>

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

          <el-form-item :label="t('提现金额')" prop="amount">
            <div class="custom-amount-box">
              <el-input-number
                  v-model="withdrawForm.amount"
                  :min="Number(handlingFee)"
                  :max="Number(walletBalance) / Number(handlingRate)"
                  :precision="6"
                  :step="10"
                  class="dark-input-number"
                  :controls="true"
                  @change="handleAmountInput"
                  @blur="validateAmountBoundary"
              />
              <div class="max-btn" @click="setMaxAmount">{{ t('最大') }}</div>
              <span class="unit-text">{{ withdrawForm.coinType }}</span>
            </div>

            <div class="amount-hints column-hints">
              <div class="hint-item balance">
                {{ t('钱包余额') }}: {{ walletBalance }} {{ $currency }}
                <span class="sub-balance" v-if="handlingRate">
                  ≈ {{ (Number(walletBalance) / Number(handlingRate)).toFixed(6) }} {{ withdrawForm.coinType }}
                </span>
              </div>
              <div class="hint-item error-text">{{ t('提款范围') }} &gt; {{ handlingFee }} {{ withdrawForm.coinType }}</div>
            </div>
          </el-form-item>

          <div class="fee-display-card">
            <div class="fee-row">
              <span class="label">{{ t('手续费') }}:</span>
              <span class="value">{{ handlingFee }} {{ withdrawForm.coinType }}</span>
            </div>
            <div class="fee-row">
              <span class="label">{{ t('汇率') }}:</span>
              <span class="value">
                {{ handlingFee }} {{ withdrawForm.coinType }} ≈ {{ (handlingFee / exchangeRate).toFixed(2) }} {{ $currency }}
              </span>
            </div>
            <div class="fee-row total-row">
              <span class="label">{{ t('预计到账') }}:</span>
              <span class="value highlight">
                {{ Number(withdrawForm.amount) <= Number(handlingFee) ? '0.000000' : (Number(withdrawForm.amount) - Number(handlingFee)).toFixed(6) }}
                {{ withdrawForm.coinType }}
              </span>
            </div>
          </div>
        </template>
      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button class="cancel-btn" @click="dialogVisible = false">{{ t('取消') }}</el-button>
        <el-button type="primary" @click="triggerSafeModal" class="submit-btn">{{ t('提交提现') }}</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
      v-model="showSafeModal"
      :title="t('安全验证')"
      width="400px"
      center
      class="custom-dark-dialog"
      align-center
      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"
          @keyup.enter="confirmSubmitWithdraw"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button class="cancel-btn" @click="showSafeModal = false">{{ t('取消') }}</el-button>
        <el-button type="primary" @click="confirmSubmitWithdraw" :loading="submitLoading">{{ t('确认提现') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { getBalance, getExchangeRate, getRechargeAddressAndWithdrawCurrencyList, withdraw } from "@/request/api.js";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:modelValue', 'success']);

const { t } = useI18n();
const elFormRef = ref(null);

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});

// 状态变量
const walletBalance = ref(0);
const allCurrencies = ref([]);
const networkOptions = ref([]);
const handlingFee = ref(0);
const handlingRate = ref(1);
const exchangeRate = ref(1);

const methodList = [
  { value: 'crypto_coin', label: '加密货币' },
  // { value: 'bank', label: '银行卡' },
];

const withdrawForm = reactive({
  withdrawMethod: 'crypto_coin',
  receiverName: '',
  bankName: '',
  bankAccount: '',
  bankAddress: '',
  coinType: '',
  network: '',
  address: '',
  amount: 0,
  bankAmount: 0
});

// 安全密码
const showSafeModal = ref(false);
const safeWord = ref('');
const submitLoading = ref(false);

// 表单验证规则
const rules = reactive({
  receiverName: [{ required: true, message: t('请输入收款名字'), trigger: 'blur' }],
  bankName: [{ required: true, message: t('请输入银行名称'), trigger: 'blur' }],
  bankAccount: [{ required: true, message: t('请输入银行账号'), trigger: 'blur' }],
  coinType: [{ required: true, message: t('请选择提现币种'), trigger: 'change' }],
  network: [{ required: true, message: t('请选择提现网络'), trigger: 'change' }],
  address: [{ required: true, message: t('请输入提现地址'), trigger: 'blur' }]
});

// 监听弹窗打开，初始化数据
watch(dialogVisible, (val) => {
  if (val && allCurrencies.value.length === 0) {
    initData();
  }
});

const onMethodChange = () => {
  if (withdrawForm.withdrawMethod === 'bank') {
    withdrawForm.coinType = '';
    withdrawForm.network = '';
  } else {
    if (allCurrencies.value.length > 0) {
      onCoinChange(allCurrencies.value[0].value);
    }
  }
};

const onCoinChange = (val) => {
  withdrawForm.coinType = val;
  const currency = allCurrencies.value.find(item => item.value === val);
  if (currency) {
    networkOptions.value = currency.networks;
    withdrawForm.network = currency.networks[0]?.value || '';
    handlingFee.value = currency.withdraw_fee;
    withdrawForm.amount = Number(currency.withdraw_fee); // 重置默认金额为手续费
    fetchExchangeRate();
  }
};

// ================= 加密货币金额逻辑 =================
const handleAmountInput = () => {
  // 仅作占位，实际由 v-model 和 ElInputNumber 自动处理
};

const validateAmountBoundary = () => {
  let val = Number(withdrawForm.amount) || 0;
  const maxAllow = Number(walletBalance.value) / Number(handlingRate.value);

  if (val < Number(handlingFee.value)) {
    withdrawForm.amount = Number(handlingFee.value);
    ElMessage.warning(t(`提现金额不能小于手续费 ${handlingFee.value}`));
  } else if (val > maxAllow) {
    withdrawForm.amount = maxAllow;
    ElMessage.warning(t('提现金额不能大于余额'));
  }
};

const setMaxAmount = () => {
  withdrawForm.amount = Number((Number(walletBalance.value) / Number(handlingRate.value)).toFixed(6));
};

const fetchExchangeRate = async () => {
  if (!withdrawForm.coinType) return;
  try {
    const res = await getExchangeRate({ symbol: withdrawForm.coinType });
    exchangeRate.value = res.data.price || 1;
    handlingRate.value = res.data.rate || 1;
  } catch (err) {
    console.error(err);
  }
};

// ================= 银行卡金额逻辑 =================
const validateBankAmountBoundary = () => {
  let val = Number(withdrawForm.bankAmount) || 0;
  if (val < 0) {
    withdrawForm.bankAmount = 0;
    ElMessage.warning(t('提现金额不能小于0'));
  } else if (val > walletBalance.value) {
    withdrawForm.bankAmount = walletBalance.value;
    ElMessage.warning(t('提现金额不能大于余额'));
  }
};

const setBankMaxAmount = () => {
  withdrawForm.bankAmount = Number(walletBalance.value);
};

// ================= 提交与验证 =================
const triggerSafeModal = () => {
  elFormRef.value.validate((valid) => {
    if (valid) {
      if (withdrawForm.withdrawMethod === 'crypto_coin') {
        const maxAllow = Number(walletBalance.value) / Number(handlingRate.value);
        if (withdrawForm.amount < Number(handlingFee.value)) {
          return ElMessage.warning(t(`提现金额不能小于 ${handlingFee.value}`));
        }
        if (withdrawForm.amount > maxAllow) {
          return ElMessage.warning(t('提现金额不能大于余额'));
        }
      } else if (withdrawForm.withdrawMethod === 'bank') {
        if (withdrawForm.bankAmount <= 0) {
          return ElMessage.warning(t('提现金额必须大于0'));
        }
        if (withdrawForm.bankAmount > walletBalance.value) {
          return ElMessage.warning(t('提现金额不能大于余额'));
        }
      }

      safeWord.value = '';
      showSafeModal.value = true;
    }
  });
};

const confirmSubmitWithdraw = async () => {
  if (!safeWord.value) {
    return ElMessage.warning(t('请输入资金密码'));
  }

  submitLoading.value = true;
  const finalAmount = withdrawForm.withdrawMethod === 'crypto_coin' ? withdrawForm.amount : withdrawForm.bankAmount;

  const data = {
    type: withdrawForm.withdrawMethod,
    currency: withdrawForm.coinType,
    network_type: withdrawForm.network,
    address: withdrawForm.address,
    amount: finalAmount,
    bank_card_no: withdrawForm.bankAccount,
    bank_user_name: withdrawForm.receiverName,
    bank: withdrawForm.bankName,
    safe_word: safeWord.value
  };

  try {
    await withdraw(data);
    showSafeModal.value = false;
    dialogVisible.value = false;
    emit('success'); // 触发成功事件，通知父组件刷新数据
  } catch (err) {
    console.error(err);
  } finally {
    submitLoading.value = false;
  }
};

// ================= 初始化数据 =================
const initData = async () => {
  try {
    const res = await getRechargeAddressAndWithdrawCurrencyList({ type: 2 });
    const mergedData = res.data.list.reduce((acc, item) => {
      const existing = acc.find(entry => entry.currency === item.currency);
      if (existing) {
        existing.network_type.push(item.network_type);
      } else {
        acc.push({
          currency: item.currency,
          network_type: [item.network_type],
          withdraw_fee: item.withdraw_fee
        });
      }
      return acc;
    }, []);

    allCurrencies.value = mergedData.map(item => ({
      label: item.currency,
      value: item.currency,
      networks: item.network_type.map(n => ({ label: n, value: n })),
      withdraw_fee: item.withdraw_fee
    }));

    const balanceRes = await getBalance();
    walletBalance.value = balanceRes.data.money;

    if (allCurrencies.value.length > 0) {
      onCoinChange(allCurrencies.value[0].value);
    }
  } catch (err) {
    console.error(err);
  }
};

const resetForm = () => {
  if(elFormRef.value) elFormRef.value.resetFields();
  withdrawForm.amount = 0;
  withdrawForm.bankAmount = 0;
  safeWord.value = '';
};
</script>

<style scoped lang="scss">
$main-color: #f8b932;
$bg-dark: #1a1a1a;
$border-color: #444;
$text-primary: #fff;
$text-secondary: #999;

.withdraw-dialog {
  .withdraw-modal-body {
    max-height: 65vh;
    overflow-y: auto;
    padding-right: 10px;

    &::-webkit-scrollbar { width: 6px; }
    &::-webkit-scrollbar-thumb { background: #555; border-radius: 4px; }
  }
}

.w-full { width: 100%; }
.flex-row {
  display: flex; gap: 20px;
  .flex-half { flex: 1; }
}

/* 覆盖 Element UI 默认暗黑表单样式 */
.dark-form {
  :deep(.el-form-item__label) { color: #ccc; padding-bottom: 8px; }

  /* 输入框 */
  .dark-input {
    :deep(.el-input__wrapper) {
      background-color: $bg-dark !important;
      box-shadow: 0 0 0 1px $border-color inset !important;
      height: 44px;
      &:hover, &.is-focus { box-shadow: 0 0 0 1px $main-color inset !important; }
    }
    :deep(.el-input__inner) { color: $text-primary !important; }
  }

  /* 下拉选择框穿透 */
  .dark-select {
    :deep(.el-select__wrapper) {
      background-color: $bg-dark !important;
      box-shadow: 0 0 0 1px $border-color inset !important;
      min-height: 44px;
      &:hover, &.is-focus { box-shadow: 0 0 0 1px $main-color inset !important; }
    }
    :deep(.el-select__placeholder) { color: $text-primary; }
  }
}

/* 模拟原来的自定义金额输入框 */
.custom-amount-box {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 12px;

  .dark-input-number {
    flex: 1;
    :deep(.el-input-number__decrease),
    :deep(.el-input-number__increase) {
      background-color: #262626 !important;
      border-color: $border-color !important;
      color: $text-primary !important;
      &:hover { color: $main-color !important; }
    }
    :deep(.el-input__wrapper) {
      background-color: $bg-dark !important;
      box-shadow: 0 0 0 1px $border-color inset !important;
      height: 44px;
      padding: 0 40px;
    }
    :deep(.el-input__inner) {
      color: $text-primary !important;
      font-weight: bold;
      font-size: 16px;
    }
  }

  .max-btn {
    padding: 0 16px;
    height: 44px;
    line-height: 44px;
    font-size: 14px;
    color: $main-color;
    background-color: rgba(248, 185, 50, 0.1);
    border-radius: 6px;
    font-weight: bold;
    cursor: pointer;
    transition: opacity 0.2s;
    &:hover { opacity: 0.8; }
  }

  .unit-text { font-weight: bold; color: $text-primary; width: 40px; text-align: right;}
}

/* 提示信息 */
.amount-hints {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  font-size: 12px;
  color: $text-secondary;
  width: 100%;

  &.column-hints {
    flex-direction: column;
    gap: 4px;
  }

  .balance { color: #67c23a; }
  .error-text { color: #f56c6c; }
  .sub-balance { color: #999; margin-left: 6px; font-size: 12px; }
}

/* 费用展示卡片 */
.fee-display-card {
  margin-top: 24px;
  background-color: #222;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid $border-color;

  .fee-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    font-size: 13px;
    color: $text-secondary;

    &:last-child { margin-bottom: 0; }
    .value { color: $text-primary; }

    &.total-row {
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px dashed $border-color;
      .label { font-weight: bold; color: $text-primary; font-size: 14px; }
      .highlight { color: $main-color; font-weight: bold; font-size: 16px; }
    }
  }
}

.submit-btn { width: 120px; }

/* 密码弹窗样式 */
.safe-modal-content {
  text-align: center;
  padding: 10px 0;
  .safe-tips { margin-bottom: 16px; color: #ccc; font-size: 14px; }
  .dark-input {
    :deep(.el-input__wrapper) {
      background-color: $bg-dark !important;
      box-shadow: 0 0 0 1px $border-color inset !important;
      height: 44px;
      &:hover, &.is-focus { box-shadow: 0 0 0 1px $main-color inset !important; }
    }
    :deep(.el-input__inner) { color: $text-primary !important; }
  }
}
</style>
