<template>
  <el-dialog
      v-model="dialogVisible"
      :title="t('充值')"
      width="560px"
      center
      class="custom-dark-dialog recharge-dialog"
      align-center
      append-to-body
      @closed="resetForm"
  >
    <div class="recharge-modal-body">

      <div class="qr-code-section">
        <div class="qr-code-bg">
          <el-image
              v-if="qrCodeUrl"
              :src="qrCodeUrl"
              style="width: 140px; height: 140px"
              fit="contain"
          ></el-image>
          <div v-else class="empty-qr-code">
            <el-icon :size="32" color="#666"><Picture /></el-icon>
            <span class="empty-text">{{ t('暂无二维码') }}</span>
          </div>
        </div>
      </div>

      <div class="selection-section">
        <div class="section-title">{{ t('选择币种') }}</div>
        <div class="currency-options">
          <div
              v-for="currency in allCurrencies"
              :key="currency.value"
              class="currency-card"
              :class="{ 'selected': selectedCurrency === currency.value }"
              @click="onSelectCurrency(currency.value)"
          >
            <span class="currency-name">{{ currency.label }}</span>
            <el-icon v-if="selectedCurrency === currency.value" class="check-icon"><Select /></el-icon>
          </div>
        </div>
      </div>

      <div class="selection-section">
        <div class="section-title">{{ t('选择区块链网络') }}</div>
        <div class="network-options">
          <div
              v-for="(network, n) in networkOptions"
              :key="network.value"
              class="network-card"
              :class="{ 'selected': selectedNetwork === network.value }"
              @click="onSelectNetwork(network.value, n)"
          >
            <span class="network-name">{{ network.label }}</span>
            <el-icon v-if="selectedNetwork === network.value" class="check-icon"><Select /></el-icon>
          </div>
        </div>
      </div>

      <div class="form-section">
        <div class="section-title">{{ t('充值地址') }}</div>
        <div class="address-box">
          <el-input
              v-model="rechargeAddress"
              readonly
              class="dark-input"
          >
            <template #append>
              <el-button @click="copyAddress" class="copy-btn">
                <el-icon><CopyDocument /></el-icon> {{ t('复制') }}
              </el-button>
            </template>
          </el-input>
        </div>
        <div class="address-tip">
          <el-icon><Warning /></el-icon>
          {{ t('请确认充值地址正确无误，错误地址将导致资产丢失且无法找回') }}
        </div>
      </div>

      <div class="form-section flex-row-section">
        <div class="flex-half">
          <div class="section-title">{{ t('充值数量') }}</div>
          <el-input
              v-model="amount"
              :placeholder="t('请输入数量')"
              class="dark-input"
              type="number"
              @blur="amountTouched = true"
          ></el-input>
        </div>

        <div class="flex-half">
          <div class="section-title">{{ t('预计到账') }}</div>
          <el-input
              v-model="estimatedAmount"
              readonly
              class="dark-input readonly-input"
          >
            <template #append>{{ $currency || 'CNY' }}</template>
          </el-input>
        </div>
      </div>

      <div class="exchange-rate-tip">
        {{ t('当前汇率') }}: 1 {{ selectedCurrency }} = {{ exchangeRate > 0 ? (1 / exchangeRate).toFixed(2) : '0.00' }} {{ $currency || 'CNY' }}
      </div>

      <div class="form-section upload-section">
        <div class="section-title">{{ t('上传支付凭证') }}</div>
        <div class="upload-container">
          <CUploadImage
              @change="changeImg"
              ref="CUploadImageRef"
          />
        </div>
      </div>

    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button class="cancel-btn" @click="dialogVisible = false">{{ t('取消') }}</el-button>
        <el-button type="primary" @click="submitRecharge" class="submit-btn">{{ t('确认充值') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed, nextTick } from "vue";
import { useI18n } from "vue-i18n";
import { ElMessage } from 'element-plus';
import { Picture, Select, CopyDocument, Warning } from '@element-plus/icons-vue';

import { getExchangeRate, getRechargeAddressAndWithdrawCurrencyList, recharge } from "@/request/api";
import CUploadImage from "@/components/CUploadImage/index.vue";

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

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

const { t } = useI18n();
const CUploadImageRef = ref();

// 弹窗显示双向绑定
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});

