<script setup>
import XTab from '@vue2-client/base-client/components/common/XTab/XTab.vue'
import { ref, computed, useAttrs, useSlots, onMounted } from 'vue'
import { getConfigByName } from '@vue2-client/services/api/common'

const props = defineProps({
  // 标签栏右侧附加区域的配置名（可选）。提供时将自动加载配置并渲染到 tabBar 右侧。
  tabBarExtraConfig: {
    type: String,
    default: undefined
  },
  // 控制标签间距，覆盖内部 XTab 的默认 10px；默认置 0 清除外边距
  tabBarGutter: {
    type: Number,
    default: 0
  }
})

// 兼容多种样式配置
const attrs = useAttrs()
const wrapperClassObject = computed(() => {
  const a = attrs
  const classes = {}

// 通用布尔样式开关（以存在/空字符串/'true' 为真）
const booleanStyleKeys = [
  'hasTopMargin', 'useStyle7', 'useCycle', 'useStyle8', 'out-tab', 'no-underline', 'useStyle9', 'useStyle10'
]
  for (const key of booleanStyleKeys) {
    const val = a[key]
    const truthy = val === true || val === '' || val === 'true'
    if (truthy) classes[`h-tab-${key}`] = true
  }
  return classes
})

// 创建对XTab组件的引用
const xTabRef = ref()

// 获取插槽（避免模板中直接使用 $slots 触发类型检查错误）
const slots = useSlots()
const slotNames = computed(() => {
  try {
    return Object.keys(slots || {})
  } catch (e) {
    return []
  }
})

// 右侧附加区域的动态配置
const extraConfig = ref(null)
const extraItems = computed(() => {
  const cfg = extraConfig.value
  return cfg && cfg.value ? cfg.value : []
})

// 本地异步组件映射（未全局注册时生效）
const localMap = {
  'x-input': () => import('@vue2-client/base-client/components/common/XInput/XInput.vue'),
  'x-select': () => import('@vue2-client/base-client/components/his/XSelect/XSelect.vue'),
  'x-radio': () => import('@vue2-client/base-client/components/his/XRadio/XRadio.vue'),
  'x-buttons': () => import('@vue2-client/base-client/components/common/XButtons/XButtons.vue'),
  'x-time-select': () => import('@vue2-client/base-client/components/his/XTimeSelect/XTimeSelect.vue'),
  'h-buttons': () => import('@vue2-client/base-client/components/common/HIS/HButtons/HButtons.vue')
}

// 从 attrs 中读取 serverName 与 env（保持向后兼容）
const serverName = computed(() => (attrs && attrs.serverName))
const env = computed(() => (attrs && attrs.env) || 'prod')

const loadExtraConfig = (configName) => {
  if (!configName) {
    extraConfig.value = null
    return
  }
  getConfigByName(configName, serverName.value, (res) => {
    extraConfig.value = res
  }, env.value === 'dev')
}

onMounted(() => {
  loadExtraConfig(props.tabBarExtraConfig)
})

// 暴露方法给父组件使用
defineExpose({
  // 为了兼容性，保留getXTabInstance方法
  getXTabInstance: () => xTabRef.value,
})
</script>

<template>
  <div
    class="h-tab-wrapper"
    :class="[wrapperClassObject, extraItems.length > 1 ? 'h-tab-extra-wrapper-multiple' : '']">
    <x-tab
      ref="xTabRef"
      :tabBarGutter="props.tabBarGutter"
      v-bind="$attrs"
      v-on="$listeners"
    >
      <template v-if="extraItems.length" #tabBarExtraContent>
        <!-- 父级可接管渲染；未提供则按配置兜底渲染 -->
        <slot name="tabBarExtraContent" :config="extraConfig" :items="extraItems">
          <div class="h-tab-extra-wrapper">
            <component
              v-for="(item, idx) in extraItems"
              :is="localMap[item.slotType] || item.slotType"
              :key="idx"
              :ref="item.slotRef || `extra_${idx}`"
              :serviceName="item.serviceName || serverName"
              :serverName="item.serviceName || serverName"
              :queryParamsName="item.slotConfig"
              :env="env"
              v-on="$listeners"
              v-bind="item.attrs"
            />
          </div>
        </slot>
      </template>
      <template v-for="name in slotNames" #[name]="slotData">
        <slot :name="name" v-bind="slotData" />
      </template>
    </x-tab>
  </div>
