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

      <template v-if="!payResult">
        <div class="form-section">
          <div class="section-title">{{ t('选择支付方式') }}</div>
          <div class="channel-list">
            <div
                v-for="(item, index) in channelList"
                :key="index"
                class="channel-card"
                :class="{ 'is-active': currentChannel?.value === item.value }"
                @click="selectChannel(item)"
            >
              <span class="channel-name">{{ item.label }}</span>
              <el-icon v-if="currentChannel?.value === item.value" class="check-icon"><Select /></el-icon>
            </div>
          </div>
        </div>

        <template v-if="currentChannel && currentChannel.isUsdt">
          <div class="form-section">
            <div class="section-title">{{ currentChannel.label }}</div>

            <div class="network-options">
              <div
                  v-if="trc20Address"
                  class="network-card"
                  :class="{ 'is-active': selectedNetwork === 'trc20' }"
                  @click="selectNetwork('trc20')"
              >
                <span class="network-name">TRC20</span>
                <el-icon v-if="selectedNetwork === 'trc20'" class="check-icon"><Select /></el-icon>
              </div>
              <div
                  v-if="erc20Address"
                  class="network-card"
                  :class="{ 'is-active': selectedNetwork === 'erc20' }"
                  @click="selectNetwork('erc20')"
              >
                <span class="network-name">ERC20</span>
                <el-icon v-if="selectedNetwork === 'erc20'" class="check-icon"><Select /></el-icon>
              </div>
            </div>

            <div class="usdt-info-area" v-if="selectedNetwork">
              <div class="qr-code-box">
                <el-image
                    v-if="usdtQrcode"
                    :src="usdtQrcode"
                    class="qr-img"
                    fit="contain"
                ></el-image>
                <div v-else class="empty-qr">
                  <el-icon :size="32" color="#666"><Picture /></el-icon>
                  <span class="empty-text">{{ t('获取中...') }}</span>
                </div>
              </div>

              <div class="address-box">
                <div class="address-label">{{ t('充值地址') }}</div>
                <el-input v-model="usdtQrcodeAdrees" readonly class="dark-input address-input">
                  <template #append>
                    <el-button @click="copyAddress" class="copy-btn">
                      <el-icon class="mr-1"><CopyDocument /></el-icon> {{ t('复制') }}
                    </el-button>
                  </template>
                </el-input>
                <div class="address-tip">
                  <el-icon class="mr-1"><Warning /></el-icon>
                  {{ t('请确认充值网络与地址正确无误，错误将导致资产丢失。') }}
                </div>
              </div>
            </div>

            <div class="rate-tip" v-if="usdtRate">
              {{ t('当前汇率 (USDT/RMB)') }}: <span class="rate-val">{{ usdtRate }}</span>
            </div>

            <div class="form-section" style="margin-top: 24px;" v-if="receiving_type != '1'">
              <div class="section-title">{{ t('充值金额') }}</div>
              <div class="amount-input-box">
                <span class="currency-symbol">₮</span>
                <el-input
                    v-model="amount"
                    type="number"
                    class="dark-input giant-input"
                    :placeholder="t('请输入充值金额')"
                />
              </div>
            </div>

            <div class="form-section upload-section" style="margin-top: 24px;" v-if="receiving_type != '1'">
              <div class="section-title">{{ t('上传支付凭证') }}</div>
              <div class="upload-container">
                <CUploadImage @change="changeImg" ref="CUploadImageRef" />
              </div>
              </div>

          </div>
        </template>

        <template v-if="currentChannel && !currentChannel.isUsdt">
          <div class="form-section">
            <div class="section-title">{{ t('充值金额') }}</div>

            <div class="amount-quick-list" v-if="currentChannel.config?.fixed">
              <div
                  v-for="(val, index) in currentChannel.config.fixed"
                  :key="index"
                  class="amount-card"
                  :class="{ 'is-active': amount === val }"
                  @click="selectFixedAmount(val)"
              >
                <span class="currency-symbol">￥</span>{{ val }}
              </div>
            </div>

            <div class="amount-input-box" v-else>
              <span class="currency-symbol">￥</span>
              <el-input
                  v-model="amount"
                  type="number"
                  class="dark-input giant-input"
                  :placeholder="`${t('限额')} ${currentChannel.config?.min || 0} - ${currentChannel.config?.max || '无限制'}`"
              />
            </div>

            <!-- 人工充值方式选择 -->
            <div class="form-section" style="margin-top: 24px;" v-if="currentChannel.value === 'rgcz'">
              <div class="section-title">{{ t('支付方式') }}</div>
              <div class="channel-list">
                <div
                    v-for="method in rgczMethods"
                    :key="method.value"
                    class="channel-card"
                    :class="{ 'is-active': selectedRgczMethod === method.value }"
                    @click="selectedRgczMethod = method.value"
                >
                  <span class="channel-name">{{ method.label }}</span>
                </div>
              </div>
            </div>

            </div>
        </template>
      </template>

      <template v-else>
        <div class="pay-result-area">
          <div class="qr-bg" v-if="payResult.image">
            <el-image :src="payResult.image" fit="contain" class="result-qr-img"></el-image>
          </div>
          <div class="pay-text-box">
            <div class="pay-text">
              {{ currentChannel?.label }}{{ t('充值确认') }}
              <br>{{ t('请使用浏览器扫码或者复制支付地址到浏览器打开') }}
              <br>{{ t('支付地址：') }}<a :href="payResult.url" target="_blank" class="pay-link">{{ payResult.url }}</a>
              <br>{{ t('支付金额：') }}{{ amount }} RMB
              <br>{{ t('请按实际支付金额进行付款，否则影响到账') }}
              <br>{{ t('支付完成后请耐心等待，支付到账会第一时间通知您！') }}
            </div>
          </div>
        </div>
      </template>

    </div>

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

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

