<template>
  <div class="yuebao-page-container">
    <div class="yuebao-wrapper">
      
      <div class="dashboard-card">
        <div class="header-left">
          <!-- 新增返回按钮 -->
          <el-button link class="back-btn" @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            <!-- {{ t('返回') }} -->
          </el-button>
          <div class="decorate-bar"></div>
          <div class="title-info">
            <span class="title-text">{{ t('余额宝') }}</span>
            <span class="sub-text">{{ t('灵活存取，稳健收益') }}</span>
          </div>
        </div>
        
        <div class="header-assets">
          <div class="asset-box">
            <div class="asset-title">{{ t('余额宝总额(元)') }}</div>
            <div class="asset-amount text-gold">{{ yuebaoBalance }}</div>
          </div>
          <div class="asset-divider"></div>
          <div class="asset-box">
            <div class="asset-title">{{ t('累计收益(元)') }}</div>
            <div class="asset-amount">{{ yuebaoInterest }}</div>
          </div>
        </div>

        <div class="header-actions">
          <el-button type="primary" class="action-btn add-btn" @click="openAddModal">
            <el-icon class="mr-1"><Download /></el-icon> {{ t('转入') }}
          </el-button>
          <el-button class="action-btn out-btn" @click="openOutModal">
            <el-icon class="mr-1"><Upload /></el-icon> {{ t('转出') }}
          </el-button>
          <el-button class="action-btn detail-btn" @click="goToDetail">
            <el-icon class="mr-1"><List /></el-icon> {{ t('明细') }}
          </el-button>
        </div>
      </div>

      <div class="list-card">
        <div class="list-header">
          <div class="list-title">{{ t('持仓明细') }}</div>
          <el-button link type="primary" @click="handleRefresh">
            <el-icon class="mr-1"><RefreshRight /></el-icon> {{ t('刷新') }}
          </el-button>
        </div>

        <div class="filter-bar">
          <div class="filter-item">
            <span class="filter-label">{{ t('状态') }}</span>
            <el-select 
              v-model="queryParams.status" 
              class="dark-select" 
              :placeholder="t('全部')" 
              clearable 
              style="width: 140px;"
            >
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>

          <div class="filter-item">
            <span class="filter-label">{{ t('时间范围') }}</span>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              :range-separator="t('至')"
              :start-placeholder="t('开始日期')"
              :end-placeholder="t('结束日期')"
              value-format="YYYY-MM-DD"
              class="dark-date-picker"
              style="width: 280px;"
            />
          </div>

          <div class="filter-actions">
            <el-button type="primary" @click="handleSearch" class="search-btn">
              <el-icon class="mr-1"><Search /></el-icon> {{ t('搜索') }}
            </el-button>
            <el-button @click="handleReset" class="reset-btn">
              <el-icon class="mr-1"><Refresh /></el-icon> {{ t('重置') }}
            </el-button>
          </div>
        </div>

        <div class="table-content" v-loading="loading">
          <el-table
            :data="tableData"
            style="width: 100%;"
            class="dark-table"
            :empty-text="t('暂无持仓记录')"
          >
            <el-table-column prop="id" label="ID" width="100" align="center" />
            
            <el-table-column :label="t('本金')" min-width="120" align="right">
              <template #default="scope">
                <span class="amount-text text-gold">{{ formatMoney(scope.row.principal) }}</span>
              </template>
            </el-table-column>

            <el-table-column :label="t('剩余本金')" min-width="120" align="right">
              <template #default="scope">
                <span class="amount-text">{{ formatMoney(scope.row.surplus_principal) }}</span>
              </template>
            </el-table-column>

            <el-table-column :label="t('状态')" min-width="100" align="center">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)" effect="dark" size="small">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column :label="t('预估收益')" min-width="160" align="center">
              <template #default="scope">
                <span class="amount-text">{{ scope.row.estimated_interest }}</span>
              </template>
            </el-table-column>
            

            <el-table-column :label="t('转入时间')" min-width="160" align="center">
              <template #default="scope">
                <span class="time-text">{{ formatTime(scope.row.create_time) }}</span>
              </template>
            </el-table-column>

            <el-table-column :label="t('更新时间')" min-width="160" align="center">
              <template #default="scope">
                <span class="time-text">{{ formatTime(scope.row.update_time) }}</span>
              </template>
            </el-table-column>

            <template #empty>
              <el-empty :description="t('暂无符合条件的记录')" class="dark-empty"></el-empty>
            </template>
          </el-table>
        </div>

        <div class="pagination-wrapper" v-if="total > 0">
          <el-pagination
            v-model:current-page="queryParams.page"
            v-model:page-size="queryParams.limit"
            :page-sizes="[10, 20, 50]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="dark-pagination"
          />
        </div>
      </div>

    </div>

    <el-dialog
      v-model="showAddModal"
      :title="t('转入余额宝')"
      width="400px"
      center
      custom-class="dark-dialog"
      @closed="resetForm"
    >
      <div class="modal-form-body">
        <div class="form-item">
          <div class="label">{{ t('转入金额') }}</div>
          <el-input 
            v-model="amount" 
            type="number" 
            class="dark-input giant-input" 
            :placeholder="t('请输入转入金额，最小为 1')" 
          >
            <template #prefix><span class="currency-symbol">￥</span></template>
          </el-input>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button class="cancel-btn" @click="showAddModal = false">{{ t('取消') }}</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitAdd" class="submit-btn">{{ t('确认转入') }}</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showOutModal"
      :title="t('转出余额宝')"
      width="400px"
      center
      custom-class="dark-dialog"
      @closed="resetForm"
    >
      <div class="modal-form-body">
        <div class="form-item">
          <div class="label">{{ t('转出金额') }}</div>
          <el-input 
            v-model="amount" 
            type="number" 
            class="dark-input giant-input" 
            :placeholder="t('请输入转出金额')" 
          >
            <template #prefix><span class="currency-symbol">￥</span></template>
          </el-input>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button class="cancel-btn" @click="showOutModal = false">{{ t('取消') }}</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitOut" class="submit-btn">{{ t('确认转出') }}</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
