<template>
  <div class="portal-home min-h-screen bg-[#eef3f9] text-[#17345f]">
    <Header />

    <main class="mx-auto max-w-[1400px] px-3 pb-8 pt-20">
      <section class="hero-banner overflow-hidden rounded-[6px] relative">
        <div class="">
          <!-- 轮播容器 -->
          <div class="carousel-container relative h-[50%]">
            <!-- 轮播项 -->
            <div
              class="carousel-slide absolute inset-0 transition-opacity duration-500 ease-in-out"
              v-for="(slide, index) in slides"
              :key="index"
              v-show="currentIndex === index"
              :class="{
                'opacity-100': currentIndex === index,
                'opacity-0': currentIndex !== index,
                'z-10': currentIndex === index,
                'z-0 pointer-events-none': currentIndex !== index,
              }"
            >
              <div class="hero-copy carousel-caption">
                <div class="hero-script text-[68px] font-italic text-[#0c4eb5]">
                  HELLO
                </div>
                <p class="hero-text mt-6 text-[24px] text-[#5f6f83]">
                  {{ slide.text }}
                </p>
              </div>

              <!-- 轮播背景图 -->
              <div class="hero-visual absolute inset-0">
                <img
                  :src="slide.image"
                  alt="Banner"
                  class="w-full h-full object-cover"
                />
              </div>
            </div>

            <!-- 指示器 -->
            <div
              class="carousel-indicators absolute bottom-4 left-1/2 z-30 flex transform -translate-x-1/2 space-x-2"
            >
              <span
                v-for="(_, i) in slides"
                :key="i"
                @click="currentIndex = i"
                :class="{
                  'bg-[#0c4eb5]': currentIndex === i,
                  'bg-[#2f333c]/50': currentIndex !== i,
                }"
                class="w-3 h-3 rounded-full transition-colors"
              ></span>
            </div>
          </div>
        </div>
      </section>

      <section class="portal-mobile-shortcuts mt-3 md:hidden!">
        <button
          type="button"
          class="portal-mobile-shortcut flex flex-col items-center justify-center cursor-pointer"
          @click="router.push('/flow')"
        >
          <img src="../assets//images/flow.png" alt="" class="w-10 h-10" />
          流程门户
        </button>
        <button
          v-hasPermi="['portal:dashboard:view']"
          type="button"
          class="portal-mobile-shortcut flex flex-col items-center justify-center cursor-pointer"
          @click="router.push('/drive')"
        >
          <img src="../assets//images/driveicon.png" alt="" class="w-10 h-10" />
          驾驶舱门户
        </button>
        <button
          type="button"
          class="portal-mobile-shortcut flex flex-col items-center justify-center cursor-pointer"
        >
          <img src="../assets//images/report.png" alt="" class="w-10 h-10" />
          报表门户
        </button>
      </section>

      <section class="mt-3 grid gap-4 xl:grid-cols-[1.74fr_0.74fr] grid-cols-1">
        <div class="space-y-4">
          <article
            v-for="section in portalSections"
            :key="section.code"
            class="platform-block rounded-sm md:flex"
            :style="{ minHeight: section.height }"
          >
            <div class="platform-block__header">
              <img src="../assets//images/icon.png" alt="" class="w-20 h-20" />
              <div class="platform-block__title-wrap">
                <p class="platform-block__title">{{ section.title }}</p>
                <span class="platform-block__subtitle">{{
                  section.subtitle
                }}</span>
              </div>
            </div>

            <div
              v-if="section.apps?.length"
              class="grid grid-cols-[repeat(2,minmax(0,1fr))] gap-2 p-6 px-3 md:px-6 md:grid-cols-[repeat(4,minmax(0,1fr))]"
            >
              <button
                v-for="(app, appIndex) in section.apps"
                :key="`${section.code}-${appIndex}-${app.label}`"
                type="button"
                :class="[
                  'platform-app',
                  boldLabes.includes(app.label)
                    ? 'platform-app--active'
                    : 'platform-app--ghost',
                ]"
                @click="handlePortalAppClick(app)"
              >
                <span class="platform-app__icon">
                  <img
                    v-if="app.image"
                    :src="app.image"
                    :alt="app.label"
                    class="h-7 w-7 object-contain rounded-md"
                  />
                  <Icon
                    v-else
                    :icon="app.icon || 'mdi:dots-grid'"
                    class="text-[24px]"
                  />
                </span>
                <span
                  class="platform-app__label text-[#004098] md:text-sm text-[12px] text-left"
                  >{{ app.label }}</span
                >
              </button>
            </div>
          </article>
        </div>

        <aside class="space-y-4">
          <section class="side-card side-card--notice rounded-md p-2">
            <div class="side-card__header w-[95%] ml-[8px]">
              <div class="notice-tabs">
                <button
                  style="color: #fff !important"
                  v-for="tab in noticeTabs"
                  :key="tab.key"
                  type="button"
                  :class="[
                    'notice-tab',
                    activeNoticeTab === tab.key ? 'notice-tab--active' : '',
                  ]"
                  @click="handleNoticeTabChange(tab.key)"
                >
                  {{ tab.label }}
                </button>
              </div>
              <button
                type="button"
                class="side-card__more"
                @click="handleNoticeMoreClick"
              >
                更多
                <Icon icon="mingcute:right-line" class="text-[18px]" />
              </button>
            </div>

            <div class="space-y-2 p-2 pt-3">
              <div
                v-if="!userStore.getUser.username"
                class="flex h-full items-center justify-center"
              >
                <div class="text-[#8a9ab0] pt-5">登录后查看</div>
              </div>

              <div
                v-if="!currentNoticeList.length && userStore.getUser.username"
                class="flex h-[120px] items-center justify-center text-[#8a9ab0]"
              >
                暂无数据
              </div>
              <article
                v-if="userStore.getUser.username"
                v-for="notice in currentNoticeList"
                :key="notice.id"
                class="notice-item cursor-pointer"
                @click="handleNoticeItemClick(notice)"
              >
                <div class="notice-item__desc">{{ notice.docsubject }}</div>
                <div class="date text-[12px] text-[#9cadc0]">
                  {{ notice.docvaliddate }}
                </div>
              </article>
            </div>
          </section>

          <section
            class="side-card side-card--notice rounded-md p-2"
            :style="{ minHeight: '190px' }"
          >
            <div class="side-card__header w-[91%] ml-[15px]">
              <div class="notice-badge px-2 pb-2">{{ todoPanelTitle }}</div>
              <button
                type="button"
                class="side-card__more"
                @click="router.push('/todo-list')"
              >
                全部任务
                <Icon icon="mingcute:right-line" class="text-[18px]" />
              </button>
            </div>
            <div class="space-y-2 p-4 pt-2">
              <div
                v-if="!userStore.getUser.username"
                class="flex h-full items-center justify-center"
              >
                <div class="text-[#8a9ab0] pt-10">登录后查看</div>
              </div>

              <div
                v-if="!oaTasks.length && userStore.getUser.username"
                class="flex h-full items-center justify-center"
              >
                <div class="text-[#8a9ab0] pt-10">暂无待办</div>
              </div>

              <article
                v-if="userStore.getUser.username"
                v-for="task in oaTasks"
                :key="task.requestId"
                @click="handleTask(task)"
                class="todo-item rounded-md cursor-pointer"
              >
                <div class="flex min-w-0 items-start justify-between gap-3">
                  <div class="min-w-0">
                    <div
                      class="truncate text-[14px] font-semibold text-[#0d4a9d]"
                    >
                      {{ task.requestName }}
                    </div>
                    <div class="mt-1 text-[12px] text-[#8a9ab0]">
                      创建人：{{ task.creatorName }} · {{ task.createTime }}
                    </div>
                  </div>
                  <span
                    :class="['todo-item__tag', getTagClass(task.requesLevel)]"
                    >{{ getTagName(task.requesLevel) }}</span
                  >
                </div>
              </article>
            </div>
          </section>

          <section
            class="side-card side-card--content p-2 rounded-md"
            :style="{ minHeight: '180px' }"
          >
            <div class="side-card__header w-[90%] ml-[15px]">
              <div class="news notice-badge pb-2">{{ newsPanelTitle }}</div>
              <button type="button" class="side-card__more" @click="goNews">
                更多
                <Icon icon="mingcute:right-line" class="text-[18px]" />
              </button>
            </div>
            <div class="space-y-2 p-4 pt-2">
              <div
                v-if="!userStore.getUser.username"
                class="flex h-full items-center justify-center"
              >
                <div class="text-[#8a9ab0] pt-10">登录后查看</div>
              </div>

              <div
                v-if="!newsList.length && userStore.getUser.username"
                class="flex h-full items-center justify-center"
              >
                <div class="text-[#8a9ab0] pt-10">暂无新闻</div>
              </div>
              <article
                v-for="news in newsList"
                :key="news.id"
                class="news-mini cursor-pointer rounded-md"
                @click="handleNoticeItemClick(news)"
              >
                <div class="min-w-0 flex-1">
                  <div
                    class="line-clamp-1 text-[13px] font-semibold leading-[1.45] text-[#c8d0e5]"
                  >
                    {{ news.docsubject }}
                  </div>
                  <div class="mt-2 text-[12px] text-[#9cadc0]">
                    {{ news.docvaliddate }}
                  </div>
                </div>
              </article>
            </div>
          </section>

          <section
            v-if="userStore.getUser.username"
            class="side-card side-card--placeholder rounded-md"
            :style="{ minHeight: '78px', backgroundColor: '#3575e4' }"
          >
            <div class="placeholder-panel flex flex-col text-left">
              <!-- <div class="text-sm">需要帮助？</div> -->
              <div class="text-[10px]">遇到系统操作问题，需要帮助</div>
              <div
                class="bg-white text-sm text-center text-[#004098] py-1 px-2 rounded-full mt-2 w-[30%] cursor-pointer"
                @click="openConsult"
              >
                立即咨询
              </div>
            </div>
          </section>
        </aside>
      </section>
    </main>

    <el-dialog v-model="dialogVisible" title="提示" width="500">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <h4 :id="titleId" class="flex gap-2 items-center">
            <Icon
              :icon="'si:warning-line'"
              color="#ef6c1a"
              size="16"
              class="text-[20px]"
            /><span class="text-black">提示</span>
          </h4>
        </div>
      </template>
      <span class="text-black">SRM系统尚未正式上线使用</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" color="#063e8d" @click="confirmSrm">
            继续访问
          </el-button>
        </div>
      </template>
    </el-dialog>

    <Footer />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, reactive, ref } from "vue";
