<template>
  <view class="project-list">
    <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 用于查无数据时的展示 -->
      <uv-empty v-if="!verticalList.length && loadStatus !== 'loading'" mode="list"></uv-empty>

      <view 
        class="common-list-card" 
        v-for="item in verticalList" 
        :key="item.id" 
        @click="onRowClick(item)"
      >
        <view class="card-header">
          <text class="title">{{ item.projectName || item.name || '未命名' }}</text>
          <text class="status-tag" :class="'status-' + item.projectStatus">{{ getStatusName(item.projectStatus) }}</text>
        </view>
        <view class="card-body">
          <view class="info-item">
            <text class="label">立项日期：</text>
            <view class="value" style="display: flex; justify-content: space-between;">
              <text>{{ formatDate(item.approvalDate || item.setupDate || item.date) }}</text>
              <text style="color: #585858;">{{ item.projectLeaderName || item.managerName || item.manager || '-' }}</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 加载更多 -->
      <uv-load-more v-if="verticalList.length > 0 || loadStatus === 'loading'" :status="loadStatus" @loadmore="loadMore"></uv-load-more>
    </scroll-view>

    <!-- 返回顶部按钮 -->
    <uv-back-top 
      :scrollTop="currentScrollTop" 
      :bottom="100" 
      :right="30"
      @click="backToTop"
    ></uv-back-top>
  </view>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, nextTick } from 'vue';
import { storeToRefs } from 'pinia';
import { debounce } from 'lodash-es';
import { useProjectStore } from '@/store/modules/project';
import { formatDate } from '@/utils/date';
import { projectStatusOptions } from '@/constants/index';

const props = defineProps({
  queryParams: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['goDetail']);
const projectStore = useProjectStore();
const { verticalList, verticalPagination, fetchVerticalLoading } = storeToRefs(projectStore);

const loadStatus = ref('loadmore'); // loadmore, loading, nomore

// 滚动距离状态
const scrollTopValue = ref(0);
const currentScrollTop = ref(0); // 监听当前滚动的准确高度用于渲染显隐

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

const backToTop = () => {
  // scroll-view 需要这种 hack 方式才能完美由非0回滚到0
  scrollTopValue.value = currentScrollTop.value;
  nextTick(() => {
    scrollTopValue.value = 0;
  });
};

// ----------------- 下拉刷新功能 -----------------
const isTriggered = ref(false);

const onRefresh = async () => {
  isTriggered.value = true;
  // fetchData 内部会重置页码并重新请求数据
  await fetchData(true);
  isTriggered.value = false;
};

const getStatusName = (code: string) => {
  const item = projectStatusOptions.find(opt => opt.dictValue === code);
  return item ? item.dictLabel : code || '未知状态';
};

const fetchData = async (reset = false) => {
  loadStatus.value = 'loading';
  
  const { success, rows, total } = await projectStore.fetchVerticalProjects(props.queryParams, reset);
  
  if (success) {
    if (verticalList.value.length >= total || rows.length < verticalPagination.value.pageSize) {
      loadStatus.value = 'nomore';
    } else {
      loadStatus.value = 'loadmore';
    }
  } else {
    loadStatus.value = 'nomore';
  }
};

const loadMore = async () => {
  if (loadStatus.value === 'nomore' || fetchVerticalLoading.value) return;
  
  loadStatus.value = 'loading';
  const { success, rows, total } = await projectStore.loadMoreVerticalProjects(props.queryParams);
  
  if (success) {
    if (verticalList.value.length >= total || rows.length < verticalPagination.value.pageSize) {
      loadStatus.value = 'nomore';
    } else {
      loadStatus.value = 'loadmore';
    }
  } else {
    loadStatus.value = 'nomore';
  }
};

const debouncedFetchData = debounce(() => {
  fetchData(true);
}, 500);

watch(() => props.queryParams, () => {
  debouncedFetchData();
}, { deep: true });

onMounted(() => {
  fetchData(true);
});

const onRowClick = (item: any) => {
  emit('goDetail', { ...item, _type: 'vertical' });
};
</script>

<style lang="scss" scoped>
.project-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-list {
  flex: 1;
  height: 100%;
}
</style>
