<template>
  <el-dialog
      v-model="dialogVisible"
      :title="t('提现')"
      width="600px"
      center
      class="custom-dark-dialog withdraw-dialog"
      align-center
      append-to-body
      @closed="resetForm"
      draggable
  >
    <div class="withdraw-modal-body" v-loading="loading">

      <div class="section-title">
        <div class="stick"></div>
        <span>{{ t('选择提现方式') }}</span>
      </div>

      <div class="channel-list" v-if="channelList.length > 0">
        <div
            class="channel-item"
            v-for="(item, index) in channelList"
            :key="item.value"
            :class="{ 'is-active': activeChannelIndex === index }"
            @click="switchChannel(index)"
        >
          <span class="channel-name">{{ item.label }}</span>
          <el-icon class="check-icon" v-if="activeChannelIndex === index"><Select /></el-icon>
        </div>
      </div>

      <div v-else class="loading-channels">
        <el-skeleton animated>
          <template #template>
            <div style="display: flex; gap: 12px;">
              <el-skeleton-item variant="rect" style="width: 140px; height: 44px; border-radius: 6px;" />
              <el-skeleton-item variant="rect" style="width: 140px; height: 44px; border-radius: 6px;" />
            </div>
          </template>
        </el-skeleton>
      </div>

      <div class="form-card" v-if="channelList.length > 0">

        <div class="form-group amount-group">
          <span class="label">{{ t('提现金额') }}</span>
          <div class="input-box">
            <span class="currency-symbol">{{ isUSDT ? '$' : '¥' }}</span>
            <el-input
                type="number"
                v-model="formData.amount"
                class="dark-input amount-input"
                :placeholder="t('请输入提现金额')"
            />
          </div>
          <div class="limit-hint" v-if="currentChannel && currentChannel.config">
            <span>{{ t('单笔限额') }}: {{ currentChannel.config.min }} - {{ currentChannel.config.max }}</span>
          </div>
        </div>

        <el-divider border-style="dashed" class="dark-divider" />

        <div class="form-group" v-if="currentChannel.value !== 'rgtx'">
          <span class="label">{{ t('收款账户') }}</span>

          <template v-if="accountList.length > 0">
            <el-select
                v-model="selectedAccountId"
                class="dark-select"
                :placeholder="t('请选择收款账户')"
                style="width: 100%;"
            >
              <el-option
                  v-for="acc in accountList"
                  :key="acc.id"
                  :label="formatAccountLabel(acc)"
                  :value="acc.id"
              >
                <div class="account-option-item">
                  <span v-if="isUSDT">
                    <span class="acc-alias">{{ acc.alias || 'USDT' }}</span>
                    <span class="acc-detail">{{ formatCardNo(acc.address) }}</span>
                  </span>
                  <span v-else>
                    <span class="acc-alias">{{ acc.bank_name }} ({{ acc.account }})</span>
                    <span class="acc-detail">{{ formatCardNo(acc.card_no) }}</span>
                  </span>
                </div>
              </el-option>
            </el-select>
          </template>

          <template v-else>
            <div class="empty-account-box">
              <el-icon class="mr-1"><Warning /></el-icon>
              <span>{{ t('当前通道暂无绑定的收款账户，请先') }}</span>
              <span class="highlight-text" @click="() => {
                showWalletManagement = true
                dialogVisible = false
              }">{{ t('前往提现设置添加') }}</span>
            </div>
          </template>
        </div>

        <template v-if="currentChannel.value === 'rgtx'">
          <div class="form-group">
            <span class="label">{{ t('银行名称/平台') }} <span style="color: #f56c6c;">*</span></span>
            <el-input
                v-model="formData.bank_name"
                class="dark-input std-input"
                :placeholder="t('请输入银行名称或平台名')"
            />
          </div>

          <div class="form-group">
            <span class="label">{{ t('收款账号(卡号)') }} <span style="color: #f56c6c;">*</span></span>
            <el-input
                v-model="formData.card_no"
                class="dark-input std-input"
                :placeholder="t('请输入收款账号或银行卡号')"
            />
          </div>

          <div class="form-group">
            <span class="label">{{ t('真实姓名') }} <span style="color: #f56c6c;">*</span></span>
            <el-input
                v-model="formData.account"
                class="dark-input std-input"
                :placeholder="t('请输入收款人真实姓名')"
            />
          </div>

          <div class="form-group">
            <span class="label">{{ t('别名 (可选)') }}</span>
            <el-input
                v-model="formData.alias"
                class="dark-input std-input"
                :placeholder="t('如：我的建行卡')"
            />
          </div>
        </template>

        <div class="form-group" style="margin-top: 24px;">
          <span class="label">{{ t('资金密码') }}</span>
          <el-input
              type="password"
              v-model="formData.safe_word"
              class="dark-input std-input"
              :placeholder="t('请输入您的资金密码')"
              show-password
          />
        </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="handleSubmit"
            :disabled="channelList.length === 0 || (currentChannel.value !== 'rgtx' && accountList.length === 0)"
            class="submit-btn"
        >
          {{ t('确认提现') }}
        </el-button>
      </span>
    </template>
  </el-dialog>

  <WalletManagement v-model="showWalletManagement" />