// 新增引入 ArrowLeft
import { Download, Upload, RefreshRight, Search, Refresh, List, ArrowLeft } from '@element-plus/icons-vue';

// 引入你的接口 (新增 getBalance)
import { addYuebao, withdrawYuebao, getYuebaoItemList, getBalance } from '@/request/api.js';

const { t } = useI18n();
const router = useRouter();

const loading = ref(false);
const tableData = ref([]);
const total = ref(0);

// === 新增：资产数据 ===
const yuebaoBalance = ref('0.00');
const yuebaoInterest = ref('0.00');

// 日期范围
const dateRange = ref([]);

const queryParams = reactive({
  page: 1,
  limit: 20,
  status: '', 
  start_time: '',
  end_time: ''
});

// 状态下拉配置
const statusOptions = computed(() => [
  { label: t('全部'), value: '' },
  { label: t('持仓中'), value: 1 },
  { label: t('已取出'), value: 2 }
]);

// 弹窗与表单状态
const showAddModal = ref(false);
const showOutModal = ref(false);
const amount = ref('');
const submitLoading = ref(false);

onMounted(() => {
  fetchData();
  fetchBalance(); // 初始化获取余额宝资产信息
});

// --- 新增：返回功能 ---
const goBack = () => {
  router.back();
};

// --- 新增：跳转到明细页面 ---
const goToDetail = () => {
  router.push({ name: 'YuebaoItemList' });
};

// --- 获取余额宝资产信息 ---
const fetchBalance = async () => {
  try {
    const res = await getBalance();
    if (res && res.code === 1 && res.data) {
      yuebaoBalance.value = res.data.yuebao || '0.00';
      yuebaoInterest.value = res.data.yuebao_invest || '0.00';
    }
  } catch (error) {
    console.error('获取余额失败', error);
  }
};

// --- 获取持仓列表 ---
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getYuebaoItemList(queryParams);
    if (res && res.code === 1) {
      tableData.value = res.data.list || res.data.data || [];
      total.value = res.data.total || tableData.value.length || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取持仓列表失败', error);
  } finally {
    loading.value = false;
  }
};

// --- 搜索与重置 ---
const handleSearch = () => {
  queryParams.page = 1;
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.start_time = dateRange.value[0];
    queryParams.end_time = dateRange.value[1];
  } else {
    queryParams.start_time = '';
    queryParams.end_time = '';
  }
  fetchData();
};

const handleReset = () => {
  queryParams.status = '';
  dateRange.value = [];
  queryParams.start_time = '';
  queryParams.end_time = '';
  queryParams.page = 1;
  fetchData();
};

// --- 操作响应 ---
const handleRefresh = () => {
  fetchData();
  fetchBalance(); // 刷新列表时同步刷新余额宝资产
};

const handleSizeChange = (val) => {
  queryParams.limit = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  queryParams.page = val;
  fetchData();
};