const allCurrencies = ref([]);
const selectedCurrency = ref('USDT');
const networkOptions = ref([]);
const addressOptions = ref([]);
const selectedNetwork = ref('');
const rechargeAddress = ref('');
const amount = ref('');
const amountTouched = ref(false);
const estimatedAmount = ref('0');
const qrCodeUrl = ref('');
const exchangeRate = ref(0);
const uploadFileUrl = ref('');

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

const changeImg = (e) => {
  uploadFileUrl.value = Array.isArray(e) ? e[0] : e;
};

const updateCurrencyInfo = (currencyValue) => {
  const currency = allCurrencies.value.find(item => item.value === currencyValue);
  if (currency) {
    qrCodeUrl.value = currency.qrCodeUrl;
    networkOptions.value = currency.networks;
    addressOptions.value = currency.address;
    selectedNetwork.value = currency.networks.length > 0 ? currency.networks[0].value : '';
    rechargeAddress.value = currency.address[0] || '';
  }
};

const onSelectCurrency = async (currencyValue) => {
  selectedCurrency.value = currencyValue;
  await getBlockChainFee();
};

const onSelectNetwork = (networkValue, index) => {
  selectedNetwork.value = networkValue;
  rechargeAddress.value = addressOptions.value[index] || '';
};

// 复制地址功能
const copyAddress = async () => {
  if (!rechargeAddress.value) return;
  try {
    await navigator.clipboard.writeText(rechargeAddress.value);
    ElMessage.success(t('复制成功'));
  } catch (err) {
    // 降级处理
    const input = document.createElement('input');
    input.setAttribute('value', rechargeAddress.value);
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
    ElMessage.success(t('复制成功'));
  }
};

watch(selectedCurrency, (newVal) => {
  updateCurrencyInfo(newVal);
  amount.value = '';
  amountTouched.value = false;
  estimatedAmount.value = '0';
});

watch(amount, (newAmount) => {
  if (newAmount === '') {
    estimatedAmount.value = '0';
    return;
  }
  amountTouched.value = true;
  if (exchangeRate.value > 0) {
    estimatedAmount.value = (Number(newAmount) / Number(exchangeRate.value)).toFixed(2);
  } else {
    estimatedAmount.value = '0.00';
  }
});

const submitRecharge = async () => {
  if (!amount.value || Number(amount.value) <= 0) {
    amountTouched.value = true;
    return ElMessage.warning(t('请输入充值数量'));
  }
  if (!uploadFileUrl.value) {
    return ElMessage.warning(t('请上传支付凭证'));
  }

  const params = {
    currency: selectedCurrency.value,
    network_type: selectedNetwork.value,
    address: rechargeAddress.value,
    amount: amount.value,
    payment_receipt: uploadFileUrl.value
  };

  try {
    await recharge(params);
    // 接口本身封装了 success 提示
    emit('success');
    dialogVisible.value = false;
  } catch (err) {
    console.error(err);
  }
};

const getBlockChainFee = async () => {
  try {
    const res = await getExchangeRate({ symbol: selectedCurrency.value });
    exchangeRate.value = res.data.price || 0;
    // 重新计算预估到账
    if (amount.value) {
      estimatedAmount.value = exchangeRate.value > 0 ? (Number(amount.value) / Number(exchangeRate.value)).toFixed(2) : '0.00';
    }
  } catch (err) {
    console.error(err);
  }
};

