<template>
  <div class="billing-orders-container">
    <n-card class="orders-card">
      <template #header>
        <div class="orders-header">
          <n-input
            v-model:value="filters.search"
            :placeholder="$t('Search orders...')"
            clearable
            :size="inputSize"
            class="search-input"
            @input="debouncedSearch"
          >
            <template #prefix>
              <i-lucide-search class="h-4 w-4" />
            </template>
          </n-input>
          <n-space :size="12">
            <n-button
              type="primary"
              :size="buttonSize"
              :loading="exporting"
              @click="exportToCsv"
              :block="isMobile"
            >
              <template #icon>
                <i-lucide-download class="h-4 w-4" />
              </template>
              {{ $t('Export') }}
            </n-button>
            <n-button
              :size="buttonSize"
              @click="resetAndFetch"
              :loading="initialLoading"
              :block="isMobile"
            >
              <template #icon>
                <i-lucide-refresh-cw class="h-4 w-4" />
              </template>
            </n-button>
          </n-space>
        </div>
      </template>

      <n-empty
        v-if="!initialLoading && orders.length === 0"
        :description="$t('No order records to display')"
        class="empty-state"
      >
        <template #icon>
          <i-lucide-file-text class="h-12 w-12 text-gray-400" />
        </template>
      </n-empty>

      <n-data-table
        v-else
        :columns="tableColumns"
        :data="orders"
        :loading="initialLoading"
        :pagination="false"
        :scroll-x="isMobile ? 1200 : undefined"
        :bordered="false"
        :single-line="false"
        class="orders-table"
        size="medium"
      />

      <div v-if="orders.length > 0" class="orders-footer">
        <div class="orders-info">
          {{ $t('Showing {count} orders, total {total}', { count: orders.length, total: totalCount }) }}
        </div>
        <n-button
          v-if="hasMoreToLoad"
          type="primary"
          :loading="loadingMore"
          :size="buttonSize"
          :block="isMobile"
          @click="loadMore"
        >
          {{ $t('Load More') }}
        </n-button>
      </div>
    </n-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, h, getCurrentInstance } from 'vue';
import { NCard, NInput, NButton, NSpace, NDataTable, NEmpty, NTag } from 'naive-ui';
import { createResource } from 'jingrow-ui';
import { unparse } from 'papaparse';

const instance = getCurrentInstance();
const $t = instance?.appContext.config.globalProperties.$t || ((key) => key);
const pageSize = 20;
const orders = ref([]);
const totalCount = ref(0);
const currentPage = ref(1);
const initialLoading = ref(true);
const loadingMore = ref(false);
const exporting = ref(false);
const windowWidth = ref(window.innerWidth);

const isMobile = computed(() => windowWidth.value <= 768);
const inputSize = computed(() => (isMobile.value ? 'medium' : 'medium'));
const buttonSize = computed(() => (isMobile.value ? 'medium' : 'medium'));

const filters = reactive({
  search: ''
});
    
// 计算是否还有更多数据可加载
const hasMoreToLoad = computed(() => {
  return orders.value.length < totalCount.value;
});

// 定义表格列
const tableColumns = computed(() => {
  const statusColumn = {
    title: $t('Status'),
    key: 'status',
    width: isMobile.value ? 100 : 120,
    render(row) {
      const statusProps = getStatusProps(row.status);
      return h(NTag, {
        type: statusProps.color === 'green' ? 'success' : 
              statusProps.color === 'orange' ? 'warning' : 
              statusProps.color === 'red' ? 'error' : 'info',
        size: isMobile.value ? 'small' : 'medium'
      }, { default: () => statusProps.label });
    }
  };

  const baseColumns = [
    {
      title: $t('Time'),
      key: 'creation',
      width: isMobile.value ? 140 : 160,
      ellipsis: { tooltip: true },
      render(row) {
        return formatDate(row.creation);
      }
    },
    {
      title: $t('Title'),
      key: 'title',
      width: isMobile.value ? 120 : 150,
      ellipsis: { tooltip: true },
      render(row) {
        return row.title || '-';
      }
    },
    {
      title: $t('Order ID'),
      key: 'order_id',
      width: isMobile.value ? 120 : 150,
      ellipsis: { tooltip: true },
      render(row) {
        return row.order_id || '-';
      }
    },
    {
      title: $t('Transaction ID'),
      key: 'trade_no',
      width: isMobile.value ? 120 : 150,
      ellipsis: { tooltip: true },
      render(row) {
        return row.trade_no || '-';
      }
    },
    {
      title: $t('Order Type'),
      key: 'order_type',
      width: isMobile.value ? 100 : 120,
      ellipsis: { tooltip: true },
      render(row) {
        return row.order_type || '-';
      }
    },
    {
      title: $t('Payment Method'),
      key: 'payment_method',
      width: isMobile.value ? 100 : 120,
      ellipsis: { tooltip: true },
      render(row) {
        return row.payment_method || '-';
      }
    },
    {
      title: $t('Description'),
      key: 'description',
      width: isMobile.value ? 150 : 200,
      ellipsis: { tooltip: true },
      render(row) {
        return row.description || '-';
      }
    },
    {
      title: $t('Amount'),
      key: 'total',
      width: isMobile.value ? 100 : 120,
      align: 'right',
      render(row) {
        return formatCurrency(row.total);
      }
    },
    statusColumn
  ];

  // 移动端隐藏部分列
  if (isMobile.value) {
    return baseColumns.filter(col => 
      ['creation', 'title', 'total', 'status'].includes(col.key)
    );
  }

  return baseColumns;
});
    