</template>

<script setup>
import { ref, computed, reactive, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { Select, Warning } from '@element-plus/icons-vue';
import { useUserStore } from '@/store/user';
import { getBalance } from '@/request/api'
import WalletManagement from '@/businessComponents/WalletManagement/index.vue';

// ================== 钱包管理 ==================
const showWalletManagement = ref(false);
// 获取 baseUrl 配置
import { apiUrl } from "@/request/index";

const userStore = useUserStore();

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

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

const { t, locale } = useI18n();

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

const loading = ref(false);

// 封装原生 Fetch 请求以适配 PC 端
const customRequest = (path, method = 'GET', data = {}) => {
  return new Promise((resolve, reject) => {
    const token = localStorage.getItem('token') || '';
    let url = apiUrl + path;
    const options = {
      method: method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
        'lang': locale.value
      }
    };

    if (method === 'GET') {
      const queryParams = new URLSearchParams(data).toString();
      if (queryParams) url += `?${queryParams}`;
    } else {
      options.body = JSON.stringify(data);
    }

    fetch(url, options)
        .then(res => res.json())
        .then(resData => resolve(resData))
        .catch(err => reject(err));
  });
};

// --- 状态管理 ---
const channelList = ref([]);
const activeChannelIndex = ref(0);

const accountList = ref([]); // 账户列表
const selectedAccountId = ref(''); // 选中的账户 ID

const formData = reactive({
  amount: '',
  safe_word: '',
  bank_name: '',
  card_no: '',
  account: '',
  alias: ''
});

// 监听弹窗打开，初始化数据
watch(dialogVisible, (val) => {
  if (val && channelList.value.length === 0) {
    fetchChannels();
  } else if (val) {
    // 每次打开重新获取一下当前通道的账户列表（防止用户在外面刚刚添加了新账户）
    fetchAccountList();
  }
});

// --- 计算属性 ---
const currentChannel = computed(() => channelList.value[activeChannelIndex.value] || {});
const isUSDT = computed(() => currentChannel.value?.value === 'usdt');

// 格式化账户下拉框显示的选中文字
const formatAccountLabel = (acc) => {
  if (isUSDT.value) {
    return `${acc.alias || 'USDT'} - ${formatCardNo(acc.address)}`;
  } else {
    return `${acc.bank_name}(${acc.account}) - ${formatCardNo(acc.card_no)}`;
  }
};

const formatCardNo = (no) => {
  if (!no) return '';
  if (no.length > 12) {
    return no.substring(0, 4) + ' **** **** ' + no.substring(no.length - 4);
  } else if (no.length > 4) {
    return no.substring(0, 3) + ' **** ' + no.substring(no.length - 3);
  }
  return no;
};

// --- 获取提现渠道 ---
const fetchChannels = async () => {
  loading.value = true;
  try {
    const res = await customRequest('wallet/withdrawChannel', 'GET');
    if (res.code === 0 || res.code === 1) {
      channelList.value = res.data || [];
      if (channelList.value.length > 0) {
        await fetchAccountList();
      }
    } else {
      ElMessage.error(res.msg || t('获取提现渠道失败'));
    }
  } catch (error) {
    console.error('Fetch Channels Error:', error);
  } finally {
    loading.value = false;
  }
};

