<template>
  <el-dialog
      v-model="dialogVisible"
      :title="t('提现设置')"
      width="860px"
      center
      class="custom-dark-dialog settings-main-dialog"
      align-center
      append-to-body
      @open="onDialogOpen"
  >
    <div class="settings-modal-body" v-loading="loading">

      <div class="channel-pills-container">
        <div
            class="pill-item"
            v-for="ch in channelOptions"
            :key="ch.value"
            :class="{ 'is-active': activeChannel === ch.value }"
            @click="switchChannel(ch.value)"
            v-show="ch.value !== 'rgtx'"
        >
          <el-icon v-if="ch.value === 'usdt'"><Link /></el-icon>
          <el-icon v-else-if="ch.value === 'DF002'"><Monitor /></el-icon>
          <el-icon v-else><CreditCard /></el-icon>
          <span class="ml-1">{{ ch.label }}</span>
        </div>
      </div>

      <div class="tab-content">
        <div class="cards-grid">

          <div class="add-card-btn" @click="openModal()">
            <el-icon class="plus-icon"><Plus /></el-icon>
            <span>{{ t('添加账户') }}</span>
          </div>

          <div
              class="wallet-card"
              :class="getCardSkin(activeChannel)"
              v-for="item in accountList"
              :key="item.id"
          >
            <template v-if="activeChannel === 'usdt'">
              <div class="card-header">
                <div class="bank-name">
                  <el-icon class="mr-1"><Link /></el-icon> {{ getChannelLabel('usdt') || 'USDT' }}
                </div>
                <div class="channel-tag" v-if="item.alias">{{ item.alias }}</div>
              </div>
              <div class="card-body">
                <div class="address-text">{{ item.address }}</div>
              </div>
              <div class="card-footer">
                <div class="account-name"></div>
                <div class="actions">
                  <el-icon class="action-icon edit" @click="openModal(item)" :title="t('编辑')"><Edit /></el-icon>
                  <el-icon class="action-icon delete" @click="handleDelete(item.id)" :title="t('删除')"><Delete /></el-icon>
                </div>
              </div>
            </template>

            <template v-else>
              <div class="card-header">
                <div class="bank-name">{{ item.bank_name }}</div>
                <div class="channel-tag" v-if="item.alias">{{ item.alias }}</div>
              </div>
              <div class="card-body">
                <div class="card-no">{{ formatCardNo(item.card_no) }}</div>
              </div>
              <div class="card-footer">
                <div class="account-name">{{ item.account }}</div>
                <div class="actions">
                  <el-icon class="action-icon edit" @click="openModal(item)" :title="t('编辑')"><Edit /></el-icon>
                  <el-icon class="action-icon delete" @click="handleDelete(item.id)" :title="t('删除')"><Delete /></el-icon>
                </div>
              </div>
            </template>
          </div>

        </div>

        <el-empty
            v-if="accountList.length === 0 && !loading"
            :description="t('当前通道暂无账户记录')"
            class="dark-empty"
        />
      </div>
    </div>
  </el-dialog>

  <el-dialog
      v-model="showBankModal"
      :title="bankForm.id ? t('编辑账户') : t('添加账户')"
      width="480px"
      center
      custom-class="dark-dialog"
      append-to-body
      @closed="resetBankForm"
  >
    <div class="modal-form-body">
      <div class="form-item">
        <div class="label">{{ t('提现通道') }}</div>
        <el-input
            :model-value="getChannelLabel(bankForm.channel)"
            class="dark-input std-input"
            disabled
        />
      </div>
      <div class="form-item">
        <div class="label">{{ t('银行名称/平台') }} <span class="required">*</span></div>
        <el-input v-model="bankForm.bank_name" class="dark-input std-input" :placeholder="getBankNamePlaceholder()" />
      </div>
      <div class="form-item">
        <div class="label">{{ t('收款账号') }} <span class="required">*</span></div>
        <el-input v-model="bankForm.card_no" class="dark-input std-input" :placeholder="t('请输入收款账号或银行卡号')" />
      </div>
      <div class="form-item">
        <div class="label">{{ t('真实姓名') }} <span class="required">*</span></div>
        <el-input v-model="bankForm.account" class="dark-input std-input" :placeholder="t('请输入收款人真实姓名')" />
      </div>
      <div class="form-item">
        <div class="label">{{ t('别名 (可选)') }}</div>
        <el-input v-model="bankForm.alias" class="dark-input std-input" :placeholder="t('如：我的建行卡')" />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button class="cancel-btn" @click="showBankModal = false">{{ t('取消') }}</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitBank" class="submit-btn">{{ t('保存') }}</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
      v-model="showAddressModal"
      :title="addressForm.id ? t('编辑账户') : t('添加账户')"
      width="480px"
      center
      custom-class="dark-dialog"
      append-to-body
      @closed="resetAddressForm"
  >
    <div class="modal-form-body">
      <div class="form-item">
        <div class="label">{{ t('提现通道') }}</div>
        <el-input :model-value="getChannelLabel('usdt') || 'USDT'" class="dark-input std-input" disabled />
      </div>
      <div class="form-item">
        <div class="label">{{ t('USDT 提现地址') }} <span class="required">*</span></div>
        <el-input v-model="addressForm.address" class="dark-input std-input" :placeholder="t('请输入准确的 USDT 地址')" />
      </div>
      <div class="form-item">
        <div class="label">{{ t('地址别名 (可选)') }}</div>
        <el-input v-model="addressForm.alias" class="dark-input std-input" :placeholder="t('如：波场TRC20钱包')" />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button class="cancel-btn" @click="showAddressModal = false">{{ t('取消') }}</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitAddress" class="submit-btn">{{ t('保存') }}</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage, ElMessageBox } from 'element-plus';
