<template>
  <el-card class="w-full min-w-0 relative" style="border: 0">
    <div
      class="relative overflow-hidden rounded-lg mb-3 h-25 bg-cover bg-center"
      :style="{ backgroundImage: `url(${bg})` }"
    >
      <div class="absolute inset-0 bg-white/0"></div>
      <div class="relative h-full flex items-center gap-3 px-4 cursor-pointer">
        <div class="min-w-0 flex-1">
          <h3 class="font-bold">{{ title }}</h3>
          <div class="text-[#606266] text-sm mt-1 leading-snug">{{ desc }}</div>
        </div>
      </div>
    </div>

    <!-- 九宫格布局 -->
    <div class="p-4">
      <div class="flex flex-wrap gap-4">
        <div
          v-for="(item, index) in items"
          :key="index"
          class="relative rounded-lg p-3 text-center cursor-pointer group transform transition-transform duration-200 hover:bg-blue-50 hover:scale-105 hover:shadow-lg"
          @mouseenter="showTooltip(index)"
          @mouseleave="hideTooltip"
          @click="handleView(item)"
        >
          <div class="flex flex-col items-center">
            <!-- 功能图标占位符 -->
            <div
              class="w-13 h-13 rounded-lg flex items-center justify-center mb-2 mx-auto transition-colors"
            >
              <img
                :src="getIconByLabel(item.label)"
                :alt="`${item.label} Logo`"
                class="w-full h-full object-contain"
              />
            </div>

            <!-- 功能名称 -->
            <span
              :class="[
                'text-xs font-medium text-slate-600',
                isSpecialSystem(item.label)
                  ? 'font-bold text-gray-800'
                  : 'text-gray-700',
              ]"
            >
              {{ item.label }}
            </span>

            <!-- 标签 -->
            <!-- <span
              v-if="item.tag"
              class="mt-1 text-xs px-2 py-0.5 rounded-full bg-red-100 text-red-700"
            >
              {{ item.tag }}
            </span> -->
          </div>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ssoLogin, getMCSsoToken, zentaoSsoLogin } from "@/api/user";
import { useUserStore } from "@/stores/useUserStore";
import { getAccessToken } from "@/utils/auth";

// 导入所有图标
import oaimage from "@/assets/images/oa.jpg";
import crmimage from "@/assets/images/crm.jpg";
import ehrimage from "@/assets/images/ehr.jpg";
import scmimage from "@/assets/images/scm.png";
import erpimage from "@/assets/images/fm.jpg"; // 财务管理系统
import driveimage from "@/assets/images/drive.jpg"; // 经营驾驶舱
import zhanlueimage from "@/assets/images/zhanlue.jpg"; // 战略解码
import jishuimage from "@/assets/images/jishu.jpg"; // 技术研发管理
import zuzhiimage from "@/assets/images/zuzhi.jpg"; // 组织资产管理
import safeimage from "@/assets/images/safe.png"; // 安全合规管理
import pmsimage from "@/assets/images/pms.jpeg"; // 设备管理
import zhonghangimage from "@/assets/images/中航.png"; // 中航北斗
import lianyouimage from "@/assets/images/lianyou.jpeg"; // 智能连油
import qhseimage from "@/assets/images/qhse.jpg"; // qhse
import zuanjingimage from "@/assets/images/zuanjing.jpeg"; //智能钻井
import yalieimage from "@/assets/images/yalie.png"; //智能压裂
import zhuqiimage from "@/assets/images/zhuqi.png"; //智能注气
import pmimage from "@/assets/images/pm.jpg"; // 项目管理
import dataimage from "@/assets/images/data.jpg"; // 全局数据治理
import thinkimage from "@/assets/images/think.jpg"; // 智能决策
import aiimage from "@/assets/images/ai.png"; // AI大模型
import agentimage from "@/assets/images/agent.jpeg"; // ai智能体
import videoimage from "@/assets/images/video.png"; // ai智能体
import youimage from "@/assets/images/youcnag.png"; // ai智能体
import fileagent from "@/assets/images/fileagent.png";
import zhiduagent from "@/assets/images/zhiduagent.png";
import jishuimage2 from "@/assets/images/jishuimage.png";

const userStore = useUserStore();
const router = useRouter();

// 控制弹出框显示
const currentTooltipIndex = ref<number | null>(null);

const showTooltip = (index: number) => {
  currentTooltipIndex.value = index;
};

const hideTooltip = () => {
  currentTooltipIndex.value = null;
};

type Item = { label: string; tag?: "新" | "热" };

const props = defineProps<{
  title: string;
  desc: string;
  items: Item[];
  bg: string;
  // bg2: string[];
  id: string;
}>();

// 创建图标映射表
const iconMap: Record<string, string> = {
  OA办公: oaimage,
  "经营驾驶舱(MC)": driveimage,
  战略解码与执行: zhanlueimage,
  "财务管理(FM)": erpimage,
  技术研发管理: jishuimage,
  "客户管理(CRM)": crmimage,
  "人力资源(EHR)": ehrimage,
  "供应商管理(SRM)": scmimage,
  组织资产管理: zuzhiimage,
  风控合规管理: safeimage,
  中航北斗: zhonghangimage,
  "视频中心(VCS)": videoimage,
  智能钻井: zuanjingimage,
  智慧压裂: yalieimage,
  智慧注气: zhuqiimage,
  智慧连油: lianyouimage,
  "质量安全管理(QHSE)": qhseimage,
  "设备管理(PMS)": pmsimage,
  "项目管理(PM)": pmimage,
  "全局数据治理(数据中台)": dataimage,
  智能决策: thinkimage,
  行业AI大模型: aiimage,
  "AI智能体(智能交互)": agentimage,
  数字油藏: youimage,
  工艺文件智能体: fileagent,
  集团制度智能体: zhiduagent,
  研发需求管理: jishuimage2,
};
const isSpecialSystem = (label: string) => {
  const specialSystems = [
    "OA办公",
    "客户管理(CRM)",
    "设备管理(PMS)",
    "中航北斗",
    "智慧连油",
  ];
  return specialSystems.includes(label);
};
// 根据标签获取对应图标
const getIconByLabel = (label: string) => {
  return iconMap[label] || oaimage; // 默认返回oa图标，以防某些标签没有对应图标
};

