import { Button, Space, Dropdown, Menu } from "antd"
import React, { useEffect, useState } from "react"
import { CaretUpOutlined } from '@ant-design/icons';
import { getButtonRole } from "../../utils"

const ButtonBox = ({ ButtonBoxSchema, activityArr = [], rightActivityArr = [], size = 10, ...data }: any) => {
  const [leftData, setLeftData] = useState<any[]>([])
  const [rightData, setRightData] = useState<any[]>([])
  const [rightActivity, setrightActivityArr] = useState<any>([])
  useEffect(() => {
    if (ButtonBoxSchema instanceof Array) {
      setLeftData(ButtonBoxSchema)
    } else {
      setLeftData(ButtonBoxSchema?.left || [])
      const roleIndex: any = []
      const arr = ButtonBoxSchema?.right?.filter((item: any, index: number) => {
        if (getButtonRole(item?.role)) {
          roleIndex.push(index)
        }
        return getButtonRole(item?.role)
      })
      const arr2 = rightActivityArr?.filter((_item: any, index: number) => {
        return roleIndex.includes(index)
      })
      setrightActivityArr(arr2)
      if (arr?.length) {
        setRightData(arr)
      }
    }
  }, [ButtonBoxSchema])


  return <div style={{ marginBottom: "20px", display: "flex", justifyContent: "space-between" }} {...data}>
    <Space size={size}>
      {leftData.map((item: any, index: any) => {
        if (!getButtonRole(item?.role)) {
          return null
        }
        return <Button onClick={() => {
          activityArr?.[index] && activityArr[index]()
        }} type={item.type} key={item.text} >
          {item?.icon || null}
          {item.text}
        </Button>
      })}
      <span></span>
    </Space>
    {rightData && rightData?.length ? <Dropdown overlay={<Menu
      items={rightData.map((item: any, index: number) => {
        return {
          label: item.text,
          key: item.text,
          icon: item?.icon || null,
          onClick: () => {
            rightActivity?.[index] && rightActivity[index]()
          }
        }
      })}
    />}>
      <Button>
        <Space>
          更多操作
          <CaretUpOutlined />
        </Space>
      </Button>
    </Dropdown> : null}
  </div>
}

export default ButtonBox