import * as authUtil from "@/utils/auth";
import * as dd from "dingtalk-jsapi";
import Header from "@components/home/header.vue";
import Footer from "@components/home/Footer.vue";
import { useRouter } from "vue-router";
import axios from "axios";
import { Icon } from "@iconify/vue";
import { ElLoading, ElMessageBox } from "element-plus";
import {
  getMCSsoToken,
  ssoLogin,
  zentaoSsoLogin,
  getOATasks,
  getNotices,
  getRedHeadFiles,
  getNews,
  srmLogin,
} from "@/api/user";
import { useUserStore } from "@/stores/useUserStore";
import { getAccessToken } from "@/utils/auth";
import { deleteUserCache } from "@hooks/useCache";
import { manualLogoutKey, reloginCancelKey } from "@/config/axios/service";
import banner1 from "@/assets/images/banner1.png";
import banner2 from "@/assets/images/banner2.png";
import banner3 from "@/assets/images/banner3.jpg";
import banner4 from "@/assets/images/banner4.png";
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 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";
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";
import agentimage from "@/assets/images/agent.jpeg";
import videoimage from "@/assets/images/video.png";
import fileagent from "@/assets/images/fileagent.png";
import zhiduagent from "@/assets/images/zhiduagent.png";
import jishuimage2 from "@/assets/images/jishuimage.png";
import zhanlueimage from "@/assets/images/zhanlue.jpg"; // 战略解码
import safeimage from "@/assets/images/safe.png"; // 安全合规管理
import zuzhiimage from "@/assets/images/zuzhi.jpg";
import youimage from "@/assets/images/youcnag.png"; // ai智能体
import hongpan from "@/assets/images/鸿盘.jpg"; // ai智能体

