<template>
  <div class="pc-recharge-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" placeholder="请选择充值类型" style="width: 160px;" @change="handleQuery">
                <el-option
                    v-for="option in types"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                />
              </el-select>
              </el-form-item>

            <el-form-item :label="t('日期区间')">
              <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  :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">{{ parseFloat(scope.row.amount || 0) }}</span>
                <!-- 兼容：RMB 数据缺少 coin 的情况 -->
                <span class="currency">{{ scope.row.coin || (queryParams.type === 'rmb' ? 'RMB' : '') }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="status" :label="t('状态')" width="140" align="center">
              <template #default="scope">
                <div style="display: flex; align-items: center; justify-content: center;">
                  <el-tag v-if="scope.row.status === 0" type="info" effect="dark" class="status-tag">
                    <span v-if="scope.row.channel === 'rgcz'">{{ t('待人工处理') }}</span>
                    <span v-else>{{ t('待处理') }}</span>
                  </el-tag>
                  <el-tag v-else-if="scope.row.status === 1" type="warning" effect="dark" class="status-tag">{{ t('处理中') }}</el-tag>
                  <el-tag v-else-if="scope.row.status === 2" type="success" effect="dark" class="status-tag">{{ t('成功') }}</el-tag>
                  <el-tag v-else-if="scope.row.status === 3" type="danger" effect="dark" class="status-tag">
                    <span v-if="scope.row.channel === 'rgcz'">{{ t('审核驳回') }}</span>
                    <span v-else>{{ t('失败') }}</span>
                  </el-tag>
                  <el-tag v-else-if="scope.row.status === 4" type="info" effect="dark" class="status-tag">{{ t('待用户提交凭证') }}</el-tag>
                  <el-tag v-else-if="scope.row.status === 5" type="danger" effect="dark" class="status-tag">{{ t('待审核') }}</el-tag>
                  <el-tag v-else type="info" class="status-tag">{{ t('未知') }}</el-tag>

                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    :content="scope.row.remark"
                    placement="top"
                  >
                    <el-icon v-if="scope.row.status === 3 && scope.row.remark" style="margin-left: 10px;" size="22"><WarningFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>

            <el-table-column :label="t('支付凭证')" width="90" align="center">
              <template #default="scope">
                <el-image
                    v-if="scope.row.image"
                    class="voucher-img"
                    :src="scope.row.image"
                    :preview-src-list="[scope.row.image]"
                    preview-teleported
                    fit="cover"
                />
                <span v-else class="empty-text">--</span>
              </template>
            </el-table-column>

            <el-table-column :label="t('实际到账')" min-width="130" align="right">
              <template #default="scope">
                <!-- 兼容：RMB 数据缺少 actual_received 的情况，直接取 amount -->
                <span class="actual-amount">+{{ parseFloat(scope.row.actual_received || scope.row.amount || 0) }}</span>
                <!-- 兼容：RMB 的币种单位 -->
                <span class="currency">{{ queryParams.type === 'rmb' ? 'RMB' : $currency }}</span>
              </template>
            </el-table-column>

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

            <!-- 兼容：RMB 数据使用 bank_name / channel，根据类型动态切换表头 Label -->
            <el-table-column :label="queryParams.type === 'rmb' ? t('充值渠道') : t('网络类型')" min-width="100">
              <template #default="scope">
                <el-tag  type="info" effect="plain" class="net-tag">{{ scope.row.bank_name || scope.row.channel_text || scope.row.net || '--' }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="from_address" :label="t('来源地址')" min-width="180" show-overflow-tooltip v-if="queryParams.type !== 'rmb'">
              <template #default="scope">
                <span class="address-text">{{ scope.row.from_address || '--' }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="created_at" :label="t('创建时间')" min-width="150">
              <template #default="scope">
                <span class="time-text">{{ scope.row.created_at }}</span>
              </template>
            </el-table-column>

            <!-- 新增操作列 -->
            <el-table-column :label="t('操作')" min-width="100" fixed="right" align="center">
              <template #default="scope">
                <el-button
                    v-if="queryParams.type === 'rmb' && scope.row.pay_data && scope.row.status === 4"
                    type="primary"
                    size="small"
                    link
                    @click="openUploadModal(scope.row)"
                >
                  {{ t('上传凭证') }}
                </el-button>
                <span v-else class="empty-text">--</span>
              </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>

    <!-- 上传凭证确认弹窗 -->
    <el-dialog
        v-model="uploadVisible"
        :title="t('充值确认')"
        width="400px"
        destroy-on-close
        class="recharge-upload-dialog"
    >
      <div class="info-container" v-if="payDataRef">
        <div class="info-item">
          <span class="label">{{ t('充值类型') }}</span>
          <span class="value" v-if="currentItem && currentItem.payment_type">
            {{ paymentTypeText[Number(currentItem.payment_type) - 1] }}
          </span>
        </div>
        <div class="info-item">
          <span class="label">{{ t('收款人姓名') }}</span>
          <span class="value">{{ payDataRef.payName }}</span>
        </div>
        <div class="info-item">
          <span class="label">{{ t('收款账号') }}</span>
          <span class="value">{{ payDataRef.payAccount }}</span>
        </div>

         <div class="info-item" v-if="currentItem.payment_type == '3' && payDataRef.bankName">
          <span class="label">{{ t('开户行') }}</span>
          <span class="value">{{ payDataRef.bankName }}</span>
        </div>

        <div class="qr-wrapper" v-if="payDataRef.payQrCode">
          <el-image class="qr-code" :src="payDataRef.payQrCode" fit="contain" />
          <span class="qr-tip">{{ t('收款码') }}</span>
        </div>

        <div class="upload-wrapper">
          
          <CUploadImage
           @change="changeImg"
              ref="CUploadImageRef"
          />
          <span class="qr-tip">{{ t('上传支付凭证') }}</span>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadVisible = false">{{ t('取消') }}</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleConfirmUpload">
            {{ t('提交') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { Search, RefreshRight, ArrowLeft, Plus, WarningFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getRecharge } from '@/request/api.js'
import { apiUrl } from "@/request" // 引入基础 API 地址
import { useRouter } from "vue-router"
import CUploadImage from '@/components/CUploadImage/index.vue'

const router = useRouter()
// 导出 locale 用于请求头
const { t, locale } = useI18n()

// 状态与数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const dateRange = ref(null)
const types = reactive([
  { label: t('RMB充值'), value: 'rmb' },
  { label: t('加密货币充值'), value: 'crypto_coin' }
])

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

// === 上传凭证弹窗相关状态 ===
const uploadVisible = ref(false)
const submitLoading = ref(false)
const currentItem = ref({})
const payDataRef = ref(null)
const uploadParams = reactive({
  id: '',
  image: ''
})
const paymentTypeText = ref(['微信', '支付宝', '银行卡'])

// 初始化加载
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 getRecharge(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 handleQuery = () => {
  queryParams.page = 1
  fetchData()
}

// 重置查询
const handleReset = () => {
  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 goBack = () => {
  router.back()
}

// === 上传凭证功能逻辑 ===
const openUploadModal = (row) => {
  currentItem.value = row
  uploadParams.id = row.id
  uploadParams.image = ''
  try {
    payDataRef.value = JSON.parse(row.pay_data)
  } catch (e) {
    payDataRef.value = {}
  }
  uploadVisible.value = true
}

const handleUploadSuccess = (res, file) => {
  // 适配 PC 端 el-upload，假设后端直接返回 url；若结构不同需对应修改
  uploadParams.image = res.data?.url || res.url || URL.createObjectURL(file.raw)
}

const handleConfirmUpload = async () => {
  if (!uploadParams.image) {
    ElMessage.warning(t('请上传支付凭证'))
    return
  }
  submitLoading.value = true
  try {
    const token = localStorage.getItem('token') || ''
    // 照抄 APP 端的接口提交逻辑
    const response = await fetch((apiUrl || '') + 'wallet/submitImage', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
        'lang': locale.value
      },
      body: JSON.stringify(uploadParams)
    })
    const res = await response.json()
    if (res.code === 0) {
      ElMessage.success(res.msg || t('提交成功'))
      uploadVisible.value = false
      fetchData() // 刷新列表
    } else {
      ElMessage.error(res.msg || t('提交失败'))
    }
  } catch (err) {
    ElMessage.error(t('网络错误'))
  } finally {
    submitLoading.value = false
  }
}

const changeImg = (e) => {
  uploadParams.image = Array.isArray(e) ? e[0] : e;
};
</script>

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

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

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

  @container recharge-record (max-width: 800px) { padding: 4px; }
  @container recharge-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 recharge-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); }
      //
      ///* 日期选择器紧凑化 */
      //: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 recharge-record (max-width: 550px) {
        .search-form { flex-direction: column; align-items: stretch; gap: 6px; }
        //: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 recharge-record (max-width: 800px) { padding: 4px 6px; }
    @container recharge-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;
      font-size: 14px;

      @container recharge-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; }
    }

    /* 业务排版细节字号缩小 */
    .val-text { font-weight: bold; color: var(--el-text-color-primary); font-family: DIN, monospace; font-size: 14px; }
    .actual-amount { font-size: 14px; font-weight: bold; color: var(--el-color-success);  }
    .currency { font-size: 10px; color: var(--el-text-color-secondary); margin-left: 2px; }
    .rate-text {  color: var(--el-text-color-regular); }
    .address-text { font-family: monospace; font-size: 14px; color: var(--el-text-color-regular); }
    .time-text { color: var(--el-text-color-secondary); 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; }

    /* 凭证图片极限压缩 */
    .voucher-img {
      width: 50px;
      height: 50px;
      border-radius: 2px;
      border: 1px solid var(--el-border-color-lighter);
      cursor: zoom-in;
      vertical-align: middle;
      transition: opacity 0.2s;
      &:hover { opacity: 0.8; }
    }

    /* === 紧凑级暗色分页器 === */
    .pagination-wrapper {
      margin-top: 8px; display: flex; justify-content: flex-end; flex-shrink: 0;
      @container recharge-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; } }
        //  }
        //}
      }
    }
  }
}

/* 上传凭证对话框特有样式 */
.recharge-upload-dialog {
  .info-container {
    background-color: var(--el-fill-color-light);
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 20px;
  }
  
  .info-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    font-size: 14px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .label {
      color: var(--el-text-color-secondary);
    }
    
    .value {
      color: var(--el-text-color-primary);
      font-weight: 600;
    }
  }

  .qr-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 20px;
    
    .qr-code {
      width: 160px;
      height: 160px;
      border-radius: 4px;
      border: 1px solid var(--el-border-color-lighter);
    }
    
    .qr-tip {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-top: 8px;
    }
  }

  .upload-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 20px;
    
    .voucher-uploader {
      :deep(.el-upload) {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
        width: 120px;
        height: 120px;
        display: flex;
        justify-content: center;
        align-items: center;
        
        &:hover {
          border-color: var(--el-color-primary);
        }
      }
      
      .upload-icon {
        font-size: 28px;
        color: #8c939d;
      }
      
      .uploaded-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .qr-tip {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-top: 8px;
    }
  }
}
</style>