<script setup >
import XButtons from '@vue2-client/base-client/components/common/XButtons/XButtons.vue'
import { ref, computed, useAttrs, nextTick, onMounted } from 'vue'

const props = defineProps({
  // HButtons特有的属性
  buttonStyle: {
    type: String,
    default: 'button24'
  }
})

const emit = defineEmits(['update:activeIndex', 'activeChange', 'configEnd'])

// 内部 XButtons 实例引用
const xButtonsRef = ref()

// useStyle10模式下激活按钮的索引（从0开始）
const activeIndex = ref(0)

// 兼容多种样式配置
const attrs = useAttrs()

// 判断是否使用 useStyle10 模式
const isUseStyle10 = computed(() => {
  return props.buttonStyle === 'useStyle10' || attrs.useStyle10 === true || attrs.useStyle10 === '' || attrs.useStyle10 === 'true'
})

const wrapperClassObject = computed(() => {
  const a = attrs
  const classes = {}

  // 通用布尔样式开关（以存在/空字符串/'true' 为真）
  const booleanStyleKeys = [
    'max-width200',
    'width173',
    'button_refresh',
    'border', 'no-style',
    'fill-container',
    'no-boder-style',
    'form-inline',
    'one-button-style', // 一个按钮样式，占满整个宽度
    'useStyle10' // 左侧蓝色圆点指示器样式
  ]
  for (const key of booleanStyleKeys) {
    const val = a[key]
    const truthy = val === true || val === '' || val === 'true'
    if (truthy) classes[`h-buttons-${key}`] = true
  }
  return classes
})

// 获取内部按钮元素列表
const getButtonElements = () => {
  const xEl = xButtonsRef.value?.$el
  if (!xEl) return []
  return Array.from(xEl.querySelectorAll('.ant-btn'))
}

// 设置按钮激活状态
const setActiveState = (btn, isActive) => {
  if (!btn) return
  if (isActive) {
    btn.classList.add('h-btn-active')
    // 使用内联样式确保颜色生效
    btn.style.color = '#0057FE'
  } else {
    btn.classList.remove('h-btn-active')
    // 清除内联样式
    btn.style.color = ''
  }
}

// 清除所有按钮的激活样式
const clearAllActiveStyles = () => {
  const buttons = getButtonElements()
  buttons.forEach(btn => {
    setActiveState(btn, false)
  })
}

// 设置指定索引按钮为激活状态
const setActiveButton = (index) => {
  const buttons = getButtonElements()
  clearAllActiveStyles()

  if (buttons[index]) {
    setActiveState(buttons[index], true)
  }
}

// 事件委托：处理按钮点击
const handleButtonClick = (event) => {
  if (!isUseStyle10.value) return

  // 查找被点击的按钮元素
  const target = event.target.closest('.ant-btn')
  if (!target) return

  const buttons = getButtonElements()
  const index = buttons.indexOf(target)

  if (index === -1) return


  // 更新激活索引
  activeIndex.value = index
  emit('update:activeIndex', index)
  emit('activeChange', index)

  // 更新按钮样式
  clearAllActiveStyles()
  setActiveState(buttons[index], true)
}

// 初始化 useStyle10 样式（带重试机制）
const initUseStyle10 = (retryCount = 0) => {

  if (!isUseStyle10.value) {
    return
  }

  const buttons = getButtonElements()


  // 如果没有找到按钮，重试最多10次
  if (buttons.length === 0 && retryCount < 10) {
    setTimeout(() => {
      initUseStyle10(retryCount + 1)
    }, 100)
    return
  }

  if (buttons.length === 0) {

    return
  }

  // 设置第一个按钮为激活状态
  clearAllActiveStyles()
  setActiveState(buttons[0], true)
}

// 监听 XButtons 配置结束，初始化激活状态
const handleConfigEnd = async () => {
  await nextTick()
  initUseStyle10()
  emit('configEnd')
}

// 在挂载时也尝试初始化（作为备用方案）
onMounted(() => {
  setTimeout(() => {
    initUseStyle10()
  }, 300)
})

// 暴露方法：获取内部 XButtons 实例
defineExpose({
  getXButtonsInstance: function () { return xButtonsRef.value },
  /** 等待配置结束的异步方法，委托给内部 XButtons */
  waitConfigEnd: () => xButtonsRef.value?.waitConfigEnd?.() ?? Promise.resolve(),
  /** 获取当前激活按钮索引 */
  getActiveIndex: () => activeIndex.value,
  /** 设置激活按钮索引 */
  setActiveIndex: (index) => {
    activeIndex.value = index
    setActiveButton(index)
  },
  /** 获取当前激活按钮元素 */
  getActiveButton: () => {
    const buttons = getButtonElements()
    return buttons[activeIndex.value]
  }
})
</script>