import { getConfigIndex } from "@/request/api";
import CUploadImage from "@/components/CUploadImage/index.vue";

const { t, locale } = useI18n();

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

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

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

const CUploadImageRef = ref();
const loading = ref(false);

const channelList = ref([]);
const currentChannel = ref(null);
const amount = ref('');
const uploadFileUrl = ref('');
const payResult = ref(null);

const usdtRate = ref('');
const trc20Address = ref('');
const erc20Address = ref('');
const showThirdPayment = ref('0');
const selectedNetwork = ref('');
const usdtQrcode = ref('');
const receiving_type = ref('')
const usdtQrcodeAdrees = ref('')

const rgczMethods = [
  { label: '微信', value: 1 },
  { label: '支付宝', value: 2 },
  { label: '银行卡', value: 3 }
];
const selectedRgczMethod = ref('');

const currentAddress = computed(() => {
  if (selectedNetwork.value === 'trc20') return trc20Address.value;
  if (selectedNetwork.value === 'erc20') return erc20Address.value;
  return '';
});

watch(dialogVisible, (val) => {
  if (val && channelList.value.length === 0) {
    getData();
  }
});

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

const setDefaultNetwork = () => {
  if (trc20Address.value) {
    selectNetwork('trc20');
  } else if (erc20Address.value) {
    selectNetwork('erc20');
  }
};

const selectChannel = (item) => {
  currentChannel.value = item;
  amount.value = '';
  selectedNetwork.value = '';
  usdtQrcode.value = '';
  uploadFileUrl.value = '';
  payResult.value = null;
  selectedRgczMethod.value = '';
  if (CUploadImageRef.value) CUploadImageRef.value.handleDeleteAllImg();

  if (item.isUsdt) {
    setDefaultNetwork();
  }
};

const selectFixedAmount = (val) => {
  amount.value = val;
};

const selectNetwork = (network) => {
  selectedNetwork.value = network;
  getScanQrcode();
};

const copyAddress = async () => {
  if (!usdtQrcodeAdrees.value) return;
  try {
    await navigator.clipboard.writeText(usdtQrcodeAdrees.value);
    ElMessage.success(t('复制成功'));
  } catch (err) {
    ElMessage.success(t('复制成功'));
  }
};

const getData = async () => {
  loading.value = true;
  try {
    const configData = await getConfigIndex();
    if (configData && configData.data) {
      configData.data.forEach(item => {
        if (item.field === 'exchange_rate_rmb') usdtRate.value = item.val;
        if (item.field === 'receiving_address') trc20Address.value = item.val;
        if (item.field === 'receiving_address_erc20') erc20Address.value = item.val;
        if (item.field === 'three_payment_switch') showThirdPayment.value = item.val;
        if (item.field === 'receiving_type') receiving_type.value = item.val
      });
    }

    channelList.value = [];
    const res = await getChannel();
    if (res && res.list) {
      channelList.value = res.list.map(item => {
        if (item.value === 'usdt' || item.type === 'usdt' || item.isUsdt) {
          item.isUsdt = true;
        }
        return item;
      });
    }

    if (channelList.value.length > 0) {
      currentChannel.value = channelList.value[0];
      if (currentChannel.value.isUsdt) {
        setDefaultNetwork();
      }
    }
  } catch (error) {
    console.error('获取充值配置失败', error);
  } finally {
    loading.value = false;
  }
};