type PortalApp = {
  label: string;
  icon?: string;
  image?: string;
  active?: boolean;
};

type PortalSection = {
  code: string;
  title: string;
  subtitle: string;
  height: string;
  apps?: PortalApp[];
};

type NoticeItem = {
  id?: string | number;
  title?: string;
  desc?: string;
  docsubject?: string;
};

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

const todoPanelTitle = "待办中心";
const newsPanelTitle = "新闻中心";
const noticeTabs = [
  { key: "redHead", label: "红头文件" },
  { key: "notice", label: "通知公告" },
] as const;

type NoticeTabKey = (typeof noticeTabs)[number]["key"];

const portalSections: PortalSection[] = [
  {
    code: "数",
    title: "数字化运营平台",
    subtitle: "高效协同 · 战略洞察",
    height: "220px",
    apps: [
      {
        label: "OA办公",
        image: oaimage,
        active: true,
      },
      { label: "客户管理(CRM)", image: crmimage },
      { label: "人力资源(EHR)", image: ehrimage },
      { label: "供应商管理(SRM)", image: scmimage },
      { label: "经营驾驶舱(MC)", image: driveimage },
      { label: "项目管理(PM)", image: pmimage },
      { label: "开发需求管理", image: jishuimage2 },
      { label: "鸿盘", image: hongpan },

      { label: "财务管理(FM)", image: erpimage },

      { label: "技术研发管理(R&D)", image: jishuimage2 },
      { label: "战略解码与执行", image: zhanlueimage },
      { label: "组织资产管理", image: zuzhiimage },
      { label: "风控合规管理", image: safeimage },
    ],
  },
  {
    code: "智",
    title: "智慧指挥平台",
    subtitle: "高效协同 · 战略洞察",
    height: "210px",
    apps: [
      { label: "设备管理(PMS)", image: pmsimage, active: true },
      { label: "中航北斗", image: zhonghangimage },
      { label: "质量安全管理(QHSE)", image: qhseimage },
      { label: "智慧连油", image: lianyouimage },
      { label: "智慧注气", image: zhuqiimage },
      { label: "视频中心(VCS)", image: videoimage },
      { label: "智能钻井", image: zuanjingimage },
      { label: "智慧压裂", image: yalieimage },
      { label: "数字油藏", image: youimage },
    ],
  },
  {
    code: "AI",
    title: "Chat BI平台",
    subtitle: "数据智能 · 决策驱动",
    height: "160px",
    apps: [
      { label: "全局数据治理(数据中台)", image: dataimage, active: true },
      { label: "智能决策", image: thinkimage },
      { label: "行业AI大模型", image: aiimage },
      { label: "AI智能体(智能交互)", image: agentimage },
      { label: "工艺文件智能体", image: fileagent },
      { label: "集团制度智能体", image: zhiduagent },
    ],
  },
];

let boldLabes = ref([
  "OA办公",
  "客户管理(CRM)",
  "设备管理(PMS)",
  "中航北斗",
  "智慧连油",
  "质量安全管理(QHSE)",
  "智慧注气",
  "视频中心(VCS)",
  "开发需求管理",
  "经营驾驶舱(MC)",
  "项目管理(PM)",
  "鸿盘",
  "智能钻井",
  "供应商管理(SRM)",
]);

