import { computed, h } from 'vue'
import { useCipConfig } from '../hooks/use-cip-config'
import { ElButton } from 'element-plus'
import './index.less'
import { getUsingConfig } from '@cip/utils/util'
import { defaultButtonConfigMap } from './config'
import { generateProps, generateEmits } from '../helper/component-util'
import { componentScheme } from './component.scheme'
export default {
  name: 'CipButton',
  props: generateProps(componentScheme),
  emits: generateEmits(componentScheme),
  setup (props, context) {
    const cipConfig = useCipConfig()
    const buttonConfigMap = computed(() => { // 默认buttonConfig配置与cipConfig配置合并
      const result = {}
      const defaultKeys = Object.keys(defaultButtonConfigMap)
      defaultKeys.forEach(key => {
        const defaultButtonConfig = defaultButtonConfigMap[key]
        if (cipConfig.buttonConfigMap?.[key]) {
          result[key] = Object.assign({}, defaultButtonConfig, cipConfig.buttonConfigMap?.[key])
        } else {
          result[key] = defaultButtonConfig
        }
      })
      const globalButtonConfigMapKeys = Object.keys(cipConfig.buttonConfigMap || {})
      if (globalButtonConfigMapKeys.length > 0) {
        globalButtonConfigMapKeys
          .filter(key => !defaultKeys.includes(key))
          .forEach(key => {
            result[key] = cipConfig.buttonConfigMap[key]
          })
      }
      return result
    })
    const buttonConfig = computed(() => {
      return buttonConfigMap.value[props.buttonType] || {}
    })

    const _icon = computed(() => getUsingConfig(props.icon, buttonConfig.value.icon))

    return () => h(
      ElButton,
      {
        ...context.attrs,
        class: [
          'cip-button',
          {
            'cip-button--square': props.square,
            'cip-button--map': props.map
          }
        ],
        size: props.size,
        type: buttonConfig.value.type,
        onClick: (...args) => context.emit('click', ...args)
      },
      {
        // 原型按钮和方型按钮不支持文字展示
        default: (context.attrs.circle || props.square)
          ? undefined
          : () => (context.slots.default?.({ text: buttonConfig.value.text ?? '' }) || buttonConfig.value.text),
        icon: !_icon.value
          ? undefined
          : () => typeof _icon.value === 'string'
              ? h('i', { class: _icon.value })
              : h(_icon.value)
      }
    )
  }
}