import { CreditCard, Link, Plus, Edit, Delete, Monitor } from '@element-plus/icons-vue';
import { apiUrl } from '@/request';

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 loading = ref(false);
const submitLoading = ref(false);

// 通道与列表状态
const channelOptions = ref([]);
const activeChannel = ref('');

// 列表数据管理
const bankList = ref([]);
const addressList = ref([]);

// 计算当前过滤后的账户列表
const accountList = computed(() => {
  if (activeChannel.value === 'usdt') {
    return addressList.value;
  }
  return bankList.value.filter(item => item.channel === activeChannel.value);
});

// 子弹窗状态
const showBankModal = ref(false);
const showAddressModal = ref(false);

// 表单数据
const bankForm = reactive({
  id: '',
  channel: '',
  account: '',
  card_no: '',
  bank_name: '',
  alias: ''
});

const addressForm = reactive({
  id: '',
  address: '',
  alias: ''
});

// 主弹窗打开时
const onDialogOpen = async () => {
  await fetchWithdrawChannels();
  if (channelOptions.value.length > 0) {
    activeChannel.value = channelOptions.value[0].value;
  }
  await fetchAllAccounts();
};

const switchChannel = (channelValue) => {
  if (activeChannel.value === channelValue) return;
  activeChannel.value = channelValue;
};

// ----------------------------------------
// 通用 Fetch 封装
// ----------------------------------------
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 fetchWithdrawChannels = async () => {
  try {
    const res = await customRequest('wallet/withdrawChannel', 'GET');
    if (res.code === 0 || res.code === 1) {
      channelOptions.value = res.data || [];
    }
  } catch (error) {
    console.error('获取提现通道失败', error);
  }
};

const getChannelLabel = (value) => {
  const target = channelOptions.value.find(item => item.value === value);
  return target ? target.label : value;
};

// 动态处理输入框提示
const getBankNamePlaceholder = () => {
  const current = channelOptions.value.find(c => c.value === activeChannel.value);
  if (current && current.label === '支付宝') return t('例如：支付宝');
  return t('请输入银行名称或平台名');
};

const getCardSkin = (channelVal) => {
  if (channelVal === 'usdt') return 'usdt-card';
  switch(channelVal) {
    case 'DF001': return 'bank-card-default';
    case 'DF002': return 'bank-card-alipay';
    case 'DF005': return 'bank-card-rmb';
    default: return 'bank-card-default';
  }
};

// ========================================
// 业务逻辑：获取全部账户列表
// ========================================
const fetchAllAccounts = async () => {
  loading.value = true;
  try {
    const [bankRes, addressRes] = await Promise.all([
      customRequest('wallet/bankList', 'GET'),
      customRequest('wallet/address', 'GET')
    ]);

    if (bankRes.code === 0 || bankRes.code === 1) {
      bankList.value = bankRes.data?.list || [];
    }
    if (addressRes.code === 0 || addressRes.code === 1) {
      addressList.value = addressRes.data?.list || [];
    }
  } catch (error) {
    console.error('获取账户失败', error);
  } finally {
    loading.value = false;
  }
};

