<template>
  <div class="work-tab-container">
    <div class="work-tabs">
      <a-tabs v-model:activeKey="activeKey" type="editable-card" :hide-add="true" @edit="onEdit" @change="onChange">
        <a-tab-pane v-for="tab in tabs" :key="tab.key" :tab="tab.title" :closable="tab.closable" />
      </a-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick, defineExpose, defineProps } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import CurdWindowResourceV2 from '../api/dic/CurdWindowResourceV2.js';
import { menuClickedEvent } from '../common/eventBus.js';
import { Uuid } from 'pc-component-v3';

const props = defineProps({
  menuWidth: {
    type: Number,
    default: 230,
  },
});

const router = useRouter();
const route = useRoute();

// 标签页数组
const tabs = ref([
  {
    key: '/desktop/dashboard',
    title: '首页',
    path: '/desktop/dashboard',
    closable: false, // 首页不可关闭
  },
]);

// 当前激活的标签页
const activeKey = ref('/desktop/dashboard');

// 菜单节点映射表 - 存储路径与菜单节点的对应关系
const pathMenuMap = ref({});

// 固定菜单路由标题（非动态菜单项）
const STATIC_ROUTE_TITLES = {
  '/desktop/formCenter': 'OA审批',
};

// 获取不含 query 的路径，用于标题解析等
const getPathname = fullPath => fullPath.split('?')[0];

// 解析 query 参数
const parseQuery = fullPath => {
  const queryIndex = fullPath.indexOf('?');
  if (queryIndex < 0) {
    return {};
  }
  const params = {};
  new URLSearchParams(fullPath.slice(queryIndex + 1)).forEach((value, key) => {
    params[key] = value;
  });
  return params;
};

// 获取标签页稳定标识（忽略 uuid 等每次跳转都会变的参数）
const getTabIdentity = fullPath => {
  const pathname = getPathname(fullPath);
  if (
    pathname.includes('/desktop/window1/')
    || pathname.includes('/desktop/window/')
    || pathname.includes('/desktop/sheetWindow/')
  ) {
    return pathname;
  }
  if (pathname === '/desktop/launch') {
    const query = parseQuery(fullPath);
    if (query.key) {
      return `${pathname}?key=${query.key}`;
    }
  }
  return fullPath;
};

// 根据路由同步当前激活的标签
const syncActiveTab = fullPath => {
  const tabIdentity = getTabIdentity(fullPath);
  const existTab = tabs.value.find(
    tab => tab.key === tabIdentity || getTabIdentity(tab.path) === tabIdentity,
  );
  if (existTab) {
    activeKey.value = existTab.key;
  }
};

// 规范化并去重本地恢复的标签页
const normalizeTabs = parsedTabs => {
  const tabMap = new Map();
  parsedTabs.forEach(tab => {
    const path = tab.path || tab.key;
    const identity = getTabIdentity(path);
    if (!tabMap.has(identity)) {
      tabMap.set(identity, {
        ...tab,
        key: identity,
        path: path,
      });
    }
  });
  return Array.from(tabMap.values());
};

// 初始化标签页
onMounted(() => {
  // 尝试从本地存储中恢复标签页
  const savedTabs = localStorage.getItem('workTabs');
  if (savedTabs) {
    try {
      const parsedTabs = JSON.parse(savedTabs);
      if (Array.isArray(parsedTabs) && parsedTabs.length > 0) {
        // 确保首页总是存在
        if (!parsedTabs.some(tab => tab.path === '/desktop/dashboard')) {
          parsedTabs.unshift({
            key: '/desktop/dashboard',
            title: '首页',
            path: '/desktop/dashboard',
            closable: false,
          });
        }
        tabs.value = normalizeTabs(parsedTabs);
        saveTabsToLocalStorage();
      }
    } catch (e) {
      console.error('恢复标签页失败', e);
    }
  }

  // 如果当前路由不是首页，添加当前路由的标签页
  if (route.path !== '/desktop/dashboard') {
    setTimeout(() => {
      addTab(route.fullPath);
    }, 100);
  }
});

