import { Menu, Select, Tabs } from 'antd'
import React, { ReactNode, useCallback, useEffect, useState } from 'react'
import style from './index.less'
import { useModel, history } from 'umi'
import { MenuFoldOutlined, MenuUnfoldOutlined, UsergroupAddOutlined, UserOutlined } from '@ant-design/icons'

function GroupYybTabs(props: { children?: JSX.Element, height?: string | number, name?: string, allowClear?: boolean, isShowCount?: boolean, tabBarExtraContent?: ReactNode | { left?: ReactNode, right?: ReactNode } }) {
    let { allowClear = true, tabBarExtraContent, isShowCount = true, name } = props // isFadminQTab 非Admin 不展示选择人
    const [crewSelectedKeys, setCrewSelectedKeys] = useState<string[]>([]) //选中组员的菜单
    const { getAllZhMemBer, state: usesState, dispatch: useDispatch } = useModel('useOperating.useWxGroupList')
    const { tabsKey1 } = usesState
    const { dispatch, initUserIdYyb, state: { selectdUserIdYyb, selectdNameYyb } } = useModel('useOperating.useUser')
    const [isShow, setIsShow] = useState<boolean>(true)

    //获取当前角色下的公众号
    useEffect(() => {
        if (selectdNameYyb && selectdUserIdYyb) {
            setCrewSelectedKeys([selectdNameYyb + selectdUserIdYyb])
        }
    }, [selectdNameYyb, selectdUserIdYyb])

    // 特定空的需要重新赋值
    useEffect(() => {
        if (name === '账号管理' && tabsKey1 === '组员' && !selectdUserIdYyb) {
            onChange('组员')
        }
    }, [])

    //组员与自己的切换
    const onChange = (key: string) => {
        if (key === 'btn1') return
        if (key === 'btn') {
            if (tabsKey1 === '组员') {
                setIsShow(!isShow)
            }
            return
        }
        useDispatch({ type: 'setTabsKey1', params: { tabsKey1: key } })
        if (key === '自己') {
            initUserIdYyb()
            setIsShow(true)
        } else {
            /**当切换为组员的时候自动选中第一个有绑定公众号的组员 */
            let ok = true
            getAllZhMemBer?.data?.forEach((item: { key: { userId: number, nickname: string }, value: any[] }) => {
                if (ok && item?.value?.length > 0) {
                    ok = false
                    // setCrewSelectedKeys([item?.key?.nickname + item?.key?.userId])
                    dispatch({ type: 'setUserIdYyb', params: { userId: item?.key?.userId.toString(), name: item?.key?.nickname } })
                }
            })
            if (ok) {
                dispatch({ type: 'setUserIdYyb', params: { userId: getAllZhMemBer?.data[0]?.key?.userId?.toString(), name: getAllZhMemBer?.data[0]?.key?.nickname } })
            }
        }
        return () => {
            initUserIdYyb()
        }
    }

    //选中的成员改变全局userId请求获取数据
    const itemChange = (key: string, option: any) => {
        if (key) {
            // setCrewSelectedKeys([option.children + key])
            dispatch({ type: 'setUserIdYyb', params: { userId: key.toString(), name: option.children } })
        } else {
            setCrewSelectedKeys([])
            dispatch({ type: 'setUserIdYyb', params: { userId: '', name: '' } })
        }
    }
    //组员menuitem点击
    let crewMenuItemClick = (e: any) => {
        setCrewSelectedKeys([e.key])
    };
    //选中角色
    let handelUserId = useCallback((userId, name) => {
        dispatch({ type: 'setUserIdYyb', params: { userId: userId?.toString(), name } })
    }, [])

    //更改背景色
    useEffect(() => {
        let path = history.location.pathname.split('/')[1]
        if (path === 'operatePage') {
            localStorage.setItem('bg', 'light')
        }
        if (path === 'dataStatistics') {
            localStorage.setItem('bg', 'dark')
        }
    }, [history])

    return <>
        <Tabs onChange={onChange} className={style.tabs} type='card' activeKey={tabsKey1} tabBarExtraContent={tabBarExtraContent}>
            <Tabs.TabPane tab={<span><UserOutlined />自己</span>} key='自己' >
                {props.children}
            </Tabs.TabPane>
            {
                getAllZhMemBer?.data?.length > 0 && <>
                    <Tabs.TabPane tab={<span><UsergroupAddOutlined />组员</span>} key='组员'>
                        <div className={style.group}>
                            {
                                isShow && <div>
                                    <Select
                                        showSearch
                                        style={{ width: 178 }}
                                        placeholder="输入组员名称"
                                        optionFilterProp="children"
                                        onChange={itemChange}
                                        allowClear={allowClear}
                                        value={crewSelectedKeys?.join()?.replace(/[\w]/ig, '')}
                                        filterOption={(input, option) =>
                                            option?.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    >
                                        {
                                            getAllZhMemBer?.data?.map((user: { key: { userId: number, nickname: string } }, index: number) => {
                                                return <Select.Option value={user?.key?.userId} key={user?.key?.userId + index}>{user?.key?.nickname}</Select.Option>
                                            })
                                        }
                                    </Select>
                                    <Menu
                                        onClick={crewMenuItemClick}
                                        style={{
                                            width: 178,
                                            height: props?.height ? props.height : 'calc(100vh - 400px)',
                                            overflowY: `auto`,
                                            overflowX: 'hidden',
                                            borderRight: 0,
                                            backgroundColor: 'transparent'
                                        }}
                                        selectedKeys={crewSelectedKeys}
                                        mode={"inline"}
                                    >
                                        {
                                            getAllZhMemBer?.data?.map((item: { key: { nickname: string, userId: number }, value: any[] }) => {
                                                return <Menu.Item key={item?.key?.nickname + item?.key?.userId}>
                                                    <p onClick={() => { handelUserId(item?.key?.userId?.toString(), item?.key?.nickname) }} style={{ margin: 0 }}>
                                                        {item?.key?.nickname}
                                                        {isShowCount && <span style={{ color: '#999' }}>({item?.value?.length})</span>}
                                                    </p>
                                                </Menu.Item>
                                            })
                                        }
                                    </Menu>
                                </div>
                            }
                            {props.children}
                        </div>
                    </Tabs.TabPane>
                    <Tabs.TabPane tab={<span>{isShow ? <MenuFoldOutlined /> : <MenuUnfoldOutlined />}</span>} key='btn' />
                </>
            }
        </Tabs>
    </>
}

export default GroupYybTabs