// ========================================
// 业务逻辑：打开添加/编辑弹窗
// ========================================
const openModal = (item = null) => {
  // 修正：判断小写的 usdt
  if (activeChannel.value === 'usdt') {
    if (item) {
      addressForm.id = item.id;
      addressForm.address = item.address || '';
      addressForm.alias = item.alias || '';
    } else {
      resetAddressForm();
    }
    showAddressModal.value = true;
  } else {
    if (item) {
      bankForm.id = item.id;
      bankForm.channel = item.channel || activeChannel.value;
      bankForm.account = item.account || '';
      bankForm.card_no = item.card_no || '';
      bankForm.bank_name = item.bank_name || '';
      bankForm.alias = item.alias || '';
    } else {
      resetBankForm();
      bankForm.channel = activeChannel.value;
    }
    showBankModal.value = true;
  }
};

const resetBankForm = () => {
  bankForm.id = '';
  bankForm.channel = '';
  bankForm.account = '';
  bankForm.card_no = '';
  bankForm.bank_name = '';
  bankForm.alias = '';
};

const resetAddressForm = () => {
  addressForm.id = '';
  addressForm.address = '';
  addressForm.alias = '';
};

// ========================================
// 业务逻辑：提交保存
// ========================================
const submitBank = async () => {
  if (!bankForm.channel || !bankForm.account || !bankForm.card_no || !bankForm.bank_name) {
    return ElMessage.warning(t('请填写所有带 * 的必填项'));
  }
  submitLoading.value = true;
  try {
    const payload = { ...bankForm };
    if (!payload.id) delete payload.id;

    const res = await customRequest('wallet/addBank', 'POST', payload);
    if (res.code === 0 || res.code === 1) {
      ElMessage.success(res.msg || t('保存成功'));
      showBankModal.value = false;
      await fetchAllAccounts();
    } else {
      ElMessage.error(res.msg || t('保存失败'));
    }
  } catch (error) {
    console.error(error);
  } finally {
    submitLoading.value = false;
  }
};

const submitAddress = async () => {
  if (!addressForm.address) {
    return ElMessage.warning(t('请输入提现地址'));
  }
  submitLoading.value = true;
  try {
    const payload = { ...addressForm };
    if (!payload.id) delete payload.id;

    const res = await customRequest('wallet/addAddress', 'POST', payload);
    if (res.code === 0 || res.code === 1) {
      ElMessage.success(res.msg || t('保存成功'));
      showAddressModal.value = false;
      await fetchAllAccounts();
    } else {
      ElMessage.error(res.msg || t('保存失败'));
    }
  } catch (error) {
    console.error(error);
  } finally {
    submitLoading.value = false;
  }
};

// ========================================
// 业务逻辑：删除
// ========================================
const handleDelete = (id) => {
  ElMessageBox.confirm(t('确认要删除此账户记录吗？'), t('提示'), {
    confirmButtonText: t('确定'),
    cancelButtonText: t('取消'),
    type: 'warning',
    customClass: 'dark-message-box'
  }).then(async () => {
    loading.value = true;
    try {
      let res;
      // 修正：判断小写的 usdt
      if (activeChannel.value === 'usdt') {
        res = await customRequest('wallet/delAddress', 'GET', { id });
      } else {
        res = await customRequest('wallet/delBank', 'GET', { id });
      }

      if (res.code === 0 || res.code === 1) {
        ElMessage.success(res.msg || t('删除成功'));
        await fetchAllAccounts();
      } else {
        ElMessage.error(res.msg || t('删除失败'));
      }
    } catch (error) {
      console.error(error);
    } finally {
      loading.value = false;
    }
  }).catch(() => {});
};

// 工具函数
const formatCardNo = (no) => {
  if (!no) return '';
  if (no.length > 8) {
    return no.substring(0, 4) + ' **** **** ' + no.substring(no.length - 4);
  }
  return no;
};
</script>

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

/* --- 覆盖 el-dialog 原生样式，适配暗黑主题 --- */
:deep(.settings-main-dialog) {
  background-color: #1a1a1a;
  border: 1px solid #333;
  border-radius: 8px;

  .el-dialog__title { color: $text-primary; font-weight: bold; font-size: 18px; }
  .el-dialog__headerbtn .el-dialog__close { color: $text-secondary; &:hover { color: $main-color; } }
  .el-dialog__body { padding: 0; }
}

