<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';

interface Props {
  jurisdiction: boolean;
}

const props = defineProps<Props>();
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: 7,
      orderByProperty: 'name',
      Ascending: true,
      totalPage: 1,
      totalCount: 1,
      filters: [
        {
          name: 'isEnable',
          value: 1,
        },
        {
          name: 'type',
          value: 'application',
        },
      ],
    });
    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: '1',
    },
  });
}

function handleClick(item: UserApi.ApplicationModel) {
  const baseUrl = location.origin + location.pathname;
  window.open(
    `${baseUrl}#/jumpToEnterprise?enterpriseCode=${item.code}&webSite=${item.webSite}`,
    '_blank',
  );
}

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
        v-if="props.jurisdiction"
        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-else-if="props.jurisdiction && isLogin" class="mt-[38px]">
      <div v-if="applicationList.length > 0" class="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"
          @click="handleClick(item)"
        >
          <img
            :src="`/File/Download?fileId=${item.imgLogoFileId}`"
            alt=""
            class="h-[24px] w-auto object-contain"
          />
          <span
            class="ml-[10px] font-['Open_Sans'] text-[13px] font-medium text-[#000]"
          >
            {{ item.name }}
          </span>
        </div>
      </div>
      <div
        v-else
        class="mx-auto mt-[-20px] flex flex-col items-center justify-center text-center"
      >
        <img
          alt=""
          class="block h-[80px] w-[85px]"
          src="@/assets/image/jurisdiction.png"
        />
        {{ $t('auth.emptyContent') }}
      </div>
    </div>
    <div
      v-else
      class="mt-[10px] flex flex-col items-center justify-center text-center"
    >
      <img
        alt=""
        class="block h-[80px] w-[85px]"
        src="@/assets/image/empty.png"
      />
      {{ $t('auth.noPermission') }}
    </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>