const openAddModal = () => {
  showAddModal.value = true;
};

const openOutModal = () => {
  showOutModal.value = true;
};

const resetForm = () => {
  amount.value = '';
};

// --- 提交转入 ---
const submitAdd = async () => {
  if (!amount.value || Number(amount.value) < 1) {
    return ElMessage.warning(t('转入金额最小为 1'));
  }
  submitLoading.value = true;
  try {
    const res = await addYuebao({ amount: String(amount.value) });
    if (res.code === 1 || res.code === 0) { 
      ElMessage.success(res.msg || t('转入成功'));
      showAddModal.value = false;
      handleRefresh(); // 转入成功后刷新列表和资产
    } else {
      ElMessage.error(res.msg || t('转入失败'));
    }
  } catch (error) {
    console.error(error);
  } finally {
    submitLoading.value = false;
  }
};

// --- 提交转出 ---
const submitOut = async () => {
  if (!amount.value || Number(amount.value) <= 0) {
    return ElMessage.warning(t('请输入有效的转出金额'));
  }
  submitLoading.value = true;
  try {
    const res = await withdrawYuebao({ amount: String(amount.value) });
    if (res.code === 1 || res.code === 0) {
      ElMessage.success(res.msg || t('转出成功'));
      showOutModal.value = false;
      handleRefresh(); // 转出成功后刷新列表和资产
    } else {
      ElMessage.error(res.msg || t('转出失败'));
    }
  } catch (error) {
    console.error(error);
  } finally {
    submitLoading.value = false;
  }
};

// --- 工具函数 ---
const formatMoney = (val) => {
  if (!val && val !== 0) return '0.00';
  return Number(val).toFixed(2);
};

const formatTime = (timestamp) => {
  if (!timestamp) return '--';
  const time = timestamp.toString().length === 10 ? timestamp * 1000 : timestamp;
  const date = new Date(time);
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  const h = String(date.getHours()).padStart(2, '0');
  const min = String(date.getMinutes()).padStart(2, '0');
  const s = String(date.getSeconds()).padStart(2, '0');
  return `${y}-${m}-${d} ${h}:${min}:${s}`;
};

const getStatusText = (status) => {
  if (Number(status) === 1) return t('持仓中');
  if (Number(status) === 2) return t('已取出');
  return t('未知');
};

const getStatusType = (status) => {
  if (Number(status) === 1) return 'success';
  if (Number(status) === 2) return 'info';
  return 'info';
};
</script>

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

.yuebao-page-container {
  min-height: calc(100vh - 64px);
  background-color: $bg-dark;
  padding: 30px 20px;
  box-sizing: border-box;
}