function getChannel() {
  return new Promise((resolve, reject) => {
    const token = localStorage.getItem('token') || '';
    fetch(apiUrl + 'wallet/channel', {
      method: 'GET',
      headers: { 'Authorization': token, 'lang': locale.value }
    })
        .then(res => res.json())
        .then(data => {
          if (data.code === 0) resolve(data.data);
          else reject(data.msg);
        })
        .catch(err => reject(err));
  });
}

function getScanQrcode() {
  const token = localStorage.getItem('token') || '';
  usdtQrcode.value = '';
  fetch(`${apiUrl}wallet/scan?type=${selectedNetwork.value}`, {
    method: 'GET',
    headers: { 'Authorization': token, 'lang': locale.value }
  })
      .then(res => res.json())
      .then(data => {
        if (data.code === 0 && data.data) {
          usdtQrcode.value = data.data.qrcode;
          usdtQrcodeAdrees.value = data.data.address
        } else {
          ElMessage.error(data.msg);
        }
      })
      .catch(() => {
        ElMessage.error(t('网络错误'));
      });
}

const submitRecharge = () => {
  if (!currentChannel.value) return ElMessage.warning(t('请选择支付方式'));
  if (!amount.value || Number(amount.value) <= 0) return ElMessage.warning(t('请输入有效的充值金额'));

  const token = localStorage.getItem('token') || '';
  loading.value = true;

  // 1. USDT 处理
  if (currentChannel.value.isUsdt) {
    if (!uploadFileUrl.value) {
      loading.value = false;
      return ElMessage.warning(t('请上传支付凭证'));
    }
    fetch(apiUrl + 'wallet/recharge', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': token, 'lang': locale.value },
      body: JSON.stringify({ amount: String(amount.value), image: uploadFileUrl.value, net: selectedNetwork.value, toAddress: currentAddress.value })
    })
    .then(res => res.json())
    .then(data => {
      loading.value = false;
      if (data.code === 0) { ElMessage.success(data.msg); emit('success'); dialogVisible.value = false; } else { ElMessage.error(data.msg); }
    })
    .catch(() => { loading.value = false; ElMessage.error(t('网络错误')); });

  } 
  // 2. 人工充值处理
  else if (currentChannel.value.value === 'rgcz') {
    if (!selectedRgczMethod.value) {
      loading.value = false;
      return ElMessage.warning(t('请选择支付方式'));
    }
    fetch(apiUrl + 'wallet/paymentOrder', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': token, 'lang': locale.value },
      body: JSON.stringify({ payment_type: selectedRgczMethod.value, amount: amount.value })
    })
    .then(res => res.json())
    .then(data => {
      loading.value = false;
      if (data.code === 0) { ElMessage.success(data.msg); dialogVisible.value = false; } else { ElMessage.error(data.msg); }
    })
    .catch(() => { loading.value = false; ElMessage.error(t('网络错误')); });
  }
  // 3. 第三方充值处理
  else {
    fetch(apiUrl + 'wallet/createPay', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': token, 'lang': locale.value },
      body: JSON.stringify({ payment_type: currentChannel.value.config.type, amount: amount.value })
    })
    .then(res => res.json())
    .then(data => {
      loading.value = false;
      if (data.code === 0) {
        if (data.data && (data.data.image || data.data.url)) { payResult.value = data.data; } else { ElMessage.success(data.msg); dialogVisible.value = false; }
      } else { ElMessage.error(data.msg); }
    })
    .catch(() => { loading.value = false; ElMessage.error(t('网络错误')); });
  }
};

const resetForm = () => {
  amount.value = '';
  uploadFileUrl.value = '';
  selectedNetwork.value = '';
  usdtQrcode.value = '';
  payResult.value = null; 
  selectedRgczMethod.value = '';
  if (CUploadImageRef.value) CUploadImageRef.value.handleDeleteAllImg();
};
</script>

<style scoped lang="scss">
/* (保持原样式不变) */
$main-color: #f8b932;
$bg-dark: #1a1a1a;
$border-color: #333;
$text-primary: #fff;
$text-secondary: #999;

