<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="!spontaneityList.length && loadStatus !== 'loading'" mode="list"></uv-empty>

      <view 
        class="common-list-card" 
        v-for="item in spontaneityList" 
        :key="item.id" 
        @click="onRowClick(item)"
      >
        <view class="card-header">
          <text class="title">{{ item.projectName || item.name || '未命名' }}</text>
          <uv-tags :text="getStatusName(item.projectStatus)" :type="getStatusType(item.projectStatus)" size="mini" plain></uv-tags>
        </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 || item.year) }}</text>
              <text style="color: #585858;">{{ item.projectLeaderName || item.managerName || item.manager || '-' }}</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 加载更多 -->
      <uv-load-more v-if="spontaneityList.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 { spontaneityList, spontaneityPagination, fetchSpontaneityLoading } = 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;
  await fetchData(true);
  isTriggered.value = false;
};

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

const getStatusType = (code: string) => {
  const item = projectStatusOptions.find(opt => opt.dictValue === code);
  return item ? item.type : 'info';
};

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

const loadMore = async () => {
  if (loadStatus.value === 'nomore' || fetchSpontaneityLoading.value) return;
  
  loadStatus.value = 'loading';
  const { success, rows, total } = await projectStore.loadMoreSpontaneityProjects(props.queryParams);
  
  if (success) {
    if (spontaneityList.value.length >= total || rows.length < spontaneityPagination.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: 'spontaneity' });
};
</script>

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

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