// 添加标签页方法
const addTab = async fullPath => {
  const tabIdentity = getTabIdentity(fullPath);
  // 如果标签页已存在，则激活该标签页
  const existTab = tabs.value.find(
    tab => tab.key === tabIdentity || getTabIdentity(tab.path) === tabIdentity,
  );
  if (existTab) {
    activeKey.value = existTab.key;
    if (existTab.path !== fullPath) {
      existTab.path = fullPath;
      saveTabsToLocalStorage();
    }
    return;
  }

  // 尝试获取菜单标题
  let title = await getMenuTitle(fullPath);

  if (title) {
    // 异步获取标题期间可能已添加，再次检查
    const existAfter = tabs.value.find(
      tab => tab.key === tabIdentity || getTabIdentity(tab.path) === tabIdentity,
    );
    if (existAfter) {
      activeKey.value = existAfter.key;
      return;
    }

    // 创建新标签页（key 使用稳定标识，path 保留最近一次完整路径）
    const newTab = {
      key: tabIdentity,
      title: title,
      path: fullPath,
      closable: true, // 非首页标签可以关闭
    };

    tabs.value.push(newTab);
    activeKey.value = tabIdentity;

    // 保存标签页到本地存储
    saveTabsToLocalStorage();
  }

};

// 获取菜单标题
const getMenuTitle = async fullPath => {
  const path = getPathname(fullPath);
  // 如果有缓存的菜单信息，直接使用
  if (pathMenuMap.value[fullPath]) {
    return pathMenuMap.value[fullPath].title;
  }
  if (pathMenuMap.value[path]) {
    return pathMenuMap.value[path].title;
  }

  // 处理不同类型的路由
  if (path.includes('/desktop/window/') || path.includes('/desktop/window1/')) {
    const windowNo = extractWindowNo(path);
    if (windowNo) {
      try {
        const res = await CurdWindowResourceV2.uniqueByNoAccessControl(windowNo);
        if (res.errorCode === 0 && res.data) {
          return res.data.name;
        }
      } catch (error) {
        console.error('获取窗口标题失败', error);
      }
    }
  } else if (path.includes('/desktop/sheetWindow/')) {
    const windowNo = extractWindowNo(path);
    if (windowNo) {
      // 这里可以添加获取SheetWindow标题的逻辑
      return `表格窗口-${windowNo}`;
    }
  } else if (path.includes('/desktop/info/')) {
    const infoWindowNo = extractWindowNo(path);
    if (infoWindowNo) {
      // 这里可以添加获取Info窗口标题的逻辑
      return `信息窗口-${infoWindowNo}`;
    }
  } else if (STATIC_ROUTE_TITLES[path]) {
    return STATIC_ROUTE_TITLES[path];
  }

  return '';
};

// 从路径中提取窗口编号
const extractWindowNo = path => {
  const segments = path.split('/');
  for (let i = 0; i < segments.length; i++) {
    if (segments[i] === 'window' || segments[i] === 'window1' || segments[i] === 'sheetWindow' || segments[i] === 'info') {
      return segments[i + 1]?.split('?')[0];
    }
  }
  return null;
};

// 编辑标签页（关闭）
const onEdit = (targetKey, action) => {
  if (action === 'remove') {
    removeTab(targetKey);
  }
};

// 移除标签页
const removeTab = targetKey => {
  // 找到当前关闭的标签页索引
  const targetIndex = tabs.value.findIndex(tab => tab.key === targetKey);

  // 从数组中移除该标签页
  tabs.value = tabs.value.filter(tab => tab.key !== targetKey);

  // 如果关闭的是当前激活的标签页，则需要激活其他标签页
  if (targetKey === activeKey.value) {
    // 如果关闭的是最后一个标签页，则激活前一个标签页
    if (targetIndex === tabs.value.length) {
      activeKey.value = tabs.value[tabs.value.length - 1].key;
    } else {
      // 否则激活后一个标签页
      activeKey.value = tabs.value[targetIndex].key;
    }
    console.log(activeKey.value, 'activeKey.value');
    // 跳转到新激活标签页对应的路由
    router.push(getTabRoutePath(activeKey.value));
  }

  // 保存标签页到本地存储
  saveTabsToLocalStorage();
};