:deep(.recharge-dialog) { background-color: #1e1e1e; border: 1px solid #333; border-radius: 8px; .el-dialog__title { color: $text-primary; font-weight: bold; } .el-dialog__headerbtn .el-dialog__close { color: $text-secondary; &:hover { color: $main-color; } } .el-dialog__body { padding: 20px 24px; } }
.recharge-modal-body { max-height: 60vh; overflow-y: auto; padding-right: 10px; &::-webkit-scrollbar { width: 6px; } &::-webkit-scrollbar-thumb { background: #444; border-radius: 4px; } }
.form-section { margin-bottom: 30px; .section-title { font-size: 14px; font-weight: bold; color: $text-primary; margin-bottom: 12px; display: flex; align-items: center; &::before { content: ''; display: inline-block; width: 4px; height: 14px; border-radius: 2px; background-color: $main-color; margin-right: 8px; } } }
.channel-list, .network-options { display: flex; flex-wrap: wrap; gap: 12px; .channel-card, .network-card { padding: 10px 24px; border: 1px solid $border-color; border-radius: 6px; background-color: $bg-dark; cursor: pointer; position: relative; transition: all 0.2s; color: $text-primary; font-size: 13px; font-weight: 500; min-width: 120px; text-align: center; &:hover { border-color: #666; } &.is-active { border-color: $main-color; background-color: rgba(248, 185, 50, 0.1); 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; } } }
.amount-quick-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 12px; .amount-card { padding: 12px 0; text-align: center; border: 1px solid $border-color; border-radius: 6px; background-color: $bg-dark; cursor: pointer; transition: all 0.2s; font-size: 16px; color: $text-primary; &:hover { border-color: #666; } &.is-active { border-color: $main-color; background-color: rgba(248, 185, 50, 0.1); color: $main-color; font-weight: bold; } .currency-symbol { font-size: 12px; margin-right: 2px; color: $text-secondary; } &.is-active .currency-symbol { color: $main-color; } } }
.amount-input-box { display: flex; align-items: center; gap: 12px; margin-top: 16px; .currency-symbol { font-size: 24px; font-weight: bold; color: $text-primary; } }
.usdt-info-area { display: flex; gap: 20px; background: $bg-dark; padding: 16px; border-radius: 8px; border: 1px solid $border-color; margin-top: 16px; align-items: center; .qr-code-box { width: 140px; height: 140px; background-color: #fff; border-radius: 8px; padding: 8px; flex-shrink: 0; .qr-img { width: 100%; height: 100%; } .empty-qr { width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; background: #f5f5f5; border-radius: 4px; .empty-text { font-size: 12px; margin-top: 8px; color: #666; } } } .address-box { flex: 1; .address-label { font-size: 13px; color: $text-secondary; margin-bottom: 8px; } .address-tip { font-size: 12px; color: #f56c6c; margin-top: 12px; display: flex; align-items: center; } } }
.pay-result-area { display: flex; flex-direction: column; align-items: center; padding: 10px 0; .qr-bg { background-color: #fff; padding: 12px; border-radius: 12px; margin-bottom: 20px; .result-qr-img { width: 180px; height: 180px; } } .pay-text-box { background: #141414; padding: 16px 20px; border-radius: 8px; border: 1px solid #333; width: 100%; box-sizing: border-box; .pay-text { color: #e5e5e5; font-size: 14px; line-height: 1.8; .pay-link { color: $main-color; text-decoration: none; word-break: break-all; &:hover { text-decoration: underline; } } } } }
.rate-tip { font-size: 12px; color: $text-secondary; margin-top: 12px; .rate-val { color: #f56c6c; font-weight: bold; font-family: DIN; } }
.mr-1 { margin-right: 4px; }
:deep(.dark-input) { .el-input__wrapper { background-color: #111 !important; box-shadow: 0 0 0 1px #444 inset !important; height: 40px; 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: #222 !important; border-color: #444 !important; color: #ccc; .copy-btn { color: #ccc; border: none; &:hover { color: $main-color; } } } }
:deep(.giant-input) { .el-input__wrapper { height: 48px; } .el-input__inner { font-size: 20px; font-weight: bold; font-family: DIN; } }
.dialog-footer { display: flex; justify-content: center; gap: 16px; .cancel-btn { background: transparent; color: $text-primary; border: 1px solid $border-color; width: 100px; &:hover { border-color: $main-color; color: $main-color; } } .submit-btn { width: 140px; font-weight: bold; color: #000; background-color: $main-color; border-color: $main-color; &:hover { opacity: 0.9; } } }
</style>