</template>

<style scoped lang="less">
.h-tab-wrapper {
  width: 100%;
  overflow: visible !important;

  // 基础样式
  :deep(.ant-tabs-tab-next) {
    display: none;
  }
  :deep(.ant-tabs-nav-wrap) {
    margin-top: 18px;
    margin-bottom: 0;
  }
  :deep(.ant-tabs-nav) {
    // 去除导航容器默认左右内边距，避免收缩时左侧多出一截
    .ant-tabs-nav-container,
    .ant-tabs-nav-scroll {
      margin: 0px;
    }

    // 移除左右切换箭头带来的占位
    .ant-tabs-tab-prev,
    .ant-tabs-tab-next {
      display: none !important;
      width: 0 !important;
    }
    .ant-tabs-tab-next-icon {
      display: none;
    }
    .ant-tabs-tab {
      background-color: transparent;
      border-radius: 6px 6px 0 0;
      color: #5D5C5C;
      font-weight: bold;
      min-width: 134px;
      width: auto;
      font-size: 18px;
      line-height: 26px;
      font-family: "Source Han Sans";
      transition: all 0.3s;
      height: 32px;
      text-align: center;
      margin: 0 !important;
      padding: 0 12px !important;
    }
    .ant-tabs-tab-active {
      background-color: #0057FE;
      color: #ffffff;
      min-width: 134px;
      width: auto;
      line-height: 26px;
      height: 32px;
      text-align: center;
      margin: 0 !important;
      padding: 0 12px !important;
    }
  }

  :deep(.ant-tabs-bar) {
    border-bottom: 2px solid #0057FE;
    margin: 0px 0px;
    width: 100%;
    height: 50px;
  }

  // 滚动状态下的容器左右内边距清零，避免左侧多出一截
  :deep(.ant-tabs-nav-container-scrolling) {
    padding-left: 0 !important;
    padding-right: 0 !important;
  }

  :deep(.ant-tabs-tab-arrow-show) {
    display: none;
  }

  :deep(.ant-tabs-ink-bar) {
    background-color: transparent;
    bottom: 0px;
    display: none;
    height: 0;
  }

  :deep(.ant-tabs-tab-prev-icon-target) {
    display: none;
  }

  // 带顶部边距的样式
  &.h-tab-hasTopMargin {
    :deep(.ant-tabs-nav) {
      margin-top: 6px;
    }

    :deep(.ant-tabs-bar) {
      margin: 0 6px;
    }

    :deep(.ant-card-body) {
      padding: 6px 0;

      .ant-card-body {
        padding: 6px;
      }
    }
  }

  // 通用样式7：细下划线、透明背景、可配置宽度
  &.h-tab-useStyle7 {
    :deep(.ant-tabs-tab-next),
    :deep(.ant-tabs-tab-prev-icon-target),
    :deep(.ant-tabs-tab-next-icon) { display: none; }

    :deep(.ant-tabs-bar) { border-bottom: 2px solid transparent; }

    :deep(.ant-tabs-ink-bar) {
      display: block !important;
      background-color: #0057FE !important;
      bottom: 3px !important;
      height: 2px !important;
      /* 让 antd 自身计算宽度，与页签宽度匹配 */
      margin-left: 0 !important;
    }

    :deep(.ant-tabs-nav-wrap) {
      margin-top: 0;
      padding-left: 0 !important; // 消除整个Tab的左间距
      padding-right: 0 !important; // 消除整个Tab的右间距
    }

    :deep(.ant-tabs-nav-container) {
      padding-left: 0 !important; // 确保容器也没有左右间距
      padding-right: 0 !important;
    }

    :deep(.ant-tabs-nav) {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      .ant-tabs-tab {
        background-color: transparent;
        border-radius: 0;
        color: #333333;
        font-weight: 500;
        /* 自适应宽度，允许通过变量覆盖最小宽度 */
        min-width: var(--tab-min-width, 96px);
        width: auto;
        padding: 0 12px 6px;
        font-size: 16px;
        line-height: 10px;
        font-family: "Source Han Sans";
        transition: all 0.3s;
        height: 40px;
        text-align: center;
        margin-right: 0 !important;
      }
      .ant-tabs-tab-active {
        background-color: transparent;
        color: #0057FE;
        font-weight: 600;
        width: auto;
        padding: 0 12px 6px;
        line-height: 10px;
        height: 40px;
        text-align: center;
      }
    }

    // 可选：标签左侧圆点
    &.h-tab-useCycle {
      :deep(.ant-tabs-tab) {
        position: relative;
        padding-left: 18px !important;
        margin-right: 20px !important;
        display: inline-flex !important; // 使用inline-flex保持水平布局
        align-items: center !important; // 确保内容垂直居中
        line-height: normal !important; // 重置line-height避免冲突
        vertical-align: top !important; // 确保垂直对齐
      }
      :deep(.ant-tabs-tab::before) {
        content: "" !important;
        position: absolute !important;
        left: 0 !important;
        top: 50% !important;
        transform: translateY(-50%) !important;
        width: 12px !important;
        height: 12px !important;
        background: #0057FE !important;
        border-radius: 50% !important;
        display: block !important;
        z-index: 1 !important; // 确保圆点在最上层
      }
      :deep(.ant-tabs-nav) {
        display: flex !important;
        flex-direction: row !important; // 明确指定水平方向
        flex-wrap: nowrap !important;
        align-items: center !important; // 确保导航栏垂直居中
      }
    }
  }
  // 用户词条使用样式
  &.h-tab-useStyle8 {
    :deep(.ant-tabs-tab-next),
    :deep(.ant-tabs-tab-prev-icon-target),
    :deep(.ant-tabs-tab-next-icon) {
      display: none;
    }

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

    // Make the main Ant Design tabs container a flex column to arrange tab bar and content vertically
    :deep(.ant-tabs) {
      display: flex !important;
      flex-direction: column !important; // 确保选项卡栏在顶部，内容区域在下方
      height: auto !important; // 高度自适应
    }

    :deep(.ant-tabs-bar) {
      border-bottom: 1px solid #d9d9d9; // 底部边框
      border-right: none; // 移除右侧边框
      margin-right: 0 !important; // 移除重叠修复
      flex-shrink: 1 !important; // 允许收缩
      height: auto !important; // 高度自适应
      margin-bottom: 0px !important;
    }

    :deep(.ant-tabs-content) {
      flex: none !important; // 移除 flex: 1，允许内容区域自然流淌
    }

    :deep(.ant-tabs-nav) {
      .ant-tabs-nav-container,
      .ant-tabs-nav-wrap,
      .ant-tabs-nav-scroll,
      & > div:first-child {
        display: flex !important;
        flex-direction: row !important;
        flex-wrap: nowrap !important; // 确保不换行
        width: 100% !important; // 占据全部宽度
        height: auto !important;
      }

      height: auto !important; // 高度自适应内容
      width: 100% !important; // 确保容器占据全部宽度

      .ant-tabs-tab {
        flex: 1 !important; // 宽度等分布局
        margin-right: 0 !important;
        margin-bottom: 0 !important; // 移除底部间距
        border-top: 1px solid #d9d9d9;
        border-left: 1px solid #d9d9d9;
        border-bottom: 1px solid #d9d9d9; // 所有选项卡都有底部边框
        border-right: none; // 默认没有右边框
        &:last-child {
          border-right: 1px solid #d9d9d9; // 最后一个选项卡有右边框
        }
        border-radius: 0; // 默认无圆角，避免中间相邻处出现圆角
        background-color: #f5f5f5;
        color: #333333;
        font-weight: 500;
        font-size: 16px;
        height: 40px; // 固定高度
        width: auto !important; // 移除固定宽度，以便等分
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0;
      }
      // 首项：仅左侧圆角
      .ant-tabs-tab:first-child {
        border-top-left-radius: 10px;
        border-bottom-left-radius: 10px;
      }
      // 末项：仅右侧圆角
      .ant-tabs-tab:last-child {
        border-top-right-radius: 10px;
        border-bottom-right-radius: 10px;
      }
      .ant-tabs-tab-active {
        border-bottom: 1px solid transparent; // 激活时隐藏底部边框，与 ant-tabs-bar 的边框衔接
        background-color: #0057FE;
        color: #ffffff;
        font-weight: 600;
      }
    }
    :deep(.ant-tabs-ink-bar) {
      display: none; // 隐藏下划线
    }
  }
  &.h-tab-extra-wrapper-multiple {
    :deep(.h-tab-extra-wrapper){
      display: flex;
      justify-content: end;
      gap: 8px;
    }
    :deep(.x-radio-group){
      height: 32px;
    }
    :deep(.x-radio-item){
      height: 32px;
      display: flex;
      align-items: center;
      margin-bottom: 0px;
    }
    :deep(.ant-tabs-tab){
      height: 34px;
    }
    :deep(.ant-tabs-nav-container){
      padding-top: 2px;
    }
    :deep(.ant-tabs-extra-content){
      line-height: 0px !important;
    }
  }

  &.h-tab-out-tab {
    :deep(.ant-tabs-nav-wrap) {
      margin-top: 0px !important;
      margin-bottom: 0px !important;
    }
    :deep(.ant-tabs-nav) {
      margin-bottom: 0px !important;
    }
    :deep(.ant-tabs-nav-container) {
      padding-top: 0px !important;
      padding-bottom: 0px !important;
    }

    :deep(.ant-tabs-bar) {
      margin-top: 0px !important;
      margin-bottom: 0px !important;
      height: auto !important;
      min-height: 0px !important;
    }

    :deep(.ant-tabs-content) {
      margin-top: 0px !important;
    }
  }

  // 无下划线样式：隐藏底部指示器线条和边框
  &.h-tab-no-underline {
    :deep(.ant-tabs-bar) {
      border-bottom: none !important;
    }
    :deep(.ant-tabs-ink-bar) {
      display: none !important;
    }
  }

  // 样式9：圆角卡片式标签（带边框、居中文字、字体切换）
  &.h-tab-useStyle9 {
    :deep(.ant-tabs-tab-next),
    :deep(.ant-tabs-tab-prev-icon-target),
    :deep(.ant-tabs-tab-next-icon) { display: none; }

    // 保持 ant-tabs 为 column 布局
    :deep(.ant-tabs) {
      display: flex !important;
      flex-direction: column !important;
      height: auto !important;
      width: 100% !important;
    }

    // 移除 a-card 的默认样式影响
    :deep(.ant-card) {
      overflow: visible !important;
      width: 100% !important;
    }
    :deep(.ant-card-body) {
      padding: 0 !important;
      overflow: visible !important;
    }

    :deep(.ant-tabs-bar) {
      border-bottom: none !important;
      flex-shrink: 0 !important;
      height: auto !important;
      margin-bottom: 0 !important;
      width: 100% !important;
      overflow: visible !important;
    }

    :deep(.ant-tabs-content) {
      flex: 1 !important;
      height: auto !important;
      overflow: visible !important;
    }

    :deep(.ant-tabs-tabpane) {
      overflow: visible !important;
      display: block !important;
    }

    :deep(.ant-tabs-tabpane-active) {
      overflow: visible !important;
    }

    // 禁用切换动画，避免抖动
    :deep(.ant-tabs) {
      transition: none !important;
    }
    :deep(.ant-tabs-tabpane) {
      transition: none !important;
    }

    :deep(.ant-tabs-nav-wrap) {
      margin: 0 !important;
      padding: 0 !important;
      overflow: visible !important;
      position: relative !important;
      display: block !important;
    }

    :deep(.ant-tabs-nav-container) {
      padding: 0 !important;
      overflow: visible !important;
      display: block !important;
    }

    :deep(.ant-tabs-nav) {
      display: flex !important;
      flex-direction: row !important;
      flex-wrap: nowrap !important;
      width: auto !important;
      max-width: 100% !important;
      height: auto !important;
      margin: 0 !important;
      overflow: visible !important;

      .ant-tabs-tab {
        flex: none;
        width: auto;
        min-width: 100px;
        box-sizing: border-box;
        border: 1px solid #E5E9F0;
        border-radius: 6px;
        background: #FFFFFF;
        color: #333333;
        font-family: "Source Han Sans";
        font-size: 18px;
        font-weight: bold;
        line-height: 32px;
        height: 32px;
        text-align: center;
        margin: 0 !important;
        padding: 0 16px !important;
        overflow: hidden !important;
      }
      .ant-tabs-tab-active {
        background-color: #0057FE;
        color: #ffffff;
        font-weight: bold;
        border: 1px solid #0057FE;
      }
    }

    :deep(.ant-tabs-ink-bar) {
      display: none;
    }
  }
  // 样式10：无下划线、左侧绿色圆点、字体样式切换
  &.h-tab-useStyle10 {
    :deep(.ant-tabs-tab-next),
    :deep(.ant-tabs-tab-prev-icon-target),
    :deep(.ant-tabs-tab-next-icon) { display: none; }

    :deep(.ant-tabs-bar) {
      border-bottom: none !important;
    }

    :deep(.ant-tabs-ink-bar) {
      display: none !important;
    }

    :deep(.ant-tabs-nav-wrap) {
      margin-top: 0;
      padding-left: 0 !important;
      padding-right: 0 !important;
    }

    :deep(.ant-tabs-nav-container) {
      padding-left: 0 !important;
      padding-right: 0 !important;
    }

    :deep(.ant-tabs-nav) {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      .ant-tabs-tab {
        position: relative;
        background-color: transparent;
        border-radius: 0;
        color: #313131;
        font-family: "Source Han Sans";
        font-size: 16px;
        font-weight: bold;
        line-height: normal;
        letter-spacing: 0em;
        font-feature-settings: "kern" on;
        font-variation-settings: "opsz" auto;
        width: auto;
        padding: 0 12px 6px;
        padding-left: 18px !important;
        transition: all 0.3s;
        height: 40px;
        text-align: center;
        margin-right: 0px !important;
        display: inline-flex !important;
        align-items: center;
        vertical-align: top;
      }
      .ant-tabs-tab::before {
        content: "" !important;
        position: absolute !important;
        left: 0 !important;
        top: 50% !important;
        transform: translateY(-50%) !important;
        width: 8px !important;
        height: 8px !important;
        background: #0057FE !important;
        border-radius: 50% !important;
        display: block !important;
        z-index: 1 !important;
      }
      .ant-tabs-tab-active {
        background-color: transparent;
        color: #0057FE;
        font-weight: bold;
        width: auto;
        padding: 0 12px 6px;
        padding-left: 18px !important;
        height: 40px;
        text-align: center;
      }
      .ant-tabs-tab-active::before {
        background: #0057FE !important;
      }
    }
  }
}
</style>
