<template>
  <div class="app-card" @click="handleClick">
    <div class="app-icon">
      <img :src="project.logoUrl" alt="应用图标" v-if="project.logoUrl" />
      <div class="default-icon" v-else>{{ appName.substring(0, 2) }}</div>
    </div>
    <div class="app-name">{{ appName }}</div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { getVisitPermission } from '@/api/common'
import { getToken } from '@/utils/auth'

const props = defineProps({
  project: {
    type: Object,
    required: true
  }
})

const router = useRouter()
const appName = computed(() => props.project.projectName)

const handleClick = () => {
  console.log('点击了应用卡片', props.project)
  getVisitPermission(props.project.projectBizId, props.project.tenantBizId).then(response => {
    if (response.code === 200) {
      // 有权限访问项目，进行跳转
      // 记录最近使用的应用
      const recentApps = JSON.parse(localStorage.getItem('recentApps') || '[]')
      const newRecent = [
        props.project,
        ...recentApps.filter(app => app.projectBizId !== props.project.projectBizId)
      ].slice(0, 5)
      localStorage.setItem('recentApps', JSON.stringify(newRecent))

      // 根据 isIn 字段决定跳转逻辑
      if (props.project.isIn === 0 && props.project.projectUrl) {
        let newUrl = `${props.project.projectUrl}?projectBizId=${
          props.project.projectBizId
        }&tenantBizId=${props.project.tenantBizId}&token=${getToken()}`
        // 外部跳转
        window.open(newUrl, '_blank')
      } else {
        // 内部跳转
        router.push({
          path: '/app/dashboard',
          query: {
            projectBizId: props.project.projectBizId,
            projectName: props.project.projectName
          }
        })
      }
    } else {
      // 没访问权限提示信息
      proxy.$modal.msgError(response.msg)
    }
  })
  return
}
</script>

<style scoped>
.app-card {
  width: 100px;
  height: 120px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 15px;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.app-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.app-icon {
  width: 60px;
  height: 60px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  background-color: #f5f7fa;
  overflow: hidden;
}

.app-icon img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-icon {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  color: white;
  font-size: 18px;
  font-weight: bold;
}

.app-name {
  font-size: 13px;
  color: #606266;
  text-align: center;
  padding: 0 5px;
  word-break: break-all;
  font-weight: 500;
}
</style>