// 处理查看按钮点击事件
const handleView = async (item: Item) => {
  if (item.label === "OA办公") {
    if (userStore.getUser.username && getAccessToken()) {
      const res = await ssoLogin({
        username: userStore.getUser.username,
      });

      if (res) {
        window.open(
          "https://yfoa.keruioil.com/wui/index.html?ssoToken=" + res + "#/main",
          "_blank",
        );
      }
    } else {
      router.push({ path: "/login" });
    }
  }

  if (item.label === "设备管理(PMS)") {
    if (userStore.getUser.username && getAccessToken()) {
      window.open(
        import.meta.env.VITE_PMS_URL +
          "/portalLogin?username=" +
          userStore.getUser.username,
        "_blank",
      );
    } else {
      router.push({ path: "/login" });
    }
  }

  if (item.label === "中航北斗") {
    // window.open("https://zhbdgps.cn", "_blank");
    if (userStore.getUser.username && getAccessToken()) {
      window.open("https://zhbdgps.cn", "_blank");
    } else {
      router.push({ path: "/login" });
    }
  }

  if (item.label === "客户管理(CRM)") {
    if (userStore.getUser.username && getAccessToken()) {
      window.open(
        "https://crm-tencent.xiaoshouyi.com/global/sso/callback/00APEB9EEEA9B2E338B686B7ECFA8585808C.action?token=" +
          getAccessToken(),
        "_blank",
      );
    } else {
      router.push({ path: "/login" });
    }
  }

  if (item.label === "智慧连油") {
    const extraParam = "source=zhly";
    if (userStore.getUser.username && getAccessToken()) {
      window.open(
        import.meta.env.VITE_PMS_URL +
          "/portalLogin?username=" +
          userStore.getUser.username +
          "&" +
          extraParam,
        "_blank",
      );
    } else {
      router.push({ path: "/login" });
    }
  }

  if (item.label === "智慧注气") {
    const extraParam = "source=znzq";
    if (userStore.getUser.username && getAccessToken()) {
      window.open(
        import.meta.env.VITE_PMS_URL +
          "/portalLogin?username=" +
          userStore.getUser.username +
          "&" +
          extraParam,
        "_blank",
      );
    } else {
      router.push({ path: "/login" });
    }
  }

  if (item.label === "视频中心(VCS)") {
    const extraParam = "source=spzx";
    if (userStore.getUser.username && getAccessToken()) {
      window.open(
        import.meta.env.VITE_PMS_URL +
          "/portalLogin?username=" +
          userStore.getUser.username +
          "&" +
          extraParam,
        "_blank",
      );
    } else {
      router.push({ path: "/login" });
    }
  }

  if (item.label === "质量安全管理(QHSE)") {
    const extraParam = "source=qhse";
    if (userStore.getUser.username && getAccessToken()) {
      window.open(
        import.meta.env.VITE_PMS_URL +
          "/portalLogin?username=" +
          userStore.getUser.username +
          "&" +
          extraParam,
        "_blank",
      );
    } else {
      router.push({ path: "/login" });
    }
  }

  if (item.label === "经营驾驶舱(MC)") {
    if (userStore.getUser.username && getAccessToken()) {
      const res = await getMCSsoToken();

      if (res) {
        window.open(
          "https://report.deepoil.cc/webroot/decision/v10/entry/access/9fb42908-894a-4373-a6be-ce046a42851d?preview=true&page_number=1&ssoToken=" +
            res,
          "_blank",
        );
      }
    } else {
      router.push({ path: "/login" });
    }
  }

  if (item.label === "研发需求管理") {
    if (userStore.getUser.username && getAccessToken()) {
      const res = await zentaoSsoLogin({
        username: userStore.getUser.username,
      });

      console.log("禅道sso登录结果：", res);

      if (res) {
        window.open(
          `http://project.deepoil.cc/zentao/api.php?m=user&f=apilogin&account=${res.jobNumber}&code=${res.code}&time=${res.timestamp}&token=${res.token}`,
          "_blank",
        );
      }
    } else {
      router.push({ path: "/login" });
    }
  }
};
</script>

<style scoped>
:deep(.el-card) {
  width: 100%;
  min-width: 0;
  overflow: hidden;
}

:deep(.el-card__body) {
  width: 100%;
  min-width: 0;
  padding: 0;
}

/* 弹出框向上淡入动画 */
.tooltip-fade-enter-active {
  transition: all 0.3s ease;
}

.tooltip-fade-leave-active {
  transition: all 0.2s ease;
}

.tooltip-fade-enter-from {
  opacity: 0;
  transform: translate(-50%, 10px);
}

.tooltip-fade-leave-to {
  opacity: 0;
  transform: translate(-50%, 10px);
}
</style>