const getData = async () => {
  try {
    const res = await getRechargeAddressAndWithdrawCurrencyList({ type: 1 });
    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);
        existing.address.push(item.address);
      } else {
        acc.push({
          currency: item.currency,
          network_type: [item.network_type],
          address: [item.address],
          qrCodeUrl: item.qrcode,
        });
      }
      return acc;
    }, []);

    allCurrencies.value = mergedData.map(item => ({
      label: item.currency,
      value: item.currency,
      address: item.address,
      qrCodeUrl: item.qrCodeUrl,
      networks: item.network_type.map(trim => ({
        label: trim,
        value: trim,
      })),
    }));

    if (allCurrencies.value.length > 0) {
      selectedCurrency.value = allCurrencies.value[0].value;
      await getBlockChainFee();
      updateCurrencyInfo(allCurrencies.value[0].value);
    }
  } catch (err) {
    console.error(err);
  }
};

const resetForm = () => {
  amount.value = '';
  estimatedAmount.value = '0';
  uploadFileUrl.value = '';
  amountTouched.value = false;
  if (CUploadImageRef.value) CUploadImageRef.value.handleDeleteAllImg;
};
</script>

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

.recharge-dialog {
  /* 弹窗内部滚动区域样式 */
  .recharge-modal-body {
    max-height: 60vh;
    overflow-y: auto;
    padding-right: 10px;

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

.qr-code-section {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;

  .qr-code-bg {
    background-color: #fff; /* 二维码需要白底才能被扫出来 */
    padding: 10px;
    border-radius: 12px;
    border: 1px solid $border-color;
  }

  .empty-qr-code {
    width: 140px;
    height: 140px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #f5f5f5;
    .empty-text { font-size: 13px; margin-top: 8px; color: #666; }
  }
}

.selection-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 14px;
  color: #ccc;
  margin-bottom: 12px;
}

.currency-options {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;

  .currency-card {
    padding: 12px 24px;
    border: 1px solid $border-color;
    border-radius: 8px;
    background-color: $bg-dark;
    cursor: pointer;
    position: relative;
    transition: all 0.2s;
    color: $text-primary;

    &:hover { border-color: #666; }

    &.selected {
      border-color: $main-color;
      background-color: rgba(248, 185, 50, 0.1);
      .currency-name { color: $main-color; font-weight: bold; }
    }

    .check-icon {
      position: absolute;
      top: -6px;
      right: -6px;
      background: $main-color;
      color: #000;
      border-radius: 50%;
      padding: 2px;
      font-size: 12px;
    }
  }
}

.network-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;

  .network-card {
    padding: 8px 16px;
    border: 1px solid $border-color;
    border-radius: 20px;
    background: $bg-dark;
    color: $text-secondary;
    font-size: 13px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 6px;
    transition: all 0.2s;

    &:hover { color: $text-primary; border-color: #666; }

    &.selected {
      border-color: $main-color;
      color: $main-color;
      background: rgba(248, 185, 50, 0.1);
    }
  }
}

.form-section {
  margin-bottom: 20px;

  .address-tip {
    font-size: 12px;
    color: #f56c6c;
    margin-top: 8px;
    display: flex;
    align-items: center;
    gap: 4px;
  }
}

.flex-row-section {
  display: flex;
  gap: 20px;
  .flex-half { flex: 1; }
}

.exchange-rate-tip {
  font-size: 13px;
  color: $text-secondary;
  margin-top: -10px;
  margin-bottom: 20px;
  text-align: right;
}

/* 覆盖组件内部的深色输入框样式 */
:deep(.dark-input) {
  .el-input__wrapper {
    background-color: #1a1a1a !important;
    box-shadow: 0 0 0 1px #444 inset !important;
    height: 44px;
    transition: all 0.3s;

    &:hover, &.is-focus {
      box-shadow: 0 0 0 1px #666 inset !important;
    }
  }
  .el-input__inner {
    color: #fff !important;
  }
  .el-input-group__append {
    background-color: #262626 !important;
    border-color: #444 !important;
    color: #ccc;
    .copy-btn {
      color: #ccc;
      border: none;
      &:hover { color: $main-color; }
    }
  }
}

/* 只读输入框，不允许改变边框颜色 */
:deep(.readonly-input) {
  .el-input__wrapper {
    background-color: #222 !important;
    &:hover, &.is-focus {
      box-shadow: 0 0 0 1px #444 inset !important;
    }
  }
}

.submit-btn { width: 120px; }
</style>