const getGreeting = () => {
  const hour = new Date().getHours();
  if (hour < 12) return "早上好";
  if (hour < 18) return "下午好";
  return "晚上好";
};

// 添加轮播数据
const slides = ref([
  {
    image: banner1,
    text: "",
  },
  {
    image: banner2,
    text: "",
  },
  {
    image: banner4,
    text: "智慧平台，赋能高效协同",
  },
]);

// 当前索引
const currentIndex = ref(0);
let slideTimer: ReturnType<typeof setInterval> | null = null;

// 下一页
const nextSlide = () => {
  currentIndex.value = (currentIndex.value + 1) % slides.value.length;
};

const activeNoticeTab = ref<NoticeTabKey>("redHead");
const noticeListMap = ref<Record<NoticeTabKey, NoticeItem[]>>({
  notice: [],
  redHead: [],
});

const newsList = ref([]);

const currentNoticeList = computed(
  () => noticeListMap.value[activeNoticeTab.value] ?? [],
);

const loadHomeData = async () => {
  await loadNoticeList(activeNoticeTab.value);

  if (!userStore.getUser.username) return;

  const [oaRes, newsRes] = await Promise.all([
    getOATasks({
      id: userStore.getUser.username,
      pageNum: 1,
      pageSize: 10,
    }),
    getNews({
      pageNum: 1,
      pageSize: 10,
    }),
  ]);

  oaTasks.value = oaRes.todoList.slice(0, 3);
  newsList.value = newsRes.list.slice(0, 3);
};

const loadNoticeList = async (tabKey: NoticeTabKey) => {
  const requestApi = tabKey === "notice" ? getNotices : getRedHeadFiles;
  const res = await requestApi({
    pageNum: 1,
    pageSize: 10,
  });

  noticeListMap.value[tabKey] = (res?.list || []).slice(0, 3);
};

let currentTabKey = ref<NoticeTabKey>("redHead");
const handleNoticeTabChange = async (tabKey: NoticeTabKey) => {
  activeNoticeTab.value = tabKey;
  currentTabKey.value = tabKey;

  // if (noticeListMap.value[tabKey].length) return;

  if (userStore.getUser.username) {
    await loadNoticeList(tabKey);
  }
};

const handleNoticeMoreClick = () => {
  router.push({
    path: "/notice-redhead",
    query: {
      tabKey: currentTabKey.value,
    },
  });
};

const protectedOpen = (url: string) => {
  if (userStore.getUser.username && getAccessToken()) {
    window.open(url, "_blank");
  } else {
    router.push({ path: "/login" });
  }
};

