<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="type-tabs">
      <uv-tabs :list="tabList" :current="currentTab" @change="onTabChange"
        :activeStyle="{ color: '#1c9bfd', fontWeight: 'bold', transform: 'scale(1.05)' }"
        :inactiveStyle="{ color: '#666' }" lineColor="#1c9bfd" lineWidth="40" :itemStyle="{ height: '88rpx', flex: 1 }"
        :scrollable="false"></uv-tabs>
    </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="handleCardClick(item)">
          <view class="card-header">
            <text class="title">打款单位：{{ item.unit || '-' }}</text>
            <text class="status-tag"
              :class="item.status == '10' ? 'status-undo' : (item.status == '30' ? 'status-undo' : 'status-done')">
              {{ item.status == '10' ? '待认领' : (item.status == '30' ? '认领中' : '已认领') }}
            </text>
          </view>
          <view class="card-body">
            <!-- <view class="info-item">
              <text class="label">到账日期：</text>
              <text class="value">{{ item.date ? formatDate(new Date(item.date), 'YYYY-MM-DD') : '-' }}</text>
            </view>
            <view class="info-item">
              <text class="label">经费类型：</text>
              <text class="value">{{ getDictLabel(paymentReceivedTypeOptions, item.type) }}</text>
            </view> -->
            <view class="info-item">
              <text class="label">到款金额(元)：</text>
              <text class="value number-font">{{ amountUnitFormatter(item.amount) }}{{ item.includeTax ? '(含税)' :
                '(不含税)' }}</text>
            </view>
            <!-- <view class="info-item">
              <text class="label">管理费(元)：</text>
              <text class="value number-font">{{ amountUnitFormatter(item.manageAmount) }}</text>
            </view>
            <view class="info-item">
              <text class="label">税费(元)：</text>
              <text class="value number-font">{{ amountUnitFormatter(item.taxAmount) }}</text>
            </view> -->
            <view class="info-item" v-if="item.projectName">
              <text class="label">项目名称：</text>
              <text class="value text-ellipsis">{{ item.projectName }}</text>
            </view>
            <view class="info-item" v-if="item.projectLeaderName">
              <text class="label">项目负责人：</text>
              <text class="value">{{ item.projectLeaderName }}</text>
            </view>
            <!-- <view class="info-item" v-if="item.projectDeptName">
              <text class="label">科室：</text>
              <text class="value">{{ item.projectDeptName }}</text>
            </view>
            <view class="info-item" v-if="item.createdName">
              <text class="label">创建人：</text>
              <text class="value">{{ item.createdName }}</text>
            </view>
            <view class="info-item" v-if="item.createdTime">
              <text class="label">创建时间：</text>
              <text class="value">{{ item.createdTime ? formatDate(new Date(item.createdTime), 'YYYY-MM-DD') : '-'
                }}</text>
            </view> -->
          </view>
          <view class="card-actions" @click.stop v-if="isAdmin && (item.status == '10' || item.status == '30')">
            <view class="btn-box" v-if="item.status == '10'">
              <uv-button text="认领" type="primary" shape="circle" size="small" @click="toClaim(item.id)"></uv-button>
            </view>
            <view class="btn-box" v-if="item.status == '30'">
              <uv-button text="继续认领" type="primary" shape="circle" size="small" @click="toClaim(item.id)"></uv-button>
            </view>
          </view>
        </view>

        <uv-load-more v-if="list.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>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick, watch, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { debounce } from 'lodash-es';
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/store/modules/user';
import { useFundApi } from '@/api/fund/index';
import { useSystemApi } from '@/api/system/index';
import { onRouterPush } from '@/utils/router';
import { DEFAULT_PAGE_SIZE } from '@/constants/index';
import { formatDate } from '@/utils/date';

const userStore = useUserStore();
const { roles } = storeToRefs(userStore);

const ADMIN_ROLES = ['scientific_research_secretary', 'scientific_research_admin', 'sys_admin', 'admin'];

const isAdmin = computed(() => {
  const userRoles = roles.value || [];
  return ADMIN_ROLES.some(adminRole =>
    userRoles.some((r: any) => r.roleCode === adminRole)
  );
});

const allTabs = [{ name: '待认领', type: '10' }, { name: '已认领', type: '20' }, { name: '认领中', type: '30' }];
const tabList = computed(() => {
  if (isAdmin.value) {
    return allTabs;
  }
  return [{ name: '已认领', type: '20' }];
});

const fundApi = useFundApi();
const systemApi = useSystemApi();

const currentTab = ref(0);

const queryParams = ref({
  status: '10',
  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);
const paymentReceivedTypeOptions = ref<any[]>([]);

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 getDictLabel = (options: any[], value: string) => {
  const find = options.find((item) => item.dictValue === value);
  return find ? find.dictLabel : value || '-';
};

const getDict = async () => {
  try {
    const res: any = await systemApi.getDictDataByType('PaymentReceivedType');
    if (res.code == 200 && res.data) {
      paymentReceivedTypeOptions.value = res.data.values || [];
    }
  } catch (err) {
    console.error(err);
  }
};

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

  try {
    const res: any = await fundApi.getList(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 onTabChange = (e: any) => {
  currentTab.value = e.index;
  queryParams.value.status = tabList.value[e.index].type;
  fetchListData(true);
};

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 toViewDetail = (id: number) => {
  onRouterPush(`/pages/fund/claim/detail?id=${id}`);
};

const toClaim = (id: number) => {
  onRouterPush(`/pages/fund/claim/edit?id=${id}`);
};

const handleCardClick = (item: any) => {
  if (isAdmin.value && item.status == '10') {
    toClaim(item.id);
  } else {
    toViewDetail(item.id);
  }
};

onLoad(() => {
  queryParams.value.status = tabList.value[0]?.type || '20';
  getDict();
  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;
}

.type-tabs {
  background-color: #fff;
  padding-bottom: 10rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
}

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

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

.common-list-card {
  .card-header {
    .status-tag {
      &.status-done {
        color: #52c41a;
        background-color: rgba(82, 196, 26, 0.1);
      }

      &.status-undo {
        color: #fa8c16;
        background-color: rgba(250, 173, 20, 0.1);
      }
    }
  }

  .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;
      }
    }
  }

  .card-actions {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 24rpx;
    margin-top: 16rpx;
    border-top: 1rpx solid #f0f0f0;

    .btn-box {
      width: 150rpx;
      margin-left: 20rpx;
    }
  }
}

.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;
}
</style>
