<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

import { useUserStore } from '@vben/stores';

import { $t } from '@/locales';

import { getMyApplicationListApi, type UserApi } from '#/api';
import { useLoginModalStore } from '#/store';

const applicationList = ref<UserApi.ApplicationModel[]>([]);
const loginModalStore = useLoginModalStore();
const router = useRouter();
const userStore = useUserStore();
const isLogin = computed(() => !!userStore.userInfo);
const loading = ref(false);

async function fetchApplicationList() {
  if (!isLogin.value) {
    return;
  }

  try {
    loading.value = true;
    const result = await getMyApplicationListApi({
      currentPage: 1,
      pageSize: 6,
      orderByProperty: 'name',
      Ascending: true,
      totalPage: 1,
      totalCount: 1,
      filters: [
        {
          name: 'isEnable',
          value: 1,
        },
        {
          name: 'type',
          value: 'product',
        },
      ],
    });
    if (result?.result?.model) {
      applicationList.value = result.result.model;
    }
  } catch (error) {
    console.error('获取应用列表失败:', error);
  } finally {
    loading.value = false;
  }
}

function handleMore() {
  if (!isLogin.value) {
    loginModalStore.open();
    return;
  }
  router.push({
    path: '/application-management',
    query: {
      type: '2',
    },
  });
}

watch(
  () => isLogin.value,
  (newValue) => {
    if (newValue) {
      fetchApplicationList();
    }
  },
  { immediate: true },
);
</script>

<template>
  <div>
    <h2 class="ml-[21px] mt-[21px] text-[18px] font-bold">
      {{ $t('homeModule.productList') }}
    </h2>
    <div class="flex flex-wrap gap-[18px]">
      <div
        v-for="(item, index) in applicationList"
        :key="index"
        class="mt-[24px] flex cursor-pointer items-center rounded-[30px] border border-gray-200 bg-white px-[24px] py-[7px] shadow-md"
      >
        <img
          :src="`/File/Download?fileId=${item.imgLogoFileId}`"
          class="h-[30px] w-auto object-contain"
        />
        <span
          class="ml-[10px] font-['Open_Sans'] text-[13px] font-medium text-[#000]"
        >
          {{ item.name }}
        </span>
      </div>
      <div
        class="mt-[24px] flex cursor-pointer items-center rounded-[30px] border border-gray-200 bg-white px-[24px] py-[7px] text-[#810041] shadow-md"
        @click="handleMore"
      >
        {{ $t('btn.more') }} >
      </div>
    </div>
  </div>
</template>

<style scoped></style>
