<template>
  <uv-popup ref="popupRef" mode="bottom" round="20rpx" @close="closeDialog" closeable>
    <view class="select-project-container">
      <view class="popup-header">
        <text class="title">选择项目</text>
      </view>

      <view class="search-bar">
        <uv-input
          v-model="queryParams.projectName"
          placeholder="搜索项目名称"
          prefixIcon="search"
          shape="circle"
          clearable
          customStyle="background-color: #f5f7fa; border: none; flex: 1;"
          @change="onSearchInput"
        ></uv-input>
      </view>

      <scroll-view
        scroll-y
        class="project-list"
        @scrolltolower="loadMore"
        refresher-enabled
        :refresher-triggered="isTriggered"
        @refresherrefresh="onRefresh"
      >
        <uv-empty v-if="!list.length && loadStatus !== 'loading'" mode="list"></uv-empty>

        <view
          class="project-item"
          v-for="item in list"
          :key="item.projectId"
          @click="selectProject(item)"
        >
          <view class="item-header">
            <text class="project-name">{{ item.projectName || '未命名' }}</text>
            <text class="project-type">{{ getTypeName(item.projectType) }}</text>
          </view>
          <view class="item-body">
            <text class="info-text">项目编码：{{ item.projectCode || '-' }}</text>
            <text class="info-text">负责人：{{ item.projectLeaderName || '-' }}</text>
          </view>
        </view>

        <uv-load-more
          v-if="list.length > 0 || loadStatus === 'loading'"
          :status="loadStatus"
          @loadmore="loadMore"
        ></uv-load-more>
      </scroll-view>
    </view>
  </uv-popup>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { useProjectApi } from '@/api/project/index';
import { debounce } from 'lodash-es';

const emit = defineEmits(['select']);
const projectApi = useProjectApi();
const popupRef = ref<any>(null);

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

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

const openDialog = () => {
  popupRef.value?.open();
  fetchData(true);
};

const closeDialog = () => {
  popupRef.value?.close();
  list.value = [];
  queryParams.value.pageNum = 1;
  queryParams.value.projectName = '';
};

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

  try {
    const res: any = await projectApi.getList(queryParams.value);
    if (res.code === 200) {
      const rows = res.data?.list || [];
      total.value = res.data?.total || 0;
      
      list.value = reset ? rows : [...list.value, ...rows];
      
      if (list.value.length >= total.value || rows.length < queryParams.value.pageSize) {
        loadStatus.value = 'nomore';
      } else {
        loadStatus.value = 'loadmore';
      }
    } else {
      loadStatus.value = 'nomore';
    }
  } catch (error) {
    console.error(error);
    loadStatus.value = 'nomore';
  } finally {
    if (reset) {
      isTriggered.value = false;
    }
  }
};

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

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

const loadMore = () => {
  if (loadStatus.value === 'nomore' || loadStatus.value === 'loading') return;
  queryParams.value.pageNum += 1;
  fetchData(false);
};

const getTypeName = (type: string | number) => {
  if (type == '10') return '纵向项目';
  if (type == '20') return '横向项目';
  if (type == '30') return '内部项目';
  if (type == '40') return '重点学科';
  return '未知';
};

const selectProject = (item: any) => {
  emit('select', item);
  closeDialog();
};

defineExpose({
  openDialog,
  closeDialog
});
</script>

<style lang="scss" scoped>
.select-project-container {
  height: 80vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;
}

.popup-header {
  height: 96rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  
  .title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.search-bar {
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #f5f5f5;
  z-index: 10;
}

.project-list {
  flex: 1;
  height: 0;
  padding: 20rpx 30rpx;
  box-sizing: border-box;
}

.project-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.02);
  
  &:active {
    background-color: #f5f7fa;
  }

  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16rpx;

    .project-name {
      font-size: 30rpx;
      font-weight: 500;
      color: #333;
      flex: 1;
      margin-right: 20rpx;
    }

    .project-type {
      font-size: 24rpx;
      color: #1c9bfd;
      background-color: rgba(28, 155, 253, 0.1);
      padding: 4rpx 12rpx;
      border-radius: 4rpx;
      white-space: nowrap;
    }
  }

  .item-body {
    display: flex;
    flex-direction: column;
    gap: 10rpx;

    .info-text {
      font-size: 26rpx;
      color: #666;
    }
  }
}
</style>