// 获取标签页跳转路径（window/window1 每次打开刷新 uuid，其余保留 query）
const getTabRoutePath = tabKeyOrPath => {
  const pathname = getPathname(tabKeyOrPath);
  if (
    pathname.includes('/desktop/window1/')
    || pathname.includes('/desktop/window/')
    || pathname.includes('/desktop/sheetWindow/')
  ) {
    return pathname + '?uuid=' + Uuid.createUUID();
  }
  return tabKeyOrPath;
};

// 切换标签页
const onChange = newActiveKey => {
  activeKey.value = newActiveKey;
  router.push(getTabRoutePath(newActiveKey));
};

// 保存标签页到本地存储
const saveTabsToLocalStorage = () => {
  try {
    localStorage.setItem('workTabs', JSON.stringify(tabs.value));
  } catch (e) {
    console.error('保存标签页失败', e);
  }
};

// 监听菜单点击事件，添加菜单信息到pathMenuMap
watch(menuClickedEvent, event => {
  if (event && event.path && event.menuInfo) {
    pathMenuMap.value[event.path] = event.menuInfo;
    pathMenuMap.value[getPathname(event.path)] = event.menuInfo;
  }
}, { deep: true, immediate: true });


// 监听路由变化，同步或添加标签页
watch(
  () => route.fullPath,
  newFullPath => {
    // 有一些特殊路由可能不需要添加标签页，可以在这里过滤
    const ignorePaths = ['/login', '/loginNode', '/loginGraphic'];
    const pathname = getPathname(newFullPath);
    if (!ignorePaths.includes(pathname)) {
      nextTick(() => {
        setTimeout(() => {
          syncActiveTab(newFullPath);
          addTab(newFullPath);
        }, 100);
      });
    }
  },
);

watch(
  () => props.menuWidth,
  newWidth => {
    nextTick(() => {
      const workTabContainer = document.querySelector('.work-tab-container');
      if (workTabContainer) {
        setTimeout(() => { 
          workTabContainer.style.width = `calc(100% - 20px - ${newWidth}px)`;
        });
      }
    });
  },
  { immediate: true },
);

// 供外部组件调用，用于添加带有菜单信息的标签页
const addTabWithMenuInfo = (fullPath, menuInfo) => {
  // 缓存菜单信息（同时缓存含 query 与不含 query 的 key）
  const menuData = {
    title: menuInfo.title || menuInfo.name || '',
    menuNodeType: menuInfo.menuNodeType,
    no: menuInfo.no,
  };
  pathMenuMap.value[fullPath] = menuData;
  pathMenuMap.value[getPathname(fullPath)] = menuData;

  // 添加标签页
  addTab(fullPath);
};

// 暴露方法给其他组件使用
defineExpose({
  addTabWithMenuInfo,
});
</script>

<style scoped>
.work-tab-container {
  width: calc(100% - 20px - 230px);
  background-color: #fff;
  padding: 0;
  position: fixed;
  top: 50px;
  right: 0;
  z-index: 10;
}

.work-tabs {
  overflow-x: auto;
  overflow-y: hidden;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE and Edge */
}

.work-tabs::-webkit-scrollbar {
  display: none;
  /* Chrome, Safari, Opera */
}

/* 添加额外的样式来确保内容区域不被遮挡 */
:deep(.ant-tabs) {
  height: 40px;
  /* 设置固定高度 */
}

:deep(.ant-tabs-nav) {
  margin-bottom: 0;
}

:deep(.ant-tabs-nav-wrap) {
  flex: 1;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

:deep(.ant-tabs-nav-wrap::-webkit-scrollbar) {
  display: none;
}

:deep(.ant-tabs-tab) {
  padding: 6px 16px !important;
}

:deep(.ant-tabs-tab-btn) {
  transition: all 0.3s;
}

:deep(.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn) {
  color: #1890ff;
  font-weight: 500;
}

:deep(.ant-tabs-extra-content) {
  line-height: 44px;
}
</style>