import { ref, onMounted, watch, nextTick } from 'vue'
import { ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus'
import CipTableButton from '@cip/components/cip-table-button'
import { useTable } from '../hooks/use-table'
const getButtonInfo = (vnode) => {
  if (vnode.component) {
    const text = vnode.component.slots.default()
    return {
      ...vnode.component.ctx._.props,
      ...vnode.component.ctx._.attrs,
      text
    }
  }
  return {}
}
const RenderComponent = (props) => {
  const list = props.buttonList // .value
  let dropDownNode
  let buttonNodeList = list
  if (list.length > props.limit) {
    buttonNodeList = list.slice(0, props.limit - 1)
    dropDownNode = <ElDropdown style={'margin-left: 8px'} size={props.size}>
      {{
        default: () => <CipTableButton>更多<i class={'el-icon-caret-bottom'}/></CipTableButton>,
        dropdown: () => <ElDropdownMenu>
          {
            list.slice(props.limit - 1).map(item => {
              const { onClick, text, disabled } = getButtonInfo(item)
              return <ElDropdownItem onClick={onClick} disabled={disabled}>{text}</ElDropdownItem>
            })
          }
        </ElDropdownMenu>
      }}
    </ElDropdown>
  }
  const result = buttonNodeList.map(item => {
    const { onClick, text, type, icon, disabled } = getButtonInfo(item)
    return <CipTableButton type={type} disabled={disabled} icon={icon} onClick={onClick}>{text}</CipTableButton>
  })
  if (dropDownNode) {
    result.push(dropDownNode)
  }
  return result
}
export default {
  name: 'CipTableHandler',
  props: {
    limit: { type: Number, default: 3 },
    row: { type: Object, required: true }
  },
  setup (props, { slots }) {
    const cipTable = useTable()
    const buttonList = ref([])
    const originRef = ref()
    let vnodeList = []
    onMounted(() => {
      watch(() => props.row, (val) => {
        nextTick().then(() => collectButtons())
      }, { immediate: true, deep: true })
    })
    const collectButtons = () => {
      buttonList.value = []
      vnodeList.forEach(vnode => getButtons(vnode))
    }
    const getButtons = (vnode) => {
      if (vnode.shapeFlag === 16) {
        vnode.children.forEach(v => getButtons(v))
      }
      if (vnode.shapeFlag === 36) {
        const componentName = (vnode.type.name || '').toLowerCase()
        if (componentName.indexOf('button') > -1) {
          buttonList.value.push(vnode)
        } else {
          if (vnode.component) {
            const children = vnode.component.subTree.children || []
            children.forEach(v => getButtons(v))
          }
        }
      }
    }
    return () => {
      vnodeList = slots.default?.()
      return <div class={'cip-table-handler'}>
        <div ref={el => { originRef.value = el }} style={'display: none'}>{vnodeList}</div>
        <RenderComponent limit={props.limit} size={cipTable.size} buttonList={buttonList.value} />
      </div>
    }
  }
}