// 创建获取订单的资源
const ordersResource = createResource({
      url: 'jcloud.api.billing.get_orders',
      transform(response) {
        return {
          orders: response.orders || [],
          total: response.total || 0
        };
      },
      onSuccess(data) {
        // 更新总数
        totalCount.value = data.total;
        
        if (currentPage.value === 1) {
          // 第一页数据，替换现有数据
          orders.value = data.orders;
        } else {
          // 非第一页，追加数据
          orders.value = [...orders.value, ...data.orders];
        }
        
        // 更新加载状态
        initialLoading.value = false;
        loadingMore.value = false;
      },
  onError(error) {
    initialLoading.value = false;
    loadingMore.value = false;
  }
});

// 导出资源
const exportResource = createResource({
      url: 'jcloud.api.billing.get_orders',
  onSuccess(response) {
    const orders = response.orders || [];
    
    // 定义CSV字段
    const fields = [
      $t('Title'),
      $t('Order ID'),
      $t('Transaction ID'),
      $t('Order Type'),
      $t('Payment Method'),
      $t('Description'),
      $t('Amount'),
      $t('Status'),
      $t('Creation Time')
    ];
    
    // 准备数据
    const csvData = orders.map(order => [
      order.title || '',
      order.order_id || '',
      order.trade_no || '',
      order.order_type || '',
      order.payment_method || '',
      order.description || '',
      order.total || 0,
      order.status || '',
      order.creation || ''
    ]);
    
    // 添加表头
    csvData.unshift(fields);
    
    // 生成CSV
    let csv = unparse(csvData);
    
    // 添加BOM以支持中文
    csv = '\uFEFF' + csv;
    
    // 触发下载
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
    const today = new Date().toISOString().split('T')[0];
    const filename = `${$t('Order Records')}-${today}.csv`;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = filename;
    link.click();
    URL.revokeObjectURL(link.href);
    exporting.value = false;
  },
  onError(error) {
    exporting.value = false;
  }
});

// 方法：加载初始数据
function fetchOrders() {
      if (currentPage.value === 1) {
        initialLoading.value = true;
      } else {
        loadingMore.value = true;
      }
      
  ordersResource.submit({
    page: currentPage.value,
    page_size: pageSize,
    search: filters.search,
  });
}

// 方法：重置并获取第一页数据
function resetAndFetch() {
  currentPage.value = 1;
  fetchOrders();
}

// 方法：加载更多数据
function loadMore() {
  if (loadingMore.value) return;
  
  currentPage.value += 1;
  loadingMore.value = true;
  fetchOrders();
}

// 搜索防抖
let searchTimeout;
function debouncedSearch() {
  clearTimeout(searchTimeout);
  searchTimeout = setTimeout(() => {
    resetAndFetch();
  }, 300);
}

// 导出为CSV
function exportToCsv() {
  exporting.value = true;
  exportResource.submit({
    page: 1,
    page_size: 1000, // 设置较大的值获取更多数据用于导出
    search: filters.search,
  });
}

// 格式化金额
function formatCurrency(amount) {
  if (amount === undefined || amount === null) return '-';
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
  }).format(amount);
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '-';
  
  const date = new Date(dateString);
  if (isNaN(date.getTime())) return '-';
  
  // 格式化为 YYYY-MM-DD HH:MM 格式
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 获取状态样式
function getStatusProps(status) {
  const statusMap = {
    '待支付': { label: $t('Pending Payment'), color: 'orange' },
    '已支付': { label: $t('Paid'), color: 'green' },
    '交易成功': { label: $t('Transaction Successful'), color: 'green' },
    '已取消': { label: $t('Cancelled'), color: 'red' },
    '已退款': { label: $t('Refunded'), color: 'red' },
  };
  
  return statusMap[status] || { label: status || '', color: 'blue' };
}

function handleResize() {
  windowWidth.value = window.innerWidth;
}

// 生命周期钩子
onMounted(() => {
  handleResize();
  window.addEventListener('resize', handleResize);
  fetchOrders();
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.billing-orders-container {
  padding: 24px;
  width: 100%;
}

.orders-card {
  border-radius: 12px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
}

.orders-header {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-input {
  width: 100%;
  max-width: 300px;
}

.orders-footer {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding-top: 16px;
  margin-top: 16px;
  border-top: 1px solid var(--n-border-color);
}

.orders-info {
  font-size: 14px;
  color: var(--n-text-color-2);
}

.empty-state {
  padding: 60px 20px;
}

.orders-table {
  margin-top: 16px;
}

@media (min-width: 769px) {
  .orders-header {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }

  .orders-footer {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }

  .search-input {
    max-width: 300px;
  }
}

@media (max-width: 768px) {
  .billing-orders-container {
    padding: 16px;
  }

  .orders-header {
    gap: 12px;
  }

  .search-input {
    max-width: 100%;
  }
}
</style> 