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 GroupKyyBoxTabs(props: { children?: JSX.Element, height?: string | number, isFadminQTab?: boolean, isUserSelect?: boolean, allowClear?: boolean, tabBarExtraContent?: ReactNode | {left?: ReactNode, right?: ReactNode} }) {
    let { isFadminQTab = false, isUserSelect = false, allowClear = true, tabBarExtraContent } = props // isFadminQTab 非Admin 不展示选择人 isUserSelect 是否展示搜索人员
    const [crewSelectedKeys, setCrewSelectedKeys] = useState<string[]>([]) //选中组员的菜单
    const { getAllOfMember, state: usesState, dispatch: useDispatch, actionGroupWx } = useModel('useOperating.useWxGroupList')
    const { tabsKey } = usesState
    const { dispatch, initUserId, state: { selectdUserId } } = useModel('useOperating.useUser')
    const { state: { pitcher }, dispatch: tableDispatch, getUserAjax } = useModel('useData.useTableData')
    const { dispatch: dataDispatch } = useModel('useData.useDataCenter')
    const [isShow, setIsShow] = useState<boolean>(true)
    const { currentUser }: any = useModel('@@initialState', model => ({ currentUser: model.initialState?.currentUser }))
    const [qTab, setQTab] = useState<boolean>(false)

    useEffect(() => {
        if (isUserSelect) {
            getUserAjax.run({ user_id: currentUser.userId == 1 ? selectdUserId : currentUser.userId })
        }
    }, [isUserSelect, selectdUserId, currentUser])
    useEffect(() => {
        if (isFadminQTab && currentUser.userId !== 1) {
            setQTab(true)
        }
    }, [isFadminQTab, currentUser.userId])
    //组员与自己的切换
    const onChange = (key: string) => {
        if (key === 'btn1') return
        if (key === 'btn') {
            if (tabsKey === '组员') {
                setIsShow(!isShow)
            }
            return
        }
        useDispatch({ type: 'setTabsKey', params: { tabsKey: key } })
        tableDispatch({ type: 'channel', params: { channel: undefined } })//清空公众号select的值
        dataDispatch({ type: 'setState', params: { channel: undefined } })//清空公众号select的值
        if (key === '自己') {
            initUserId()
            setIsShow(true)
        } else {
            /**当切换为组员的时候自动选中第一个有绑定公众号的组员 */
            let ok = true
            getAllOfMember?.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: 'setUserId', params: { userId: item?.key?.userId.toString(), name: item?.key?.nickname } })
                }
            })
            if (ok) {
                dispatch({ type: 'setUserId', params: { userId: getAllOfMember?.data[0]?.key?.userId?.toString(), name: getAllOfMember?.data[0]?.key?.nickname } })
            }
        }
        return () => {
            initUserId()
        }
    }

    //选中的成员改变全局userId请求获取数据
    const itemChange = (key: string, option: any) => {
        if (key) {
            setCrewSelectedKeys([option.children + key])
            dispatch({ type: 'setUserId', params: { userId: key.toString(), name: option.children } })
            tableDispatch({ type: 'channel', params: { channel: undefined } })//清空公众号select的值
            dataDispatch({ type: 'setState', params: { channel: undefined } })//清空公众号select的值
        } else {
            setCrewSelectedKeys([])
            dispatch({ type: 'setUserId', params: { userId: '', name: '' } })
            tableDispatch({ type: 'channel', params: { channel: undefined } })//清空公众号select的值
            dataDispatch({ type: 'setState', params: { channel: undefined } })//清空公众号select的值
        }
    }
    //组员menuitem点击
    let crewMenuItemClick = (e: any) => {
        setCrewSelectedKeys([e.key])
    };
    //选中角色
    let handelUserId = useCallback((userId, name) => {
        dispatch({ type: 'setUserId', params: { userId: userId?.toString(), name } })
        tableDispatch({ type: 'channel', params: { channel: undefined } })//清空公众号select的值
        dataDispatch({ type: 'setState', params: { channel: undefined } })//清空公众号select的值
    }, [])
    //获取当前角色下的公众号
    useEffect(() => {
        actionGroupWx(selectdUserId)//获取当前角色下的公众号
    }, [selectdUserId])
    //更改背景色
    useEffect(() => {
        let path = history.location.pathname.split('/')[1]
        if (path === 'operatePage') {
            localStorage.setItem('bg', 'light')
        }
        if (path === 'dataStatistics') {
            localStorage.setItem('bg', 'dark')
        }
    }, [history])

    return <>
        {
            !qTab ?
                <Tabs onChange={onChange} className={style.tabs} type='card' activeKey={tabsKey} tabBarExtraContent={tabBarExtraContent}>
                    <Tabs.TabPane tab={<span><UserOutlined />自己</span>} key='自己' >
                        {props.children}
                    </Tabs.TabPane>
                    {
                        getAllOfMember?.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
                                                }
                                            >
                                                {
                                                    getAllOfMember?.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"}
                                            >
                                                {
                                                    getAllOfMember?.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}
                                                                <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' />
                            {
                                isUserSelect && <Tabs.TabPane tab={<Select
                                    style={{ width: 150 }}
                                    placeholder="输入搜索投手"
                                    // onChange={isShow ? (v: any) => { inputChange(v, isOk) } : (v: any) => { inputChange(v, true) }}
                                    onChange={(value: any) => { tableDispatch({ type: 'setState', params: { pitcher: value } }) }}
                                    showArrow
                                    showSearch
                                    allowClear
                                    value={pitcher}
                                >
                                    {
                                        getUserAjax?.data?.data?.map((list: any, eq: number) => {
                                            return <Select.Option key={list?.user_id} value={list?.nick_name}>
                                                {list?.nick_name}
                                            </Select.Option>
                                        })
                                    })
                                </Select>} key='btn1' />
                            }
                        </>
                    }
                </Tabs>
                :
                <>
                    <div style={{ padding: '8px 16px', backgroundColor: '#FFF', display: 'inline-block' }}>
                        {
                            isUserSelect && <Select
                                style={{ width: 150 }}
                                placeholder="输入搜索投手"
                                // onChange={isShow ? (v: any) => { inputChange(v, isOk) } : (v: any) => { inputChange(v, true) }}
                                onChange={(value: any) => { tableDispatch({ type: 'setState', params: { pitcher: value } }) }}
                                showArrow
                                showSearch
                                allowClear
                                value={pitcher}
                            >
                                {
                                    getUserAjax?.data?.data?.map((list: any, eq: number) => {
                                        return <Select.Option key={list?.user_id} value={list?.nick_name}>
                                            {list?.nick_name}
                                        </Select.Option>
                                    })
                                })
                            </Select>
                        }
                    </div>
                    {props.children}
                </>
        }
    </>
}

export default GroupKyyBoxTabs