.settings-modal-body {
  min-height: 500px;
  display: flex;
  flex-direction: column;

  .channel-pills-container {
    display: flex;
    gap: 12px;
    padding: 16px 24px;
    border-bottom: 1px solid $border-color;
    background: rgba(255, 255, 255, 0.02);
    overflow-x: auto;

    &::-webkit-scrollbar { display: none; }

    .pill-item {
      padding: 10px 20px;
      border-radius: 20px;
      background-color: #2a2a2a;
      border: 1px solid #444;
      color: #aaa;
      font-size: 14px;
      cursor: pointer;
      display: flex;
      align-items: center;
      transition: all 0.3s;
      white-space: nowrap;

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

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

  .tab-content {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
    max-height: 60vh;

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

/* --- 卡片网格布局 --- */
.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.add-card-btn {
  height: 140px;
  border: 1px dashed #555;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: rgba(255, 255, 255, 0.01);
  transition: all 0.3s ease;
  color: $text-secondary;

  .plus-icon { font-size: 32px; margin-bottom: 12px; color: #666; transition: color 0.3s; }
  span { font-size: 14px; font-weight: bold; }

  &:hover {
    border-color: $main-color;
    background: rgba(248, 185, 50, 0.05);
    color: $main-color;
    .plus-icon { color: $main-color; }
  }
}

.wallet-card {
  height: 140px;
  border-radius: 12px;
  padding: 16px 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .bank-name { font-size: 16px; font-weight: bold; color: #fff; display: flex; align-items: center; }
    .channel-tag { font-size: 12px; background: rgba(255, 255, 255, 0.2); padding: 2px 8px; border-radius: 4px; color: #fff; }
  }

  .card-body {
    flex: 1;
    display: flex;
    align-items: center;

    .card-no { font-size: 18px; font-family: DIN, monospace; font-weight: bold; letter-spacing: 2px; color: #fff; text-shadow: 0 2px 4px rgba(0,0,0,0.5); }
    .address-text { font-size: 13px; color: #fff; word-break: break-all; opacity: 0.9; line-height: 1.4; }
  }

  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;

    .account-name { font-size: 13px; color: rgba(255, 255, 255, 0.8); }
    .actions {
      display: flex;
      gap: 12px;
      .action-icon {
        font-size: 16px; color: rgba(255, 255, 255, 0.6); cursor: pointer; transition: color 0.2s;
        &:hover { color: #fff; }
        &.edit:hover { color: $main-color; }
        &.delete:hover { color: #f56c6c; }
      }
    }
  }
}

.bank-card-default {
  background: linear-gradient(135deg, #2b5876 0%, #4e4376 100%);
  border: 1px solid #4e4376;
}
.bank-card-alipay {
  background: linear-gradient(135deg, #005C97 0%, #363795 100%);
  border: 1px solid #005C97;
}
.bank-card-rmb {
  background: linear-gradient(135deg, #cb2d3e 0%, #ef473a 100%);
  border: 1px solid #cb2d3e;
}
.usdt-card {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  border: 1px solid #11998e;
}

.modal-form-body {
  padding: 10px 0 20px;

  .form-item {
    margin-bottom: 20px;
    &:last-child { margin-bottom: 0; }

    .label {
      font-size: 13px;
      color: $text-secondary;
      margin-bottom: 8px;
      .required { color: #f56c6c; margin-left: 4px; }
    }
  }
}

.ml-1 { margin-left: 4px; }
.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 $main-color inset !important; }

    &.is-disabled {
      background-color: #000 !important;
      .el-input__inner { color: $main-color !important; -webkit-text-fill-color: $main-color !important; font-weight: bold; }
    }
  }
  .el-input__inner { color: #fff !important; }
}

:deep(.dark-dialog) {
  background-color: $card-bg;
  border: 1px solid $border-color;
  border-radius: 12px;

  .el-dialog__title { color: $text-primary; font-weight: bold; }
  .el-dialog__headerbtn .el-dialog__close { color: $text-secondary; &:hover { color: $main-color; } }

  .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>

<style>
.dark-message-box {
  background-color: #1e1e1e !important;
  border: 1px solid #333 !important;
}
.dark-message-box .el-message-box__title,
.dark-message-box .el-message-box__content {
  color: #fff !important;
}
.dark-message-box .el-button--default {
  background: transparent !important;
  border-color: #444 !important;
  color: #fff !important;
}
.dark-message-box .el-button--default:hover {
  border-color: #f8b932 !important;
  color: #f8b932 !important;
}
.dark-message-box .el-button--primary {
  background-color: #f8b932 !important;
  border-color: #f8b932 !important;
  color: #000 !important;
}
</style>