<template>
  <view class="list-page-container">
    <!-- 顶部搜索 -->
    <view class="search-header">
      <view class="search-row">
        <uv-input
          placeholder="请输入项目名称"
          v-model="queryParams.projectName"
          prefixIcon="search"
          prefixIconStyle="color: #999; font-size: 32rpx;"
          clearable
          shape="circle"
          customStyle="background-color: #f5f7fa; border: none;"
          @confirm="onSearch"
        ></uv-input>
      </view>
    </view>

    <!-- 列表区域 -->
    <view class="list-container">
      <scroll-view
        scroll-y
        class="scroll-list"
        :scroll-top="scrollTopValue"
        scroll-with-animation
        refresher-enabled
        :refresher-triggered="isTriggered"
        @refresherrefresh="onRefresh"
        @scroll="onScroll"
        @scrolltolower="loadMore"
        :show-scrollbar="false"
      >
        <uv-empty v-if="!list.length && loadStatus !== 'loading'" mode="list"></uv-empty>

        <view
          class="common-list-card"
          v-for="item in list"
          :key="item.id"
          @click="toDetail(item.id)"
        >
          <view class="card-header">
            <text class="title">编号：{{ item.allotNo || '-' }}</text>
          </view>
          <view class="card-body">
            <view class="info-item">
              <text class="label">项目名称：</text>
              <text class="value text-ellipsis">{{ item.projectName || '-' }}</text>
            </view>
            <view class="info-item">
              <text class="label">项目负责人：</text>
              <text class="value">{{ item.projectIncharge || '-' }}</text>
            </view>
            <view class="info-item">
              <text class="label">入账金额(元)：</text>
              <text class="value number-font">{{ amountUnitFormatter(item.amount) }}</text>
            </view>
            <view class="info-item">
              <text class="label">入账时间：</text>
              <text class="value">{{ item.applyTime ? formatDate(item.applyTime, 'YYYY-MM-DD') : '-' }}</text>
            </view>
          </view>
        </view>

        <uv-load-more
          v-if="list.length > 0 || loadStatus === 'loading'"
          :status="loadStatus"
          @loadmore="loadMore"
        ></uv-load-more>
        
        <!-- 底部安全距离 -->
        <view class="safe-bottom-space"></view>
      </scroll-view>

      <uv-back-top
        :scrollTop="currentScrollTop"
        :bottom="100"
        :right="30"
        @click="backToTop"
      ></uv-back-top>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { debounce } from 'lodash-es';
import { useClaimApi } from '@/api/fund/index';
import { onRouterPush } from '@/utils/router';
import { formatDate } from '@/utils/date';
import { DEFAULT_PAGE_SIZE } from '@/constants/index';

const claimApi = useClaimApi();

const queryParams = ref({
  projectName: '',
  pageNum: 1,
  pageSize: DEFAULT_PAGE_SIZE
});

const list = ref<any[]>([]);
const loadStatus = ref<'loadmore' | 'loading' | 'nomore'>('loadmore');
const isTriggered = ref(false);
const scrollTopValue = ref(0);
const currentScrollTop = ref(0);

// Helper function to format amount to 2 decimal places if applicable
const amountUnitFormatter = (val: any) => {
  if (val === null || val === undefined) return '0.00';
  const num = Number(val);
  return isNaN(num) ? '0.00' : num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

const fetchListData = async (reset = false) => {
  if (reset) {
    queryParams.value.pageNum = 1;
  }
  loadStatus.value = 'loading';

  try {
    const res: any = await claimApi.getRecordList(queryParams.value);
    
    if (res.code == 200) {
      const records = res.data?.list || res.list || [];
      if (reset) {
        list.value = records;
      } else {
        list.value = [...list.value, ...records];
      }
      
      if (records.length < queryParams.value.pageSize) {
        loadStatus.value = 'nomore';
      } else {
        loadStatus.value = 'loadmore';
        queryParams.value.pageNum += 1;
      }
    } else {
      loadStatus.value = 'nomore';
    }
  } catch (error) {
    console.error('Fetch error:', error);
    loadStatus.value = 'nomore';
  } finally {
    if (reset) {
      isTriggered.value = false;
    }
  }
};

const onSearch = () => {
  fetchListData(true);
};

const debouncedSearch = debounce(() => {
  fetchListData(true);
}, 500);

watch(() => queryParams.value.projectName, () => {
  debouncedSearch();
});

const onRefresh = async () => {
  isTriggered.value = true;
  await fetchListData(true);
};

const loadMore = () => {
  if (loadStatus.value !== 'loadmore') return;
  fetchListData(false);
};

const onScroll = (e: any) => {
  currentScrollTop.value = e.detail.scrollTop;
};

const backToTop = () => {
  scrollTopValue.value = currentScrollTop.value;
  nextTick(() => {
    scrollTopValue.value = 0;
  });
};

const toDetail = (id: number) => {
  onRouterPush(`/pages/fund/claim-records/detail?id=${id}`);
};

onLoad(() => {
  fetchListData(true);
});
</script>

<style lang="scss" scoped>
.list-page-container {
  height: calc(100vh - var(--window-top));
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  box-sizing: border-box;
}

.search-header {
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
  position: sticky;
  top: 0;
  z-index: 99;
}

.list-container {
  padding: 30rpx;
  flex: 1;
  overflow: hidden;
  box-sizing: border-box;
}

.scroll-list {
  flex: 1;
  height: 100%;
}

.common-list-card {
  .card-body {
    .info-item {
      display: flex;
      font-size: 28rpx;
      margin-bottom: 12rpx;
      line-height: 1.5;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        color: #666;
        width: 200rpx;
        flex-shrink: 0;
      }
      .value {
        color: #333;
        flex: 1;
        word-break: break-all;
      }
    }
  }
}

.number-font {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  color: #1c9bfd !important;
  font-weight: 500;
}

.text-ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.safe-bottom-space {
  height: calc(80rpx + env(safe-area-inset-bottom));
  width: 100%;
}
</style>
