/*
 * @Author: donghao donghao@supervision.ltd
 * @Date: 2025-07-29 10:48:37
 * @LastEditors: donghao donghao@supervision.ltd
 * @LastEditTime: 2025-07-31 10:09:54
 * @FilePath: \Robot-Al-Platform-Web\src\renderer\src\components\Form\switch.tsx
 * @Description: Switch 组件
 */
import { defineComponent, h, withDefaults, computed, normalizeClass } from 'vue'
import { ElSwitch } from 'element-plus'
import type { SwitchProps } from 'element-plus'

interface DsSwitchProps extends SwitchProps {
  label?: string
  prefixRender?: (...ags: any[]) => any // 前缀内容 render渲染
  suffixRender?: (...ags: any[]) => any // 后缀内容 render渲染
  containerClassName?: string // container容器样式
  componentClassName?: string // 整体容器样式
}

export default defineComponent({
  name: 'DSSwitch',
  props: {
    modelValue: {
      type: [Boolean, String, Number],
      default: false
    },
    label: {
      type: String,
      default: ''
    },
    suffixRender: {
      type: Function as DsSwitchProps['suffixRender'],
      default: null
    },
    containerClassName: {
      type: String,
      default: ''
    },
    componentClassName: {
      type: String,
      default: ''
    },
    ...ElSwitch.props // 继承 ElSwitch 的所有 props
  },
  emits: ['update:modelValue', 'change'],
  setup(props, { emit, attrs }) {
    const { containerClassName, componentClassName, ...restProps } = props
    // 处理自定义类名和 Vue 的 class 属性
    const componentClasses = computed(() => {
      const classes = ['flex items-center ds-switch-box', componentClassName]
      // 处理 Vue 的 class 属性（支持字符串/数组/对象）
      if (attrs.class) {
        classes.push(normalizeClass(attrs.class))
      }
      return classes.filter((c) => c).join(' ')
    })
    // 处理自定义类名和 Vue 的 class 属性
    const containerClasses = computed(() => {
      const classes = ['flex items-center justify-between w-[136px]', containerClassName]
      // 处理 Vue 的 class 属性（支持字符串/数组/对象）
      if (attrs.class) {
        classes.push(normalizeClass(attrs.class))
      }
      return classes.filter((c) => c).join(' ')
    })

    const handleChange = (val: boolean | string | number) => {
      emit('update:modelValue', val)
      emit('change', val)
    }
    // 渲染自定义前缀内容
    const renderPrefix = () => {
      if (props.prefixRender) {
        return props?.prefixRender?.()
      }
      return <span class="ds-switch-label">{props?.label}</span>
    }
    // 渲染自定义后缀内容
    const renderSuffix = () => {
      if (props.suffixRender) {
        return props?.suffixRender?.()
      }
      return null
    }

    return () => (
      <div className={componentClasses.value}>
        <div className={containerClasses.value}>
          {/* 添加前缀插槽 */}
          {renderPrefix()}
          <ElSwitch {...restProps} modelValue={props.modelValue} onChange={handleChange} />
        </div>
        {/* 添加后缀插槽 */}
        {renderSuffix()}
      </div>
    )
  }
})
