<template>
  <cwg-page-wrapper>
    <view v-if="isShow">
      <view v-if="typesList.length > 0 && cardList.length > 0" class="add-apply" @click="addApply">{{ t("cards.p10") }}
      </view>
      <FirstApply v-if="cardList.length == 0" />
      <cwg-page-more-wrapper ref="loadMoreWrapperRef" v-else :loading="loading" :refresher-enabled="true"
        @refresh="handleRefresh">
        <VirtualCard />
      </cwg-page-more-wrapper>

    </view>
  </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from "vue";
import type { CardInfo } from "@/api/ucard";
import { useI18n } from "vue-i18n";
import useRouter from "@/hooks/useRouter";
import { ucardApi } from "@/api/ucard";
import FirstApply from "./components/FirstApply.vue";
import VirtualCard from "./components/VirtualCard.vue";
import useUserStore from "@/stores/use-user-store";
import useCardStore from "@/stores/use-card-store";
import useGlobalStore from "@/stores/use-global-store";

const userStore = useUserStore();
const cardStore = useCardStore();
const router = useRouter();
const { t } = useI18n();
const globalStore = useGlobalStore();
const cardList = ref<CardInfo[]>([]);
const typesList = ref<CardInfo[]>([]);

const isShow = ref(false);

async function applyList() {
  // 后台刷新最新卡列表，不阻塞已有缓存渲染
  globalStore.setFullScreenLoading(true);
  try {
    const [response1, response2, response3] = await Promise.all([
      ucardApi.cardList({ page: { current: 1, row: 10 }, a: 1 }),
      ucardApi.applyList({
        page: { current: 1, row: 100 },
      }),
      ucardApi.cardTypesList(),
    ]);
    const [data1, data2, data3] = await Promise.all([
      response1.data,
      response2.data,
      response3.data,
    ]);
    const merged = await mergeLists(data1, data2);
    cardList.value = merged;
    cardStore.saveUserCard(merged);
    cardTypesList(data3, data2);
    cardStore.saveApplyCard(data2);
    isShow.value = true;
  } catch (error) {
    // 请求失败时保留本地缓存的 cardList，避免页面空白
    console.error('加载卡片列表失败', error);
  } finally {
    globalStore.setFullScreenLoading(false);
    isShow.value = true;
  }
}
async function cardTypesList(data1, data2) {
  try {
    const recordTypeIds = new Set(
      data2.map((item) => {
        if (item.status != "fail" && item.status != "cancel") {
          return item.cardTypeId;
        }
      })
    );
    const result1 = data1;
    const result2 = result1.filter(
      (item) => !recordTypeIds.has(item.cardTypeId)
    );
    const result3 = result2.filter((item) =>
      item.supportHolderRegin.includes(this.businessForm.country)
    );
    typesList.value = result3;
  } catch (error) {
    typesList.value = [];
  }
}
async function mergeLists(list1, list2) {
  const mainList = list1.map((item) => {
    const { status, ...rest } = item;
    return {
      ...rest,
      activateStatus: status || null,
      status,
    };
  });
  const list3 = list2.filter((i) => i.status != "fail");
  const mainList2 = list3.map((item) => {
    const { status, ...rest } = item;
    return {
      ...rest,
      applyStatus: status || null,
      status,
    };
  });

  const mainCardTypeIds = new Set(mainList.map((i) => i.cardTypeId));
  const filteredList2 = mainList2.filter(
    (i) => !mainCardTypeIds.has(i.cardTypeId)
  );

  const latestMap = {};
  for (const item of filteredList2) {
    const cur = latestMap[item.cardTypeId];
    if (
      !cur ||
      new Date(item.addTime).getTime() > new Date(cur.addTime).getTime()
    ) {
      latestMap[item.cardTypeId] = { ...item, aId: item.id };
    }
  }
  const latestList2 = Object.values(latestMap);
  const latestList3 = latestList2.filter((i) => i.status != "cancel");
  return [...latestList3, ...mainList];
}

function addApply() {
  router.push("/select/card");
}
const loadMoreWrapperRef = ref<any>(null);
const loading = ref(false);
const finished = ref(false);

const handleRefresh = async () => {
  await applyList();
  // 停止下拉刷新动画
  if (loadMoreWrapperRef.value) {
    loadMoreWrapperRef.value.stopRefresh();
  }
};
onMounted(() => {
  // 1. 先用本地缓存的卡列表快速渲染，提升首屏速度
  const cachedCards = (cardStore.userCard as any) || [];
  if (Array.isArray(cachedCards) && cachedCards.length > 0) {
    cardList.value = cachedCards as CardInfo[];
    isShow.value = true;
  }

  // 2. 异步拉取最新数据并更新缓存
  applyList();
});
</script>

<style scoped lang="scss">
@import "@/uni.scss";

.add-apply {
  position: fixed;
  top: px2rpx(14);
  right: px2rpx(10);
  cursor: pointer;
  z-index: 100;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  gap: px2rpx(4);
  min-width: px2rpx(100);
  padding: 0 px2rpx(10);
  height: px2rpx(30);
  background: #ea002a;
  border-radius: px2rpx(100);
  font-size: px2rpx(14);
  color: #ffffff;
}
</style>