// --- 获取通道对应的账户列表 ---
const fetchAccountList = async () => {
  // 如果是 rgtx 则不强制依赖 accountList，可以选择跳过或继续加载
  loading.value = true;
  selectedAccountId.value = '';
  accountList.value = [];
  try {
    if (isUSDT.value) {
      const res = await customRequest('wallet/address', 'GET');
      if (res.code === 0 || res.code === 1) {
        accountList.value = res.data?.list || [];
      }
    } else {
      const res = await customRequest('wallet/bankList', 'GET', { channel: currentChannel.value.value });
      if (res.code === 0 || res.code === 1) {
        accountList.value = res.data?.list || [];
      }
    }

    // 默认选中第一个可用账户
    if (accountList.value.length > 0) {
      selectedAccountId.value = accountList.value[0].id;
    }
  } catch (error) {
    console.error('Fetch Accounts Error:', error);
  } finally {
    loading.value = false;
  }
};

// --- 切换渠道 ---
const switchChannel = async (index) => {
  if (activeChannelIndex.value === index) return;
  activeChannelIndex.value = index;

  formData.amount = '';
  formData.safe_word = '';
  formData.bank_name = '';
  formData.card_no = '';
  formData.account = '';
  formData.alias = '';

  await fetchAccountList();
};

// --- 提交提现逻辑 ---
const handleSubmit = async () => {
  if (!formData.amount || Number(formData.amount) <= 0) {
    return ElMessage.warning(t('请输入有效的提现金额'));
  }

  // 金额大小限制校验
  const amountNum = Number(formData.amount);
  const minLimit = currentChannel.value.config?.min;
  const maxLimit = currentChannel.value.config?.max;

  if (minLimit !== undefined && amountNum < minLimit) {
    return ElMessage.warning(`${t('单笔最小提现金额为')} ${minLimit}`);
  }
  if (maxLimit !== undefined && amountNum > maxLimit) {
    return ElMessage.warning(`${t('单笔最大提现金额为')} ${maxLimit}`);
  }

  // 针对通道为 rgtx 和其他情况做不同的校验
  if (currentChannel.value.value === 'rgtx') {
    if (!formData.bank_name) return ElMessage.warning(t('请输入银行名称或平台名'));
    if (!formData.card_no) return ElMessage.warning(t('请输入收款账号或银行卡号'));
    if (!formData.account) return ElMessage.warning(t('请输入收款人真实姓名'));
  } else {
    if (!selectedAccountId.value) {
      return ElMessage.warning(t('请选择收款账户'));
    }
  }

  if (!formData.safe_word) {
    return ElMessage.warning(t('请输入资金密码'));
  }

  loading.value = true;

  try {
    let res;
    if (currentChannel.value.value === 'rgtx') {
      res = await customRequest('wallet/payout', 'POST', {
        account: formData.account,
        amount: String(formData.amount),
        bank_name: formData.bank_name,
        card_no: formData.card_no,
        channel: currentChannel.value.value,
        safe_word: formData.safe_word,
        alias: formData.alias
      });
    } else if (isUSDT.value) {
      const targetAccount = accountList.value.find(acc => acc.id === selectedAccountId.value);
      if (!targetAccount) { loading.value = false; return; }

      res = await customRequest('wallet/withdraw', 'POST', {
        address: targetAccount.address,
        amount: String(formData.amount),
        safe_word: formData.safe_word
      });
    } else {
      const targetAccount = accountList.value.find(acc => acc.id === selectedAccountId.value);
      if (!targetAccount) { loading.value = false; return; }

      res = await customRequest('wallet/payout', 'POST', {
        account: targetAccount.account,
        amount: String(formData.amount),
        bank_name: targetAccount.bank_name,
        card_no: targetAccount.card_no,
        channel: currentChannel.value.value,
        safe_word: formData.safe_word
      });
    }

    loading.value = false;

    if (res.code === 0 || res.code === 1) {
      ElMessage.success(res.msg || t('提现申请提交成功'));

      emit('success');
      dialogVisible.value = false;

      // 刷新余额
      getBalance().then(res => {
        if(res.code === 1) {
          userStore.balance = res.data.money;
        }
      });
    } else {
      ElMessage.error(res.msg || t('提现失败，请重试'));
    }

  } catch (error) {
    loading.value = false;
    console.error('Withdraw Submit Error:', error);
    ElMessage.error(t('网络异常，请稍后再试'));
  }
};

