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

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

  try {
    loading.value = true;
    const result = await getMyApplicationListApi({
      currentPage: 1,
      pageSize: 16,
      orderByProperty: 'name',
      Ascending: true,
      totalPage: 1,
      totalCount: 1,
      filters: [
        {
          name: 'isEnable',
          value: 1,
        },
      ],
    });
    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('/application-management');
}

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

<template>
  <div class="info-card border-box h-[217px] w-full rounded-lg p-5 shadow-md">
    <div class="items-flex-start flex justify-between">
      <div>
        <h2 class="text-lg font-bold">
          {{ $t('homeModule.applicationManagement') }}
        </h2>
        <div class="text-xs text-[#9A9BA3]">Application Management</div>
      </div>
      <img
        alt="more"
        class="h-[29px] w-[29px] cursor-pointer"
        src="@/assets/image/home-more.png"
        @click="handleMore"
      />
    </div>
    <p
      v-if="!isLogin"
      class="mt-4 w-[714px] text-sm text-xs leading-relaxed text-[#9A9BA3]"
    >
      {{ $t('homeModule.applicationManagementIntroduction') }}
    </p>

    <div v-if="isLogin" class="mt-[38px] flex flex-wrap gap-[18px]">
      <div
        v-for="(item, index) in applicationList"
        :key="index"
        class="flex h-[37px] cursor-pointer items-center rounded-[11px] bg-[#fff] p-[6px_10px] shadow-md"
      >
        <img
          :src="`/File/Download?fileId=${item.imgPhotoFileId}`"
          alt=""
          class="h-[24px] w-auto object-contain"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.info-card {
  overflow: hidden;
  background: url('@/assets/image/ApplicationManagement.png') no-repeat center
    center;
  background-size: cover;
  border-radius: 26px;
}
</style>