let dialogVisible = ref(false);
const confirmSrm = async () => {
  dialogVisible.value = false;
  if (userStore.getUser.username && getAccessToken()) {
    const res = await srmLogin({
      username: userStore.getUser.username,
    });

    if (res) {
      window.open(
        `https://srmqas.deepoil.cc/#/mixed-page/view/MXP00048?Authorization=${JSON.parse(res).msg}`,
        "_blank",
      );
    }
  } else {
    router.push({ path: "/login" });
  }
};
const handlePortalAppClick = async (app: PortalApp) => {
  if (!app.label) return;

  if (app.label === "项目管理(PM)") {
    protectedOpen(
      `${import.meta.env.VITE_PMS_URL}/portalLogin?username=${userStore.getUser.username}&source=yyhy`,
    );
  }

  if (app.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 (app.label === "客户管理(CRM)") {
    protectedOpen(
      `https://crm-tencent.xiaoshouyi.com/global/sso/callback/00APEB9EEEA9B2E338B686B7ECFA8585808C.action?token=${getAccessToken()}`,
    );
  }

  if (app.label === "设备管理(PMS)") {
    protectedOpen(
      `${import.meta.env.VITE_PMS_URL}/portalLogin?username=${userStore.getUser.username}`,
    );
  }

  if (app.label === "中航北斗") {
    protectedOpen("https://zhbdgps.cn");
  }

  if (app.label === "智慧连油") {
    protectedOpen(
      `${import.meta.env.VITE_PMS_URL}/portalLogin?username=${userStore.getUser.username}&source=zhly`,
    );
  }

  if (app.label === "智慧注气") {
    protectedOpen(
      `${import.meta.env.VITE_PMS_URL}/portalLogin?username=${userStore.getUser.username}&source=znzq`,
    );
  }

  if (app.label === "视频中心(VCS)") {
    protectedOpen(
      `${import.meta.env.VITE_PMS_URL}/portalLogin?username=${userStore.getUser.username}&source=spzx`,
    );
  }

  if (app.label === "质量安全管理(QHSE)") {
    protectedOpen(
      `${import.meta.env.VITE_PMS_URL}/portalLogin?username=${userStore.getUser.username}&source=qhse`,
    );
  }

  if (app.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 (app.label === "开发需求管理") {
    if (userStore.getUser.username && getAccessToken()) {
      const res = await zentaoSsoLogin({
        username: userStore.getUser.username,
      });
      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" });
    }
  }

  if (app.label === "供应商管理(SRM)") {
    // ElMessageBox.confirm("即将跳转到供应商管理系统，是否继续？", "提示", {
    //   confirmButtonText: "继续",
    //   cancelButtonText: "取消",
    // }).then(async () => {});
    dialogVisible.value = true;
    // if (userStore.getUser.username && getAccessToken()) {
    //   const res = await srmLogin({
    //     username: userStore.getUser.username,
    //   });

    //   if (res) {
    //     window.open(
    //       `https://srmqas.deepoil.cc/#/mixed-page/view/MXP00048?Authorization=${JSON.parse(res).msg}`,
    //       "_blank",
    //     );
    //   }
    // } else {
    //   router.push({ path: "/login" });
    // }
  }

  if (app.label === "智能钻井") {
    if (userStore.getUser.username && getAccessToken()) {
      window.open(`http://172.21.0.224:8001/#/login`, "_blank");
    } else {
      router.push({ path: "/login" });
    }
  }

  if (app.label === "鸿盘") {
    if (userStore.getUser.username && getAccessToken()) {
      window.open(`https://pan.keruioil.com:52180`, "_blank");
    } else {
      router.push({ path: "/login" });
    }
  }
};

async function loginWithDingTalk() {
  const ddCorpId = import.meta.env.VITE_DD_CORPID;
  const ddClientId = import.meta.env.VITE_DD_CLIENTID;

  if (!ddCorpId || !ddClientId) return false;

  return await new Promise<boolean>((resolve) => {
    dd.requestAuthCode({
      corpId: ddCorpId,
      clientId: ddClientId,
      success: async (res: any) => {
        try {
          const { code } = res;
          const response = await axios.post(
            import.meta.env.BASE_URL + "/admin-api/system/auth/h5SocialLogin",
            {
              code,
              type: 20,
              state: new Date().getTime(),
            },
            {
              headers: {
                "Content-Type": "application/json",
                "tenant-id": 1,
              },
            },
          );

          deleteUserCache();
          userStore.resetState();
          authUtil.setToken(response.data.data);
          sessionStorage.removeItem(manualLogoutKey);
          sessionStorage.removeItem(reloginCancelKey);
          await userStore.setUserInfoAction();
          resolve(true);
        } catch (error) {
          console.log("dingTalk login error :>> ", error);
          resolve(false);
        }
      },
      fail: (err: any) => {
        console.log("err :>> ", err);
        resolve(false);
      },
    });
  });
}

async function dingTalkAutoLogin() {
  const ua = window.navigator.userAgent.toLowerCase();

  if (
    (ua.includes("dingtalk") || ua.includes("dingtalkwork")) &&
    !userStore.getUser.username &&
    !getAccessToken()
  ) {
    return await loginWithDingTalk();
  }

  return false;
}

const getTagClass = (tag: string) => {
  return tag === "0"
    ? "bg-[#dbe8ff] text-[#3f74ff]"
    : tag === "1"
      ? "bg-[#ffe1e3] text-[#ff5d66]"
      : tag === "2"
        ? "bg-[#dfe8f3] text-[#6f7f94]"
        : "bg-[#dbe8ff] text-[#3f74ff]";
};

const getTagName = (tag: string) => {
  return tag === "0"
    ? "正常"
    : tag === "1"
      ? "重要"
      : tag === "2"
        ? "紧急"
        : "正常";
};

let oaTasks = ref([]);
onMounted(async () => {
  slideTimer = setInterval(nextSlide, 5000);
  await dingTalkAutoLogin();

  await loadHomeData();
});

const handleNoticeItemClick = async (notice) => {
  const res = await ssoLogin({
    username: userStore.getUser.username,
  });

  if (res) {
    const ua = window.navigator.userAgent.toLowerCase();
    if (ua.includes("dingtalk") || ua.includes("dingtalkwork")) {
      dd.biz.util.openLink({
        url:
          "https://yfoa.keruioil.com/wui/index.html" +
          "?ssoToken=" +
          res +
          "#/main", // 先跳你的 SSO 链接
        onSuccess: () => {
          // 延迟跳目标业务地址（和你原来 setTimeout 逻辑一致）
          setTimeout(() => {
            dd.biz.util.openLink({
              url: `https://yfoa.keruioil.com/spa/document/index.jsp?openAttachment=0&id=${notice.id}`,
            });
          }, 100);
        },
      });
    } else {
      const loading = ElLoading.service({
        lock: true,
        text: "正在跳转，请稍候...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const newTab = window.open("", "_blank");
      newTab.location.href =
        "https://yfoa.keruioil.com/wui/index.html" +
        "?ssoToken=" +
        res +
        "#/main";

      setTimeout(function () {
        newTab.location.href = `https://yfoa.keruioil.com/spa/document/index.jsp?openAttachment=0&id=${notice.id}`;
        setTimeout(() => {
          loading.close();
        }, 500);
      }, 100);
    }
  }
};

const handleTask = async (row) => {
  const res = await ssoLogin({
    username: userStore.getUser.username,
  });

  if (res) {
    const ua = window.navigator.userAgent.toLowerCase();
    if (ua.includes("dingtalk") || ua.includes("dingtalkwork")) {
      dd.biz.util.openLink({
        url:
          "https://yfoa.keruioil.com/wui/index.html" +
          "?ssoToken=" +
          res +
          "#/main", // 先跳你的 SSO 链接
        onSuccess: () => {
          // 延迟跳目标业务地址（和你原来 setTimeout 逻辑一致）
          setTimeout(() => {
            dd.biz.util.openLink({
              url: `https://yfoa.keruioil.com/spa/workflow/static4form/index.html?_rdm=1776063595284#/main/workflow/req?requestid=${row.requestId}`,
            });
          }, 100);
        },
      });
    } else {
      const loading = ElLoading.service({
        lock: true,
        text: "正在跳转，请稍候...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const newTab = window.open("", "_blank");
      newTab.location.href =
        "https://yfoa.keruioil.com/wui/index.html" +
        "?ssoToken=" +
        res +
        "#/main";

      setTimeout(function () {
        newTab.location.href = `https://yfoa.keruioil.com/spa/workflow/static4form/index.html?_rdm=1776063595284#/main/workflow/req?requestid=${row.requestId}`;
        setTimeout(() => {
          loading.close();
        }, 500);
      }, 100);
    }
  }
};

const openConsult = async () => {
  const res = await ssoLogin({
    username: userStore.getUser.username,
  });

  if (res) {
    const ua = window.navigator.userAgent.toLowerCase();
    if (ua.includes("dingtalk") || ua.includes("dingtalkwork")) {
      dd.biz.util.openLink({
        url:
          "https://yfoa.keruioil.com/wui/index.html" +
          "?ssoToken=" +
          res +
          "#/main", // 先跳你的 SSO 链接
        onSuccess: () => {
          // 延迟跳目标业务地址（和你原来 setTimeout 逻辑一致）
          setTimeout(() => {
            dd.biz.util.openLink({
              url: `https://yfoa.keruioil.com/spa/workflow/static4form/index.html?_rdm=1778289187850#/main/workflow/req?iscreate=1&workflowid=488`,
            });
          }, 100);
        },
      });
    } else {
      const loading = ElLoading.service({
        lock: true,
        text: "正在跳转，请稍候...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const newTab = window.open("", "_blank");
      newTab.location.href =
        "https://yfoa.keruioil.com/wui/index.html" +
        "?ssoToken=" +
        res +
        "#/main";

      setTimeout(function () {
        newTab.location.href = `https://yfoa.keruioil.com/spa/workflow/static4form/index.html?_rdm=1778289187850#/main/workflow/req?iscreate=1&workflowid=488`;
        setTimeout(() => {
          loading.close();
        }, 500);
      }, 100);
    }
  }
};

const goNews = () => {
  router.push("/news");
};

onUnmounted(() => {
  if (slideTimer) {
    clearInterval(slideTimer);
    slideTimer = null;
  }
});
</script>

<style scoped>
.portal-home {
  --portal-bg: #050b1a;
  --portal-bg-2: #081326;
  --portal-line: rgba(97, 129, 206, 0.28);
  --portal-card: rgba(10, 19, 43, 0.8);
  --portal-card-2: rgba(12, 24, 52, 0.92);
  --portal-accent: #6e7dff;
  --portal-accent-2: #8d4dff;
  color: #eaf1ff;
  background:
    radial-gradient(
      circle at 18% 12%,
      rgba(79, 82, 221, 0.34),
      transparent 22%
    ),
    radial-gradient(circle at 82% 20%, rgba(28, 95, 255, 0.2), transparent 20%),
    radial-gradient(
      circle at 50% 100%,
      rgba(103, 46, 255, 0.16),
      transparent 28%
    ),
    linear-gradient(180deg, #040814 0%, #060d1d 46%, #040814 100%);
  background-image:
    linear-gradient(rgba(5, 11, 26, 0.62), rgba(5, 11, 26, 0.82)),
    url("../assets//images/bg666.png");
  background-position:
    center center,
    center bottom;
  background-repeat: no-repeat, no-repeat;
  background-size:
    cover,
    100% auto;
  background-attachment: fixed, fixed;
}

.hero-banner {
  position: relative;
  min-height: 310px;
  border: 1px solid rgba(113, 140, 214, 0.16);
  border-radius: 10px;
  background:
    linear-gradient(135deg, rgba(63, 91, 211, 0.32), transparent 32%),
    linear-gradient(180deg, rgba(9, 16, 36, 0.82), rgba(4, 9, 20, 0.9));
  box-shadow:
    0 24px 60px rgba(0, 0, 0, 0.38),
    inset 0 1px 0 rgba(255, 255, 255, 0.06);
  overflow: hidden;
}

.hero-banner::before {
  content: "";
  position: absolute;
  inset: 0;
  background:
    linear-gradient(120deg, rgba(128, 77, 255, 0.14) 0%, transparent 26%),
    radial-gradient(
      circle at 20% 36%,
      rgba(123, 84, 255, 0.22),
      transparent 22%
    ),
    radial-gradient(
      circle at 74% 52%,
      rgba(54, 170, 255, 0.18),
      transparent 24%
    ),
    linear-gradient(
      90deg,
      rgba(255, 255, 255, 0.04),
      transparent 40%,
      rgba(255, 255, 255, 0.02)
    );
  pointer-events: none;
}

.hero-copy {
  position: relative;
  z-index: 2;
}

.hero-script {
  display: none;
}

.hero-text {
  margin-top: 0;
  color: rgba(234, 241, 255, 0.95);
  font-size: 46px;
  font-weight: 800;
  line-height: 1.2;
  letter-spacing: 0.02em;
  text-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
  max-width: 540px;
}

.hero-visual {
  position: absolute;
  inset: 0;
  min-height: 310px;
}

.hero-visual::after {
  content: "";
  position: absolute;
  inset: 0;
  background:
    linear-gradient(90deg, rgba(5, 11, 26, 0.28) 0%, transparent 28%),
    linear-gradient(
      180deg,
      transparent 0%,
      rgba(5, 11, 26, 0.08) 56%,
      rgba(5, 11, 26, 0.28) 100%
    );
  pointer-events: none;
}

.carousel-container {
  position: relative;
  height: 310px;
  overflow: hidden;
}

.platform-block {
  /* display: flex; */
  overflow: hidden;
  border: 1px solid rgba(109, 137, 213, 0.18);
  border-radius: 8px;
  background: linear-gradient(
    180deg,
    rgba(10, 18, 38, 0.92),
    rgba(8, 15, 33, 0.92)
  );
  box-shadow:
    0 16px 34px rgba(0, 0, 0, 0.22),
    inset 0 1px 0 rgba(255, 255, 255, 0.04);
}

.platform-block__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 48px;
  padding: 0 22px 0 24px;
  background: linear-gradient(
    90deg,
    rgba(44, 70, 154, 0.5),
    rgba(18, 28, 62, 0.1)
  );
}

.platform-block__title-wrap {
  display: flex;
  flex-direction: column;
  align-items: baseline;
  gap: 18px;
  min-width: 0;
}

.platform-block__title {
  color: #f4f7ff;
  font-size: 18px;
  font-weight: 800;
  min-width: 0;
  flex: 0 1 auto;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  letter-spacing: 0.02em;
}

.platform-block__subtitle {
  color: rgba(188, 205, 255, 0.82);
  font-size: 13px;
  font-weight: 500;
  flex: 0 0 auto;
  white-space: nowrap;
}

.platform-block__watermark {
  color: rgba(119, 145, 214, 0.24);
  font-size: 42px;
  font-weight: 800;
  line-height: 1;
  letter-spacing: 0.08em;
}

.platform-app {
  display: flex;
  width: 100%;
  min-width: 0;
  min-height: 40px;
  align-items: center;
  justify-content: flex-start;
  gap: 8px;
  border: 1px solid rgba(109, 137, 213, 0.16);
  border-radius: 10px;
  padding: 0 10px;
  background: rgba(17, 25, 48, 0.8);

  font-size: 14px;
  cursor: pointer;

  transition:
    transform 0.2s ease,
    box-shadow 0.2s ease,
    background 0.2s ease;
}

.platform-app:hover {
  transform: translateY(-2px);
  border-color: rgba(133, 163, 255, 0.45);
  box-shadow: 0 10px 26px rgba(34, 54, 110, 0.3);
}

.platform-app--active {
  /* background: linear-gradient(
    90deg,
    rgba(76, 103, 224, 0.2),
    rgba(23, 30, 58, 0.88)
  );
  color: #f4f7ff;
  border-color: rgba(129, 145, 255, 0.44);
  box-shadow: inset 0 0 0 1px rgba(159, 173, 255, 0.08); */
  font-weight: 700;
}

.platform-app--ghost {
  background: rgba(15, 24, 45, 0.82);
  color: rgba(201, 212, 243, 0.9);
}

.platform-app__icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: #79b0ff;
  filter: drop-shadow(0 0 8px rgba(90, 122, 255, 0.24));
}

.platform-app__label {
  min-width: 0;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #b8b9be;
}

.portal-mobile-shortcuts {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 8px;
}

.portal-mobile-shortcut {
  min-width: 0;
  border: 1px solid rgba(116, 145, 223, 0.18);
  border-radius: 12px;
  padding: 10px 8px;
  background: linear-gradient(
    180deg,
    rgba(17, 26, 52, 0.86),
    rgba(10, 16, 32, 0.92)
  );
  color: #dfe8ff;
  font-size: 13px;
  font-weight: 600;
  box-shadow: 0 10px 24px rgba(0, 0, 0, 0.18);
}

.side-card {
  overflow: hidden;
  border: 1px solid rgba(109, 137, 213, 0.16);
  border-radius: 14px;
  background: linear-gradient(
    180deg,
    rgba(10, 18, 38, 0.92),
    rgba(7, 14, 31, 0.94)
  );
  box-shadow:
    0 16px 34px rgba(0, 0, 0, 0.22),
    inset 0 1px 0 rgba(255, 255, 255, 0.04);
}

.side-card--content {
  padding-top: 10px;
}

.side-card__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 20px;
  padding-right: 10px;
  /* border-radius: 999px; */
  /* background: rgba(28, 39, 72, 0.86); */
  border-bottom: 1px solid rgba(109, 137, 213, 0.16);
}

.notice-badge {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 25px;
  min-width: 70px;

  color: #fff;
  font-size: 14px;
}

.news.notice-badge {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 25px;
  min-width: 70px;

  color: #fff;
  font-size: 14px;
  border-bottom: 2px solid #5e45bb;
}

.notice-tabs {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.notice-tab {
  height: 25px;
  min-width: 68px;
  padding: 0 14px;
  border: 0;
  border-radius: 999px;
  background: transparent;
  color: rgba(183, 201, 244, 0.88);
  font-size: 14px;

  cursor: pointer;
  transition:
    background 0.2s ease,
    color 0.2s ease;
}

.notice-tab--active {
  position: relative;
}

.notice-tab--active::before {
  content: "";
  position: absolute;
  left: 50%;
  bottom: -2px;
  width: 90%;
  height: 2px;
  transform: translateX(-50%);
  border-radius: 999px;
  background: linear-gradient(
    to right,
    #5f3abf 0%,
    #7044c5 30%,
    #7044c5 40%,
    rgba(255, 255, 255, 0.7) 50%,
    #7044c5 60%,
    #7044c5 70%,
    #5f3abf 100%
  );
  box-shadow: 0 0 12px rgba(112, 120, 255, 0.95);
}

.notice-badge::after {
  content: "";
  position: absolute;
  top: 0;
  right: -15px;
}

.side-card__more {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border: 0;
  background: transparent;
  color: rgba(187, 203, 245, 0.82);
  cursor: pointer;
  font-size: 12px;
}

.notice-item {
  /* background: rgba(14, 22, 42, 0.88); */
  padding: 8px 14px;
  box-shadow: 0 10px 22px rgba(0, 0, 0, 0.14);
  border-radius: 12px;
}

.notice-item:hover {
  box-shadow: 0 16px 30px rgba(0, 0, 0, 0.22);
  transition: all 0.2s ease;
  transform: translateY(-1px);
}

.notice-item__title,
.notice-item__desc {
  color: rgba(224, 232, 255, 0.9);
  font-size: 13px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
}

.panel-title {
  padding: 0 16px;
  color: #eff4ff;
  font-size: 15px;
  font-weight: 700;
}

.todo-item {
  border: 1px solid rgba(109, 137, 213, 0.12);
  background: rgba(14, 22, 42, 0.88);
  padding: 8px 14px;
  box-shadow: 0 10px 22px rgba(0, 0, 0, 0.14);
}

.todo-item__tag {
  display: inline-flex;
  align-items: center;
  border-radius: 999px;
  padding: 2px 8px;
  font-size: 11px;
  font-weight: 600;
  white-space: nowrap;
}

.news-mini {
  display: flex;
  align-items: center;
  gap: 12px;
  border: 1px solid rgba(109, 137, 213, 0.12);
  background: rgba(14, 22, 42, 0.88);
  padding: 5px 12px;
  box-shadow: 0 10px 22px rgba(0, 0, 0, 0.14);
  border-radius: 12px;
}

.news-mini:hover {
  box-shadow: 0 16px 30px rgba(0, 0, 0, 0.22);
  transition: all 0.2s ease;
  transform: translateY(-1px);
}

.placeholder-panel {
  display: flex;
  height: 100%;
  padding: 16px;
  justify-content: start;
  color: #fff;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 0.08em;
}

@media (max-width: 1279px) {
  .hero-text {
    font-size: 34px;
    max-width: 420px;
  }

  .hero-visual {
    min-height: 260px;
  }
}

@media (max-width: 767px) {
  .platform-block__header {
    padding: 0 16px 0 18px;
  }

  .platform-block__title-wrap {
    gap: 12px;
    flex-wrap: wrap;
  }

  .platform-block__title {
    font-size: 16px;
  }

  .platform-block__subtitle {
    font-size: 12px;
  }

  .platform-block__watermark {
    font-size: 34px;
  }

  .hero-banner {
    min-height: 240px;
  }
  .carousel-container {
    height: 240px;
  }

  .carousel-caption {
    left: 22px;
    right: 22px;
    top: 50%;
    transform: translateY(-50%);
  }

  .hero-text {
    font-size: 24px;
    max-width: 100%;
  }
}

.carousel-indicators {
  display: flex;
  gap: 10px;
  z-index: 30;
}

.carousel-indicators span {
  width: 36px;
  height: 4px;
  border-radius: 999px;
  cursor: pointer;
  transition: all 0.25s ease;
  box-shadow: 0 0 16px rgba(112, 103, 255, 0.35);
}

.carousel-slide {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
}

.hero-visual img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  filter: saturate(1.12) contrast(1.06);
}

.carousel-caption {
  position: absolute;
  left: 80px;
  top: 44%;
  z-index: 2;
  transform: translateY(-50%);
  text-align: left;
}

.carousel-container::before {
  content: "";
  position: absolute;
  inset: auto 0 0;
  height: 120px;
  background: linear-gradient(180deg, transparent, rgba(5, 11, 26, 0.6));
  z-index: 1;
  pointer-events: none;
}

:deep(.portal-home .el-dialog) {
  border-radius: 16px;
}
</style>
