<template>
  <a-card :bordered="false" :body-style="bodyStyle">
    <a-tabs
      :tabBarGutter="tabBarGutter"
      :activeKey="activeKey"
      @change="tabPaneChange"
      :hideAdd="true"
      :tabBarStyle="{ display: showTabBar ? 'block' : 'none' }"
    >
      <slot name="extraBeforeTabs"></slot>
      <a-tab-pane
        :forceRender="true"
        v-for="(tab, index) in data"
        :key="index"
        :tab="tab.title"
      >
        <component
          :is="resolveComponentType(tab.type)"
          :key="`xTabPaneComp${index}`"
          :ref="`tab_comp_${index}`"
          v-bind="tab.props || {}"
        />
      </a-tab-pane>
    </a-tabs>
  </a-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { resolveComponentType } from '../componentTypes'

const props = defineProps({
  // 标签页数据
  data: {
    type: Array,
    required: true
  },
  // 是否显示标签栏
  showTabBar: {
    type: Boolean,
    default: true
  },
  // 标签页切换时的回调函数
  onChange: {
    type: [String, Function],
    default: null
  },
  // Tab间距
  tabBarGutter: {
    type: Number,
    default: 10
  },
  // 卡片样式
  bodyStyle: {
    type: Object,
    default: () => ({})
  },
  // 默认激活的标签页
  defaultActiveKey: {
    type: [String, Number],
    default: 0
  }
})

// 激活的标签页
const activeKey = ref(0)

// 切换标签页
const tabPaneChange = (newKey) => {
  if (activeKey.value === newKey) return

  const oldKey = activeKey.value
  activeKey.value = newKey

  // 触发标签页切换事件
  if (props.onChange) {
    try {
      if (props.onChange instanceof Function) {
        props.onChange(oldKey, newKey, props.data[oldKey], props.data[newKey])
      } else {
        // 创建一个安全的函数执行环境
        // eslint-disable-next-line no-new-func
        const onChange = new Function('oldKey', 'newKey', 'oldTab', 'newTab', `return (${props.onChange})(oldKey, newKey, oldTab, newTab)`)
        onChange(oldKey, newKey, props.data[oldKey], props.data[newKey])
      }
    } catch (error) {
      console.error('执行标签页切换回调错误:', error)
    }
  }
}

// 生命周期
onMounted(() => {
  activeKey.value = props.defaultActiveKey
})
</script>