<template>
  <div
    class="h-buttons-wrapper"
    :class="[
      `h-buttons-${buttonStyle}`,
      wrapperClassObject
    ]"
    @click="handleButtonClick"
  >
    <x-buttons
      ref="xButtonsRef"
      v-bind="$attrs"
      v-on="$listeners"
      @configEnd="handleConfigEnd"
    >
      <template v-for="(_, name) in $slots" #[name]="slotData">
        <slot :name="name" v-bind="slotData" />
      </template>
    </x-buttons>
  </div>
</template>

<style scoped lang="less">
.h-buttons-wrapper {
  // 基础样式
  :deep(.ant-btn-group) {
    .ant-btn {
      border-radius: 6px;
      background-color: #FFFFFF;
      border: 1px solid #9499A0;
      color: #313131;
      font-weight: normal;
      letter-spacing: 0em;
      width: 110px;
      font-size: 16px;
      font-family: "Source Han Sans";
      line-height: normal;
      margin-right: 25px;
      height: 32px;
    }
  }
  // button24样式
  &.h-buttons-button24 {
    :deep(.ant-btn-group) {
      .ant-btn {
        border: 1px solid #CDCDCD;
        color: #5D5C5C;
        // top: -100px;
        width: fit-content;
        min-width: 110px;
      }
    }
  }
  // button23样式
  &.h-buttons-button23 {
    :deep(.ant-btn-group) {
      .ant-btn {
        border: none;
        padding: 0 !important;
        color: #FFFFFF;
        border-radius: 50%;
        background-color: #1890FF;
        margin-left: 10px;
        top: -88px;
        width: 30px;
        height: 30px;
      }
    }
  }
  // +号样式（共享基础样式）
  &.h-buttons-table-height-button23,
  &.h-buttons-table-height-button23-no-transform {
    :deep(.ant-btn-group) {
      display: inline-flex;
      align-items: center;
      height: 100%;

      .ant-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border: none;
        padding: 0 !important;
        color: #FFFFFF;
        border-radius: 50%;
        background-color: #1890FF;
        margin-left: 10px;
        width: 30px;
        height: 30px;
      }
    }
  }
  // 仅在有分页的场景上移
  &.h-buttons-table-height-button23 {
    :deep(.ant-btn-group) {
      .ant-btn { transform: translateY(-100%); }
    }
  }
  // 居中+悬停高亮的新样式
  &.h-buttons-plus-center {
    :deep(.ant-btn-group) {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 16px;

      .ant-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #CDCDCD;
        color: #5D5C5C;
        min-width: 110px;
        transition: background-color 0.2s ease, border-color 0.2s ease, color 0.2s ease;

        &:hover {
          background-color: #0057FE;
          border-color: #0057FE;
          color: #FFFFFF;
        }
        /* 支持通过 data-type 改变悬停颜色 */
        &[data-type='success']:hover {
          background-color: #34C76E;
          border-color: #34C76E;
          color: #FFFFFF;
        }
      }
    }
  }
  // 按钮布局样式公共部分
  &.h-buttons-button-left,
  &.h-buttons-button-center,
  &.h-buttons-button-right,
  &.h-buttons-button-space-between {
    :deep(.ant-btn-group) {
      width: 100%;
      display: flex;
      flex-wrap: nowrap;
      .ant-btn {
        border: 1px solid #CDCDCD;
        color: #5D5C5C;
        white-space: nowrap;
        overflow: hidden;
        margin-right: 0px;
        text-overflow: ellipsis;
      }
    }
  }
  &.h-buttons-max-width200 {
    :deep(.ant-btn) {
      max-width: 200px !important;
    }
  }
  // button-left样式 - 按钮从左到右排列
  &.h-buttons-button-left {
    :deep(.ant-btn-group) {
      justify-content: flex-start;
      gap: 12px;
    }
  }
  // button-center样式 - 按钮居中排列
  &.h-buttons-button-center {
    :deep(.ant-btn-group) {
      justify-content: center;
      gap: 12px;
    }
  }
  // button-right样式 - 按钮从右到左排列
  &.h-buttons-button-right {
    :deep(.ant-btn-group) {
      justify-content: flex-end;
      gap: 12px;
    }
  }
  // button-space-between样式 - 按钮两端对齐（两个按钮时分布在两端）
  &.h-buttons-button-space-between {
    :deep(.ant-btn-group) {
      justify-content: space-between;
    }
  }

  // button-icon-tiles样式 - 左侧彩色图标块 + 右侧文字
  &.h-buttons-button-icon-tiles {
    :deep(.ant-btn-group) {
      width: 100%;
      display: flex;
      flex-wrap: wrap; // 允许自动换行
      justify-content: flex-start; // 左对齐
      gap: 0; // 取消统一间距

      .ant-btn {
        position: relative;
        display: inline-flex;
        align-items: center;
        gap: 10px; // 控制图标与文字间距
        border: 1px solid #E6E8EB;
        font-size: 14px;
        height: 44px;
        padding: 0 10px 0 10px;
        border-radius: 8px;
        min-width: 116px;
        box-shadow: 0 2px 0 rgba(0,0,0,0.02);
        margin-right: 12px; // 用margin控制横向间距，末尾一排自然换行
      }

      .ant-btn .anticon {
        width: 26px;
        height: 26px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 6px;
        color: #fff;
        font-size: 14px;
        flex: 0 0 26px; // 固定正方形，防止随文本挤压变形
        box-sizing: border-box;
      }

      /* 默认蓝色，支持通过 data-type 改变色块（success/warning/error/default）*/
      .ant-btn .anticon { background: #3FA7FF; }
      .ant-btn[data-type='success'] .anticon { background: #34C76E; }
      .ant-btn[data-type='warning'] .anticon { background: #FFA940; }
      .ant-btn[data-type='error'] .anticon { background: #FF7875; }
      .ant-btn[disabled] .anticon { background: #BFBFBF; }

      /* 图标与文字间距在有图标时更自然 */
      .ant-btn > .anticon + span { margin-left: 10px; }
    }
  }
  // 水印图标与按钮容器布局调整
  &.h-buttons-button-watermark-icon {
    :deep(.watermark-icon) {  transform: translate(-50%, -54%) !important; }
    :deep(.x-button) { display: flex !important; }
    :deep(.ant-btn-group) {
      margin: 0 auto;
      display: block;
    }
  }
  &.h-buttons-0padding-button {
    padding: 0px 4px;
  }
  // button25样式 用于会诊申请侧边栏按钮样式
  &.h-buttons-button25 {
    :deep(.x-buttons) {
      .ant-btn-group {
        width: 173px;
        justify-content: space-between;

        .ant-btn {
          width: 173px;
        }
      }
    }
  }
  &.h-buttons-button_refresh {
    margin-top: 10px;
  }
  // 居中样式 用于门诊收费左侧按钮样式（三个按钮居中样式）
  &.h-buttons-out-button {
    :deep(.x-buttons) {
      margin-top: 2px !important;
      margin-bottom: 10px !important;
      display: flex;
      justify-content: center;
      .ant-btn-group {
        display: flex;
        flex-wrap: nowrap;
        gap: 12px;
        .ant-btn {
          width: 110px;
          height: 32px;
          border-radius: 6px;
          opacity: 1;
          background: #FFFFFF;
          box-sizing: border-box;
          border: 1px solid #9499A0;
          margin-right: 0px;
          /* 允许正常文本渲染，避免省略号导致的“变成点了” */
          font-family: "Source Han Sans";
          font-size: 16px;
          font-weight: normal;
          line-height: normal;
          color: #313131;
        }
        /* 还原子元素默认高度，避免文字被压缩成点 */
      }
    }
  }
  // button15样式 - 垂直排列的深色按钮组
  &.h-buttons-button15 {
    :deep(.x-buttons) {
      margin-top: -22px;
      .ant-btn-group {
        flex-direction: column; /* 按钮垂直排列 */
        display: flex; /* 启用flex布局 */
        gap: 6px; /* 按钮间距 */
        .ant-btn {
          border: none; /* 移除边框 */
          color: #FFFFFF; /* 字体颜色 */
          background-color: #0057FE; /* 背景色 */
          box-sizing: border-box; /* 盒模型 */
          left: 12px; /* 左偏移 */
          width: 280px; /* 宽度 */
        }
      }
    }
  }
  // button2样式
  &.h-buttons-button2 {
    :deep(.x-buttons) {
      margin: -20px 6px -20px 6px;
      .ant-btn-group {
        width: 100%;
        justify-content: space-between;
        display: flex; /* 确保flex布局 */
        flex-wrap: nowrap; /* 防止换行 */
        .ant-btn {
          border-radius: 6px; /* 边框圆角 */
          border: none; /* 移除边框 */
          flex: 0 0 46%; /* flex-grow: 0, flex-shrink: 0, flex-basis: 46% */
          min-width: 0; /* 覆盖可能的默认最小宽度 */
          font-size: 16px; /* 字体大小 */
          height: 32px; /* 高度 */
          color: #FFFFFF; /* 字体颜色 */
          background-color: #1890FF; /* 背景颜色 */
        }
      }
    }
  }
  // 与表单项内联使用时的垂直居中对齐样式
  &.h-buttons-form-inline {
    :deep(.ant-btn-group){
      height: 45px;
      display: flex;
      align-items: center;
    }
  }
  &.h-buttons-width173 {
    :deep(.ant-btn) {
      width: 173px !important;
    }
  }
  // 按钮无边框+无图标+无阴影
  &.h-button-no-style{
    :deep(.ant-btn) {
        border: 0px;
        .anticon{
          display: none;
        }
    }
    :deep(.ant-btn-primary){
      text-shadow: none;
      box-shadow: none;
    }
  }
  // 按钮组边距
  &.h-button-border{
    border: 1px solid #E5E9F0;
    border-radius: 6px;
  }
  // 按钮撑开整个容器
  &.h-buttons-fill-container{
    :deep(.x-buttons) {
        width: 100%;
        .ant-btn-group{
          width: 100%;
          .ant-btn{
            width: 100%;
            margin-right: 0px;
          }
        }
    }
  }
  &.h-buttons-one-button-style {
    margin: 0 !important;
    padding: 0 !important;
    :deep(.x-buttons) {
      margin: 0 !important;
      padding: 0 !important;
      .ant-btn-group {
        width: 100%;
        height: 32px;
        justify-content: space-between;
        display: flex;
        flex-wrap: nowrap;
        .ant-btn {
          width: 100%;
          margin-right: 0px !important;
          min-width: 100% !important;
          border-radius: 6px; /* 边框圆角 */
          font-size: 18px; /* 字体大小 */
          line-height: 26px;
          font-weight: bold;
          letter-spacing: 14px;
          height: 32px; /* 高度 */
          color: #FFFFFF; /* 字体颜色 */
          background: #0057FE;/* 背景颜色 */
        }
      }
    }
  }
  // no-boder-style样式 - 无边框样式
  &.h-buttons-no-boder-style {
    :deep(.ant-btn-group) {
      margin-left: -20px;
      .ant-btn {
        border: none !important;
        background: transparent !important;
        height: 23px;
        opacity: 1;
        font-family: "Source Han Sans";
        font-size: 16px;
        font-weight: normal;
        line-height: normal;
        letter-spacing: 0em;
        color: #313131;
        padding: 0;
        box-shadow: none;
        margin-right: 0;
        margin-left: 0;

        // 图标样式
        .anticon {
          height: 16px;
          width: 16px;
          opacity: 1;
          background: transparent;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          color: #94979E;
          margin-right: 4px;
        }

        &:hover {
          background: transparent !important;
          color: #313131;
        }

        &:focus {
          background: transparent !important;
          color: #313131;
        }
      }
    }
  }
  // useStyle10样式 - 左侧蓝色圆点指示器样式，与HTab useStyle10效果一致
  &.h-buttons-useStyle10 {
    :deep(.ant-btn-group) {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-left: 0 !important;
      padding: 0 !important;

      .ant-btn {
        position: relative;
        background-color: transparent !important;
        border: none !important;
        border-radius: 0 !important;
        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;
        height: 40px;
        padding: 0 12px 6px 18px;
        text-align: center;
        margin-right: 0 !important;
        box-shadow: none !important;
        display: inline-flex;
        align-items: center;
        vertical-align: top;
        outline: none !important;
        background: transparent !important;
        background-image: none !important;
        border-color: transparent !important;
        border-width: 0 !important;

        &::before {
          content: "" !important;
          position: absolute !important;
          left: 5px !important;
          top: 50% !important;
          transform: translateY(-50%) !important;
          width: 8px !important;
          height: 8px !important;
          background-color: #1890ff !important;
          background-image: none !important;
          border-radius: 50% !important;
          display: block !important;
          z-index: 10 !important;
          pointer-events: none !important;
          opacity: 1 !important;
          mix-blend-mode: normal !important;
          box-shadow: none !important;
          filter: none !important;
          -webkit-filter: none !important;
        }

        .anticon {
          display: none !important;
        }
      }

      // 激活状态：通过 h-btn-active 类控制
      .ant-btn.h-btn-active {
        color: #0057FE !important;
      }
    }
  }
}
</style>