.yuebao-wrapper {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* ==================================
   1. 顶部操作看板
   ================================== */
.dashboard-card {
  background: linear-gradient(135deg, #1e1e1e 0%, #2a2a2a 100%);
  border-radius: 12px;
  padding: 30px 40px;
  border: 1px solid $border-color;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);

  .header-left {
    display: flex;
    align-items: center;

    /* 新增返回按钮样式 */
    .back-btn {
      margin-right: 16px;
      font-size: 20px;
      color: $text-secondary;
      &:hover {
        color: $main-color;
      }
    }

    .decorate-bar {
      width: 6px;
      height: 36px;
      background-color: $main-color;
      border-radius: 3px;
      margin-right: 16px;
    }

    .title-info {
      display: flex;
      flex-direction: column;
      gap: 4px;

      .title-text { font-size: 24px; font-weight: bold; color: $text-primary; letter-spacing: 1px; }
      .sub-text { font-size: 13px; color: $text-secondary; }
    }
  }

  /* === 资产展示区 === */
  .header-assets {
    display: flex;
    align-items: center;
    gap: 40px;
    margin-left: 60px;
    margin-right: auto; // 将按钮挤到最右边

    .asset-box {
      display: flex;
      flex-direction: column;
      gap: 6px;

      .asset-title {
        font-size: 14px;
        color: $text-secondary;
      }
      
      .asset-amount {
        font-size: 28px;
        font-weight: 900;
        font-family: DIN, monospace;
        color: $text-primary;
        line-height: 1;
        
        &.text-gold {
          color: $main-color;
          text-shadow: 0 2px 10px rgba(248, 185, 50, 0.2);
        }
      }
    }

    .asset-divider {
      width: 1px;
      height: 40px;
      background-color: $border-color;
    }
  }

  .header-actions {
    display: flex;
    gap: 16px;

    .action-btn {
      height: 44px;
      padding: 0 30px;
      font-size: 15px;
      font-weight: bold;
      border-radius: 6px;
    }

    .add-btn {
      background-color: $main-color;
      border-color: $main-color;
      color: #000;
      &:hover { opacity: 0.9; }
    }

    .out-btn, .detail-btn {
      background-color: transparent;
      border: 1px solid $border-color;
      color: $text-primary;
      &:hover { border-color: $main-color; color: $main-color; }
    }
  }
}

/* ==================================
   2. 持仓列表卡片
   ================================== */
.list-card {
  background-color: $card-bg;
  border-radius: 12px;
  border: 1px solid $border-color;
  padding: 20px 24px;
  min-height: 500px;
  display: flex;
  flex-direction: column;

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .list-title {
      font-size: 16px;
      font-weight: bold;
      color: $text-primary;
    }
  }

  /* --- 搜索栏 --- */
  .filter-bar {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 20px;
    background: rgba(255, 255, 255, 0.02);
    padding: 16px;
    border-radius: 8px;
    border: 1px solid #2a2a2a;

    .filter-item {
      display: flex;
      align-items: center;
      gap: 10px;

      .filter-label {
        font-size: 14px;
        color: #999;
      }
    }

    .filter-actions {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-left: auto;

      .search-btn {
        background-color: $main-color;
        border-color: $main-color;
        color: #000;
        font-weight: bold;
        &:hover { opacity: 0.9; }
      }

      .reset-btn {
        background: transparent;
        color: #ccc;
        border: 1px solid #444;
        &:hover {
          color: $main-color;
          border-color: $main-color;
        }
      }
    }
  }

  .table-content {
    flex: 1;

    .amount-text {
      font-family: DIN, monospace;
      font-size: 15px;
      font-weight: bold;
      &.text-gold { color: $main-color; }
    }

    .time-text {
      font-family: monospace;
      color: #aaa;
      font-size: 13px;
    }
  }
}

/* --- 深色组件深度覆盖 --- */
:deep(.dark-select) {
  .el-input__wrapper {
    background-color: #141414;
    box-shadow: 0 0 0 1px #333 inset;
    &:hover, &.is-focus { box-shadow: 0 0 0 1px $main-color inset; }
  }
  .el-input__inner { color: #fff; }
}

:deep(.dark-date-picker) {
  background-color: #141414 !important;
  box-shadow: 0 0 0 1px #333 inset !important;
  border: none;
  transition: all 0.3s;
  
  .el-range-input { color: #fff; background: transparent; }
  .el-range-separator { color: #999; }
  &:hover, &.is-active { box-shadow: 0 0 0 1px $main-color inset !important; }
}

:deep(.dark-table) {
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: #141414;
  --el-table-header-text-color: #ccc;
  --el-table-text-color: #eee;
  --el-table-row-hover-bg-color: #262626;
  --el-table-border-color: #333;
  
  &::before { display: none; }
  
  th.el-table__cell {
    font-weight: bold;
    border-bottom: 1px solid #333 !important;
    padding: 12px 0;
  }
  td.el-table__cell {
    border-bottom: 1px solid #2a2a2a !important;
    padding: 14px 0 !important;
  }
  .el-table__inner-wrapper::before { background-color: transparent; }
}

/* --- 分页器 --- */
.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  
  :deep(.dark-pagination) {
    --el-pagination-bg-color: #141414;
    --el-pagination-text-color: #ccc;
    --el-pagination-button-color: #ccc;
    --el-pagination-hover-color: #f8b932;

    .btn-prev, .btn-next, .el-pager li {
      background-color: #141414;
      border: 1px solid #333;
      border-radius: 4px;
      margin: 0 4px;
      &.is-active { background-color: $main-color; color: #000; border-color: $main-color; }
    }
  }
}

/* ==================================
   3. 弹窗样式
   ================================== */
.modal-form-body {
  padding: 10px 0 20px;

  .form-item {
    .label {
      font-size: 14px;
      color: $text-secondary;
      margin-bottom: 10px;
    }
  }

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

: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; } }

  .giant-input {
    .el-input__wrapper {
      background-color: #141414 !important;
      box-shadow: 0 0 0 1px #444 inset !important;
      height: 54px;
      border-radius: 8px;
      &:hover, &.is-focus { box-shadow: 0 0 0 1px $main-color inset !important; }
    }
    .el-input__inner { font-size: 24px; font-weight: bold; color: $main-color !important; 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>