<template>
  <div class="pc-withdrawal-record-container">
    <div class="record-wrapper">

      <div class="filter-card">
        <div class="filter-header">
          <div class="header-left">
            <div class="back-action" @click="goBack">
              <el-icon><ArrowLeft /></el-icon>
              <span class="back-text">{{ t('返回') }}</span>
            </div>

            <el-divider direction="vertical" class="header-divider" />

            <div class="title-line">
              <div class="decorate-bar bmc"></div>
              <span class="title-text">{{ t('提现记录') }}</span>
            </div>
          </div>
        </div>

        <div class="filter-body">
          <el-form :inline="true" :model="queryParams" class="search-form">
            <el-form-item :label="t('提现类型')">
              <el-select
                  v-model="queryParams.type"
                  class="compact-select"
                  @change="handleTypeChange"
              >
                <el-option
                    v-for="item in typeColumns"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item :label="t('日期区间')">
              <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  :start-placeholder="t('开始日期')"
                  :end-placeholder="t('结束日期')"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  class="compact-date-picker"
                  @change="handleQuery"
              />
            </el-form-item>

            <el-form-item class="action-items">
              <el-button type="primary" @click="handleQuery">
                <el-icon class="btn-icon"><Search /></el-icon>
                {{ t('立即查询') }}
              </el-button>
              <el-button @click="handleReset" class="reset-btn">
                <el-icon class="btn-icon"><RefreshRight /></el-icon>
                {{ t('重置全部') }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <div class="table-card">

        <div class="table-content">
          <el-table
              :data="tableData"
              class="compact-table"
              style="width: 100%"
              height="100%"
              :empty-text="t('没有发现相关记录')"
          >
            <el-table-column :label="t('提现金额')" min-width="130" align="left">
              <template #default="scope">
                <span class="val-text">{{ scope.row.amount }}</span>
                <span class="currency">{{ scope.row.currency || (queryParams.type === 'rmb' ? 'CNY' : 'USDT') }}</span>
              </template>
            </el-table-column>

            <el-table-column v-if="queryParams.type === 'crypto_coin'" :label="t('汇率')" min-width="90" align="center">
              <template #default="scope">
                <span v-if="scope.row.exchange_rate" class="highlight-text">{{ scope.row.exchange_rate }}</span>
                <span v-else class="empty-text">--</span>
              </template>
            </el-table-column>

            <el-table-column :label="t('手续费')" min-width="110" align="center">
              <template #default="scope">
                <span class="fee-text">
                  {{ queryParams.type === 'crypto_coin' ? scope.row.service_charge : scope.row.fee }}
                </span>
                <span class="currency">{{ scope.row.currency || (queryParams.type === 'rmb' ? 'CNY' : 'USDT') }}</span>
              </template>
            </el-table-column>

            <el-table-column v-if="queryParams.type === 'crypto_coin'" :label="t('提现地址')" min-width="200" show-overflow-tooltip align="center">
              <template #default="scope">
                <span class="address-text">{{ scope.row.address || '--' }}</span>
              </template>
            </el-table-column>

            <el-table-column v-if="queryParams.type === 'rmb'" :label="t('渠道')" min-width="120" align="center">
              <template #default="scope">
                <span>{{ scope.row.channel_text || scope.row.bank_name || '--' }}</span>
              </template>
            </el-table-column>

            <el-table-column v-if="queryParams.type === 'rmb'" :label="t('收款人')" min-width="120" align="center">
              <template #default="scope">
                <span>{{ scope.row.account || '--' }}</span>
              </template>
            </el-table-column>

            <el-table-column v-if="queryParams.type === 'rmb'" :label="t('收款账号')" min-width="180" show-overflow-tooltip align="center">
              <template #default="scope">
                <span class="address-text">{{ scope.row.card_no || '--' }}</span>
              </template>
            </el-table-column>

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

                <el-tooltip
                    v-if="isFailedStatus(scope.row.status) && (scope.row.admin_note || scope.row.remark)"
                    class="box-item"
                    effect="dark"
                    :content="scope.row.admin_note || scope.row.remark"
                    placement="top"
                >
                  <el-icon class="reject-icon" color="#f56c6c"><Warning /></el-icon>
                </el-tooltip>
              </template>
            </el-table-column>

            <el-table-column prop="created_at" :label="t('申请时间')" min-width="150" align="right" />

            <el-table-column :label="t('操作')" width="100" align="center" fixed="right">
              <template #default="scope">
                <el-button v-if="scope.row.status === 0 && scope.is_locked != 1" type="primary" link size="small" @click="handleCancel(scope.row)">
                  {{ t('撤销申请') }}
                </el-button>
              </template>
            </el-table-column>

            <template #empty>
              <el-empty :description="t('没有发现相关记录')" class="compact-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, 100]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              class="compact-pagination"
          />
        </div>
      </div>

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

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { Search, RefreshRight, Warning, ArrowLeft } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
// 引入 walletWithdrawCancel 接口
import { getWithdrawHistory, walletWithdrawCancel } from '@/request/api.js'
import { useRouter } from "vue-router"

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

// 状态与数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const dateRange = ref(null)

// 提现类型选项
const typeColumns = computed(() => [
  { label: t('加密货币提现'), value: 'crypto_coin' },
  { label: t('RMB提现'), value: 'rmb' }
])

// 查询参数
const queryParams = reactive({
  type: 'rmb',
  page: 1,
  limit: 20,
  start_time: '',
  end_time: ''
})

// 初始化加载
onMounted(() => {
  fetchData()
})

// 获取列表数据
const fetchData = async () => {
  loading.value = true

  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 = ''
  }

  try {
    const res = await getWithdrawHistory(queryParams)
    if (res.code === 1) {
      tableData.value = res.data.list || []
      total.value = res.data.count || res.data.list.length
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (err) {
    console.error(err)
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 切换提现类型时重置分页并查询
const handleTypeChange = () => {
  queryParams.page = 1
  fetchData()
}

// 触发查询
const handleQuery = () => {
  queryParams.page = 1
  fetchData()
}

// 重置查询
const handleReset = () => {
  queryParams.type = 'crypto_coin'
  dateRange.value = null
  queryParams.start_time = ''
  queryParams.end_time = ''
  handleQuery()
}

// 分页变化
const handleSizeChange = (val) => {
  queryParams.limit = val
  fetchData()
}

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

// --- 状态枚举工具函数 ---
const getStatusText = (status) => {
  if (queryParams.type === 'crypto_coin') {
    // 加密货币状态：0申请中 1成功 2失败 3已撤回
    const map = { 0: t('申请中'), 1: t('成功'), 2: t('失败'), 3: t('已撤回') }
    return map[status] || t('未知')
  } else {
    // rmb状态：多加一个6已撤回
    const map = { 0: t('待处理'), 1: t('处理中'), 2: t('成功'), 3: t('失败'), 6: t('已撤回') }
    return map[status] || t('未知')
  }
}

const getStatusTagType = (status) => {
  if (queryParams.type === 'crypto_coin') {
    const map = { 0: 'warning', 1: 'success', 2: 'danger', 3: 'info' }
    return map[status] || 'info'
  } else {
    // rmb
    const map = { 0: 'warning', 1: 'primary', 2: 'success', 3: 'danger', 6: 'info' }
    return map[status] || 'info'
  }
}

const isFailedStatus = (status) => {
  return (queryParams.type === 'crypto_coin' && status === 2) || (queryParams.type === 'rmb' && status === 3)
}

// --- 新增：撤销申请功能 ---
const handleCancel = (row) => {
  ElMessageBox.confirm(
      t('确定要撤销该提现申请吗？'),
      t('提示'),
      {
        confirmButtonText: t('确定'),
        cancelButtonText: t('取消'),
        type: 'warning',
      }
  ).then(async () => {
    try {
      // type参数：1usdt订单；2人民币订单
      const orderType = queryParams.type === 'crypto_coin' ? 1 : 2
      const res = await walletWithdrawCancel({
        id: row.id,
        type: orderType
      })
      if (res.code === 1) {
        fetchData() // 刷新列表
      } else {
        // ElMessage.error(res.msg || t('撤销失败'))
      }
    } catch (err) {
      console.error(err)
      ElMessage.error(t('网络错误'))
    }
  }).catch(() => {})
}

const goBack = () => {
  router.back()
}
</script>

<style scoped lang="scss">
$main-color: #f8b932;
$card-bg: var(--el-bg-color-overlay);

.pc-withdrawal-record-container {
  /* 声明顶级盒子为容器查询基准点 */
  container-type: inline-size;
  container-name: withdrawal-record;

  height: 100%;
  padding: 6px 8px; /* 整体外边距极限压缩 */
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  @container withdrawal-record (max-width: 800px) { padding: 4px; }
  @container withdrawal-record (max-width: 550px) { padding: 2px; }

  .record-wrapper {
    display: flex;
    flex-direction: column;
    //gap: 6px; /* 卡片间距压缩 */
    width: 100%;
    flex: 1;
    min-height: 0;
    overflow: hidden;
  }

  /* === 1. 顶部筛选卡片 === */
  .filter-card {
    flex-shrink: 0;
    background-color: $card-bg;
    //border-radius: 6px;
    padding: 8px 14px; /* 内边距压缩 */
    border: 1px solid var(--el-border-color-light);

    @container withdrawal-record (max-width: 550px) { padding: 6px 8px; }

    .filter-header {
      margin-bottom: 8px;
      .header-left {
        display: flex; align-items: center;

        .back-action {
          display: flex; align-items: center; cursor: pointer; color: var(--el-text-color-regular); font-size: 14px; transition: color 0.2s;
          &:hover { color: $main-color; }
          .el-icon { margin-right: 2px; }
        }

        .header-divider { margin: 0 10px; height: 14px; border-left: 1px solid var(--el-border-color-darker); }

        .title-line {
          display: flex; align-items: center;
          .decorate-bar { width: 3px; height: 14px; border-radius: 2px; margin-right: 6px; background-color: $main-color; }
          .title-text { font-size: 14px; font-weight: bold; color: var(--el-text-color-primary); }
        }
      }
    }

    /* === 筛选表单深度压缩 === */
    .filter-body {
      .search-form { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin-bottom: 0; }

      :deep(.el-form-item) { margin-right: 0; margin-bottom: 0; display: flex; align-items: center; }
      //:deep(.el-form-item__label) { line-height: 26px !important; height: 26px !important; padding-right: 6px; font-size: 14px; margin-bottom: 0; color: var(--el-text-color-regular); }

      /* 下拉与日期选择器紧凑化 */
      .compact-select { width: 140px; }
      //:deep(.el-select .el-select__wrapper) { min-height: 26px !important; height: 26px !important; padding: 0 6px; font-size: 14px; }
      //
      //:deep(.el-date-editor) { height: 26px; padding: 0 6px; max-width: 220px; width: 100%; }
      //:deep(.el-range-separator) { line-height: 24px; font-size: 14px; padding: 0 2px; color: var(--el-text-color-secondary); }
      //:deep(.el-range-input) { font-size: 14px; color: var(--el-text-color-primary); }
      //:deep(.el-input__icon) { line-height: 26px; }

      .action-items {
        display: flex; gap: 6px;
        .reset-btn { &:hover { color: $main-color; border-color: $main-color; background-color: var(--el-color-primary-light-9); } margin-left: 10px}
        //.btn-icon { margin-right: 2px; font-size: 14px; }
      }

      /* 小屏表单换行处理 */
      @container withdrawal-record (max-width: 550px) {
        .search-form { flex-direction: column; align-items: stretch; gap: 6px; }
        .compact-select { width: 100%; }
        //:deep(.el-date-editor) { max-width: 100%; }
        //.action-items {
        //  width: 100%;
        //  :deep(.el-form-item__content) { display: flex; width: 100%; gap: 6px; }
        //  .el-button { flex: 1; margin: 0; }
        //}
      }
    }
  }

  /* === 2. 表格卡片 === */
  .table-card {
    flex: 1;
    min-height: 0;
    background-color: $card-bg;
    //border-radius: 6px;
    padding: 6px 8px;
    border: 1px solid var(--el-border-color-light);
    display: flex;
    flex-direction: column;
    overflow: hidden;

    @container withdrawal-record (max-width: 800px) { padding: 4px 6px; }
    @container withdrawal-record (max-width: 550px) { padding: 2px 4px; }

    /* ★ 终极修复：绝对定位表格容器 */
    .table-content {
      flex: 1;
      min-height: 0;
      position: relative;
      overflow: hidden;
    }

    .compact-table {
      position: absolute;
      top: 0; left: 0; right: 0; bottom: 0;

      @container withdrawal-record (max-width: 800px) { font-size: 14px; }

      /* 穿透压缩 Padding */
      //:deep(th.el-table__cell) { font-weight: bold; border-bottom: 1px solid var(--el-border-color-lighter) !important; padding: 4px 0; font-size: 14px; background-color: var(--el-fill-color-light); }
      //:deep(td.el-table__cell) { border-bottom: 1px solid var(--el-border-color-lighter) !important; padding: 4px 0 !important; }
      //:deep(.cell) { padding: 0 6px; line-height: 1.3; }
      //:deep(.compact-empty .el-empty__description p) { color: var(--el-text-color-secondary); font-size: 14px; }
    }

    /* 业务排版细节字号缩小 */
    .order-no { color: var(--el-text-color-regular); font-size: 14px; }
    .val-text { font-weight: bold; color: var(--el-text-color-primary); font-size: 14px; }
    .highlight-text { color: $main-color; font-weight: bold;  font-size: 13px; }
    .fee-text { color: var(--el-text-color-regular);  font-size: 14px; }
    .currency { font-size: 10px; color: var(--el-text-color-secondary); margin-left: 2px; }
    .address-text { font-family: monospace; font-size: 14px; color: var(--el-text-color-regular); }
    .bank-info { line-height: 1.4; font-size: 14px; }
    .empty-text { color: var(--el-text-color-placeholder); }

    /* 状态与图标压缩 */
    .status-tag { height: 18px; padding: 0 4px; line-height: 16px; font-size: 10px; border-radius: 2px; }
    .reject-icon { margin-left: 4px; cursor: pointer; vertical-align: -2px; font-size: 14px; }

    /* === 紧凑级暗色分页器 === */
    .pagination-wrapper {
      margin-top: 8px; display: flex; justify-content: flex-end; flex-shrink: 0;
      @container withdrawal-record (max-width: 550px) { margin-top: 6px; justify-content: center; }

      .compact-pagination {
        display: flex; align-items: center; flex-wrap: wrap; justify-content: center; gap: 4px;
        //
        //:deep(.el-pagination__total) { margin-right: 4px; font-size: 14px; height: 24px; line-height: 24px; color: var(--el-text-color-secondary); }
        //:deep(.el-pagination__sizes) {
        //  margin-right: 4px;
        //  .el-select .el-select__wrapper { min-height: 24px !important; height: 24px !important; padding: 0 6px; font-size: 14px; line-height: 24px; }
        //}
        //
        //:deep(.btn-prev), :deep(.btn-next) { min-width: 24px; height: 24px; padding: 0 4px; border-radius: 4px; }
        //:deep(.el-pager li) {
        //  min-width: 24px; height: 24px; line-height: 24px; font-size: 14px; margin: 0 2px; border-radius: 4px;
        //}
        //
        //:deep(.el-pagination__jump) {
        //  margin-left: 4px; font-size: 14px; height: 24px; line-height: 24px; color: var(--el-text-color-secondary);
        //  .el-input {
        //    width: 36px; height: 24px;
        //    .el-input__wrapper { height: 24px; padding: 0 2px; .el-input__inner { font-size: 14px; text-align: center; } }
        //  }
        //}
      }
    }
  }
}
</style>