// --- 重置表单 ---
const resetForm = () => {
  formData.amount = '';
  formData.safe_word = '';
  formData.bank_name = '';
  formData.card_no = '';
  formData.account = '';
  formData.alias = '';
};
</script>

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

/* --- 覆盖 el-dialog 原生样式，适配暗黑主题 --- */
:deep(.withdraw-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;
  }
}

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

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

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  font-size: 15px;
  font-weight: bold;
  color: $text-primary;
  margin-top: 10px;

  .stick {
    width: 4px;
    height: 14px;
    background-color: $main-color;
    border-radius: 2px;
  }
}

/* 渠道选择网格 */
.channel-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 24px;

  .channel-item {
    position: relative;
    background-color: $bg-dark;
    border: 1px solid $border-color;
    border-radius: 6px;
    padding: 12px 24px;
    text-align: center;
    transition: all 0.2s ease;
    cursor: pointer;
    min-width: 120px;

    .channel-name {
      font-size: 14px;
      color: $text-secondary;
      font-weight: 500;
      transition: color 0.2s;
    }

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

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

      .channel-name {
        color: $main-color;
        font-weight: bold;
      }

      .check-icon {
        position: absolute;
        bottom: 0;
        right: 0;
        background: $main-color;
        color: #000;
        padding: 2px;
        font-size: 12px;
        border-radius: 4px 0 0 0;
      }
    }
  }
}

.loading-channels {
  margin-bottom: 24px;
}

/* 表单卡片区 */
.form-card {
  background-color: transparent;

  .dark-divider {
    border-color: #333;
    margin: 24px 0;
  }

  .form-group {
    margin-bottom: 16px;

    .label {
      display: block;
      font-size: 13px;
      color: $text-secondary;
      margin-bottom: 8px;
    }
  }

  /* 下拉框里的选项布局 */
  .account-option-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    .acc-alias { color: #fff; font-weight: bold; }
    .acc-detail { color: #888; font-family: DIN, monospace; font-size: 12px; }
  }

  /* 提现金额特殊巨大字体输入框 */
  .amount-group {
    .input-box {
      display: flex;
      align-items: center;
      gap: 12px;
      background-color: $bg-dark;
      border: 1px solid $border-color;
      border-radius: 8px;
      padding: 0 16px;
      transition: border-color 0.3s;

      &:focus-within {
        border-color: $main-color;
      }

      .currency-symbol {
        font-size: 24px;
        font-weight: bold;
        color: $text-primary;
        font-family: DIN, monospace;
      }

      :deep(.amount-input) {
        .el-input__wrapper {
          background: transparent !important;
          box-shadow: none !important;
          padding: 0;
          height: 54px;
        }
        .el-input__inner {
          font-size: 24px;
          font-weight: bold;
          color: $main-color !important;
          font-family: DIN, monospace;
        }
      }
    }

    .limit-hint {
      margin-top: 8px;
      font-size: 12px;
      color: $text-secondary;
    }
  }

  /* 空账户提示 */
  .empty-account-box {
    display: flex;
    align-items: center;
    background-color: rgba(245, 108, 108, 0.1);
    border: 1px solid rgba(245, 108, 108, 0.3);
    padding: 10px 16px;
    border-radius: 6px;
    color: #f56c6c;
    font-size: 13px;

    .highlight-text {
      color: $main-color;
      margin-left: 4px;
      font-weight: bold;
      text-decoration: underline;
      cursor: pointer;
    }
  }

  /* 标准输入框深度覆盖 */
  :deep(.std-input), :deep(.dark-select) {
    .el-input__wrapper {
      background-color: $bg-dark !important;
      box-shadow: 0 0 0 1px $border-color inset !important;
      height: 40px;
      border-radius: 6px;
      transition: all 0.3s;

      &:hover, &.is-focus {
        box-shadow: 0 0 0 1px #666 inset !important;
      }
    }
    .el-input__inner {
      color: $text-primary !important;
      font-size: 14px;
    }
  }
}

/* --- 底部按钮区 --- */
.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; }
    &:disabled {
      background-color: #555;
      border-color: #555;
      color: #888;
    }
  }
}
</style>
