<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { TableColumnsType } from 'ant-design-vue'
import { Tag as ATag, Table as ATable } from 'ant-design-vue'
import { useI18n } from "vue-i18n";
import { useRouter } from 'vue-router';
import { fetchRechargeHistory } from '@/service/api/auth';
import { useWindowSize } from '@vueuse/core';

const router = useRouter();
const handleBack = () => {
  router.push('/billing/billservice');
};

const { t } = useI18n();

const rechargeData = ref<Api.Recharge.RechargeRecord[]>([]);
const total = ref(0);

const { width } = useWindowSize();
const isMobile = computed(() => width.value < 768);

const formatDateTime = (dateTimeString: string) => {
  if (!dateTimeString) return '';
  const date = new Date(dateTimeString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};

const getRechargeData = async () => {
  try {
    const response = await fetchRechargeHistory({
      pageNum: 1,
      pageSize: 10
    });
    // console.log('API Response:', response);
    if (response?.data?.rows) {
      // console.log('Setting data:', response.data.rows);
      rechargeData.value = response.data.rows;
      total.value = response.data.total;
    }
  } catch (error) {
    // console.error('Failed to fetch recharge history:', error);
  }
};

onMounted(() => {
  getRechargeData();
});

const columns = computed<TableColumnsType>(() => [
  {
    title: t('page.Rechargehistory.topupdate'),
    dataIndex: 'createTime',
    key: 'createTime',
    responsive: ['md'],
    customRender: ({ text }) => text ? formatDateTime(text) : ''
  },
  {
    title: t('page.Rechargehistory.amount'),
    dataIndex: 'orderAmount',
    key: 'orderAmount',
    customRender: ({ text }: { text: string }) => {
      const formattedAmount = Number(text).toFixed(2);
      return `¥${formattedAmount}`;
    }
  },
  {
    title: t('page.Rechargehistory.type'),
    dataIndex: 'type',
    key: 'type',
    customRender: ({ text }: { text: number }) => {
      return h(ATag, {
        color: text === 1 ? 'blue' : 'green'
      }, {
        default: () => text === 1 ? t('page.Rechargehistory.rechargeType') : t('page.Rechargehistory.packageType')
      })
    }
  },
  {
    title: t('page.Rechargehistory.status'),
    dataIndex: 'status',
    key: 'status',
    customRender: ({ text }: { text: number }) => {
      return h(ATag, {
        color: text === 1 ? 'success' : 'warning'
      }, {
        default: () => text === 1 ? t('page.Rechargehistory.paid') : t('page.Rechargehistory.unpaid')
      })
    }
  }
]);
</script>

<template>
  <div class="p-4">
    <div class="text-lg font-bold mb-4 flex justify-between items-center">
      <span>{{ t('page.Rechargehistory.recharge') }}</span>
      <a-button @click="handleBack">
        {{ t('page.login.common.back') }}
      </a-button>
    </div>
    <div>
      <ATable
        :columns="columns"
        :data-source="rechargeData"
        :row-key="(record: Api.Recharge.RechargeRecord) => record.id"
        :pagination="{
          pageSize: 5,
          total: total,
          showTotal: (total: number) => `共 ${total} 条`,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: ['5', '10', '20', '50']
        }"
      >
        <template #expandedRowRender="{ record }">
          <div class="pl-4">
            <div v-if="isMobile" class="mb-2">
              <strong>{{ t('page.Rechargehistory.topupdate') }}:</strong>
              {{ formatDateTime(record.createTime) }}
            </div>
          </div>
        </template>
      </ATable>
    </div>
  </div>
</template>

<style scoped>
.p-4 {
  padding: 1rem;
}
.mb-4 {
  margin-bottom: 1rem;
}
.text-lg {
  font-size: 1.125rem;
}
.font-bold {
  font-weight: bold;
}
.pl-4 {
  padding-left: 1rem;
}
</style>
