import React, { useState, useEffect, useCallback } from 'react'
import { Menu, Modal, Select, Tabs } from 'antd'
import style from './index.less'
import { useModel } from 'umi';
import { ExclamationCircleOutlined } from '@ant-design/icons';
const { SubMenu } = Menu;
const { Option } = Select
function LeftPage(props: { isOk?: boolean, isShow?: boolean, h?: number, children?: JSX.Element,isDisabled?:boolean }) {
    const { isOk = true, isShow, h,isDisabled = true } = props
    const { getWxGroupAll, actionWx, getAllOfMember, state, dispatch } = useModel('useOperating.useWxGroupList', model => ({ getWxGroupAll: model.getDataList, ...model }))
    const { dispatch: userDispatch, state: usetState, initUserId } = useModel('useOperating.useUser')
    const { tabsKey, groupAllWx, allWx } = state
    const [openKeys, setOpenKeys] = useState<string[]>(['']) //自己栏选中展开的菜单
    const [crewOpenKeys, setCrewOpenKeys] = useState<string[]>(['']) //组员栏选中展开的菜单
    const [selectedKeys, setSelectedKeys] = useState<string[]>(['']) //自己栏选中的菜单
    const [crewSelectedKeys, setCrewSelectedKeys] = useState<string[]>(['']) //组员栏选中的菜单
    const [visible, setVisible] = useState<boolean>(false)//未保存编辑显示提示窗
    const [wx, setWx] = useState<any>(null)//提示窗出现后暂存点击的公众号以备逻辑跳转
    const [wxData, setWxData] = useState<any>({
        key: '自己',
        menuItem: null,
        crewMenuItem: null,
    })
    let bWith = document.body.clientWidth < 700
    //自己menuitem点击
    let menuItemClick = useCallback((e: any, isOk?: any) => {
        setWxData({ ...wxData, menuItem: e })
        if (isOk) {
            if (e?.keyPath) {
                setSelectedKeys([e.keyPath[0]])
                setOpenKeys(['', e.keyPath[1]])
            }
        }
    }, [getWxGroupAll, wxData])
    /**组员menuitem点击 */
    let crewMenuItemClick = useCallback((e: any, isOk?: any) => {
        setWxData({ ...wxData, crewMenuItem: e })
        if (isOk) {
            if (e?.keyPath) {
                setCrewSelectedKeys([e?.keyPath[0]])
                setCrewOpenKeys([e?.keyPath[1]])
            }
        }
    }, [getAllOfMember, wxData])
    //自己menu点击
    let menuClick = useCallback((e: any) => {
        setOpenKeys(e)
    }, [getWxGroupAll])
    /**组员menu点击 */
    let crewMenuClick = useCallback((e: any) => {
        setCrewOpenKeys(e)
    }, [])
    /**放弃保存 */
    let outSaver = () => {
        setVisible(false)
        tabsChange(wxData.key, true)
        if (wxData.key === '自己') {
            if (typeof wxData?.menuItem === 'string') {
                inputChange(wxData?.menuItem, true)
            } else {
                wxData?.menuItem && menuItemClick(wxData?.menuItem, true)
            }

        } else {
            if (typeof wxData?.crewMenuItem === 'string') {
                inputChange(wxData?.crewMenuItem, true)
            } else {
                wxData?.crewMenuItem && crewMenuItemClick(wxData?.crewMenuItem, true)
            }
        }
        if (wx) {
            selectData(wx, true)
        }
    }

    //选中微信的数据
    let selectData = useCallback((wx: any, isOk?: any) => {
        setWx(wx)
        if (isOk) {
            actionWx(wx)
            setVisible(false)
        } else {
            if (!visible) {
                setVisible(true)
            }
        }
    }, [getAllOfMember, wxData, visible])
    //tabs选中
    let tabsChange = useCallback((key: string, isOk?: boolean) => {
        console.log(111111, key)
        setWxData({ ...wxData, key })
        if (isOk) {
            dispatch({ type: 'setTabsKey', params: { tabsKey: key } })
            if (key === '自己') {
                initUserId()
                if (openKeys[0] && selectedKeys[0]) {
                    selectGZH(openKeys[1], selectedKeys[0], key)
                } else {
                    let ok = true
                    getWxGroupAll?.data?.forEach((item: any) => {
                        if (ok && item?.mpAccounts?.length > 0) {
                            ok = false
                            actionWx(item?.mpAccounts[0])
                        }
                    })
                }

            } else {
                if (crewOpenKeys[0] && crewSelectedKeys[0]) {
                    selectGZH(crewOpenKeys[0], crewSelectedKeys[0], key)
                } else {
                    let ok = true
                    getAllOfMember?.data?.forEach((item: { key: any, value: any[] }) => {
                        if (ok && item?.value?.length > 0) {
                            ok = false
                            actionWx(item?.value[0])
                        }
                    })
                }
            }
            setVisible(false)
        } else {
            if (!visible) {
                setVisible(true)
            }

        }
    }, [openKeys, selectedKeys, crewOpenKeys, crewSelectedKeys, wxData, visible, getWxGroupAll, getAllOfMember])
    /*以key筛选公众号 */
    let selectGZH = (open: string, select: string, tabsKey?: string) => {
        if (tabsKey === '自己') {
            if (getWxGroupAll?.data) {//筛选出微信号
                getWxGroupAll?.data?.forEach((item: any) => {
                    if (item?.groupName === open) {
                        item?.mpAccounts?.forEach((obj: any) => {
                            if (obj?.nickName === select) {
                                actionWx(obj)//更新当前选中微信号，触发各个组件的数据获取
                            }
                        })
                    }
                })
            }
        } else {
            if (getAllOfMember?.data) {
                getAllOfMember?.data?.forEach((item: { key: { nickname: string, userId: number }, value: any[] }) => {
                    if (item?.key?.nickname + item?.key?.userId === open) {
                        item?.value?.forEach((obj: any) => {
                            if (obj?.nickName === select) {
                                userDispatch({ type: 'setUserId', params: { userId: item?.key?.userId } })
                                actionWx(obj)//更新当前选中微信号，触发各个组件的数据获取
                            }
                        })
                    }
                })
            }
        }
    }
    //搜索
    let inputChange = (v: string, isOk?: boolean) => {
        console.log(v)
        if (v) {
            if (isOk) {
                let [open, select] = v.split('_') //切换字符串转换成数组
                if (tabsKey === '自己') {//设置选中key展开的菜单
                    setOpenKeys([open])
                    setSelectedKeys([select])
                } else {
                    setCrewOpenKeys([open])
                    setCrewSelectedKeys([select])
                }
                userIdset(v)
                selectGZH(open, select, tabsKey)//已key搜索对应的公众号并发送请求获取数据
            } else {
                if (!visible) {
                    if (tabsKey === '自己') {
                        setWxData({ ...wxData, menuItem: v })
                    } else {
                        setWxData({ ...wxData, crewMenuItem: v })
                    }
                    setVisible(true)
                }
                userIdset(v)
            }
        }
    }
    //设置选中的userId
    const userIdset = useCallback((v?: any) => {
        if (tabsKey === '自己') {
            initUserId()
        } else {
            let id = typeof v === 'number' ? v : v.replace(/[\u4e00-\u9fa5_]/ig, '')
            userDispatch({ type: 'setUserId', params: { userId: id } })
        }
    }, [tabsKey])
    //首次加载选中当前选中的tabs有公众号的组或成员中第一个公众号
    useEffect(() => {
        if (tabsKey === '自己') {
            getWxGroupAll?.data?.forEach((item: { mpAccounts?: any[], groupName: string }, index: number) => {
                item?.mpAccounts?.forEach((wx: { nickName: string }) => {
                    if (wx?.nickName === state?.actionWX?.nickName) {
                        setOpenKeys(['', `${item?.groupName}`])
                        setSelectedKeys([`${wx?.nickName}`])
                    }
                })
            })
        } else {
            getAllOfMember?.data?.forEach((item: { key: { nickname: string, userId: number }, value: any[] }, index: number) => {
                item?.value?.forEach((wx: { nickName: string }) => {
                    if (wx?.nickName === state?.actionWX?.nickName) {
                        setCrewOpenKeys([`${item?.key?.nickname + item?.key?.userId}`])
                        setCrewSelectedKeys([`${wx?.nickName}`])
                    }
                })
            })
        }

    }, [tabsKey])
    useEffect(() => {
        if (visible) {
            Modal.confirm({
                title: '有修改未保存！',
                icon: <ExclamationCircleOutlined />,
                onOk() {
                    setVisible(false)
                },
                onCancel() {
                    outSaver()
                },
                okText: '去保存修改',
                cancelText: '放弃修改',
            });
        }
    }, [visible])
    return <>
        <Tabs type="card" activeKey={tabsKey} onChange={isShow ? (key: any) => tabsChange(key, isOk) : (key: any) => tabsChange(key, true)} className={style.tabs} >
            <Tabs.TabPane tab='自己' key='自己'>
                <div className={style.group}>
                    <div>
                        <Select
                            style={{ width: '100%' }}
                            placeholder="输入搜索公众号"
                            onChange={isShow ? (v: any) => { inputChange(v, isOk) } : (v: any) => { inputChange(v, true) }}
                            showArrow
                            showSearch
                            allowClear
                        >
                            {
                                getWxGroupAll?.data?.map((item: any, index: number) => {
                                    return item?.mpAccounts?.map((list: any, eq: number) => {
                                        return <Option key={item?.groupName + list?.id} value={item.groupName + '_' + list?.nickName} disabled={isDisabled ? list?.verifyTypeInfo === -1 :false}>
                                            <img src={list?.headImg || localStorage?.bookImg} className={style.item_img} />{list.nickName}
                                        </Option>
                                    })
                                })
                            }
                        </Select>
                        <Menu
                            onClick={isShow ? (e: any) => menuItemClick(e, isOk) : (e: any) => menuItemClick(e, true)}
                            style={{ width: `${bWith ? '100%' : '178px'}`, height: 'calc(100vh - 220px)', overflowY: 'auto', overflowX: 'hidden' }}
                            openKeys={openKeys}
                            selectedKeys={selectedKeys}
                            mode={"inline"}
                            onOpenChange={menuClick}
                        >
                            {
                                getWxGroupAll?.data?.map((item: any) => {
                                    return <SubMenu
                                        key={item?.groupName}
                                        title={<p>{item?.groupName}<span style={{ color: '#999' }}>({item?.mpAccounts?.length || 0})</span></p>}
                                    >
                                        {
                                            item?.mpAccounts?.map((list: any) => {
                                                return <Menu.Item
                                                    key={list?.nickName}
                                                    onClick={isShow ? () => {
                                                        selectData(list, isOk)
                                                        userIdset(item?.userId)
                                                    } : () => {
                                                        selectData(list, true)
                                                        userIdset(item?.userId)
                                                    }}
                                                    disabled={isDisabled ? list.verifyTypeInfo === -1 :false}
                                                >
                                                    <img src={list?.headImg || localStorage?.bookImg} className={style.item_img} />
                                                    <span>{list?.nickName}</span>
                                                </Menu.Item>
                                            })
                                        }
                                    </SubMenu>
                                })
                            }
                        </Menu>
                    </div>
                    {props.children}
                </div>
            </Tabs.TabPane>
            {
                getAllOfMember?.data?.length > 0 && <>
                    <Tabs.TabPane tab='组员' key='组员'>
                        <div className={style.group}>
                            <div >
                                <Select
                                    style={{ width: '100%' }}
                                    placeholder="输入搜索公众号"
                                    onChange={isShow ? (v: any) => { inputChange(v, isOk) } : (v: any) => { inputChange(v, true) }}
                                    showArrow
                                    showSearch
                                    allowClear
                                >
                                    {
                                        getAllOfMember?.data?.map((item: { key: { nickname: string, userId: number }, value: any[] }, index: number) => {
                                            return item?.value?.map((list: any, eq: number) => {
                                                return <Option key={list?.id + item?.key?.nickname} value={item?.key?.nickname + item?.key?.userId + '_' + list?.nickName} disabled={ isDisabled?list?.verifyTypeInfo === -1:false}>
                                                    <img src={list?.headImg || localStorage?.bookImg} className={style.item_img} /> {list?.nickName}
                                                </Option>
                                            })
                                        })
                                    }
                                </Select>
                                <Menu
                                    onClick={isShow ? (e: any) => crewMenuItemClick(e, isOk) : (e: any) => crewMenuItemClick(e, true)}
                                    style={{ width: `${bWith ? '100%' : '178px'}`, height: 'calc(100vh - 220px)', overflowY: 'auto', overflowX: 'hidden' }}
                                    openKeys={crewOpenKeys}
                                    selectedKeys={crewSelectedKeys}
                                    mode={"inline"}
                                    onOpenChange={crewMenuClick}
                                >
                                    {
                                        getAllOfMember?.data?.map((item: { key: { nickname: string, userId: number }, value: any[] }, eq: number) => {
                                            return <SubMenu
                                                key={item?.key?.nickname + item?.key?.userId}
                                                title={<p>{item?.key?.nickname}<span style={{ color: '#999' }}>({item?.value?.length})</span></p>}
                                            >
                                                {
                                                  crewOpenKeys.some((name) => name === item?.key?.nickname + item?.key?.userId) &&   item?.value?.map((list: any,index:number) => {
                                                        return <Menu.Item
                                                            key={eq + '_' + index + '_' + list?.id + '_' + list?.putUserId}
                                                            onClick={isShow ? () => {
                                                                selectData(list, isOk)
                                                                userIdset(item?.key?.userId)
                                                            } : () => {
                                                                selectData(list, true)
                                                                userIdset(item?.key?.userId)
                                                            }}
                                                            disabled={isDisabled? list.verifyTypeInfo === -1 :false}
                                                        >
                                                            <img src={list?.headImg || localStorage?.bookImg} className={style.item_img} />
                                                            <span>{list?.nickName}</span>
                                                        </Menu.Item>
                                                    })
                                                }
                                            </SubMenu>
                                        })
                                    }
                                </Menu>
                            </div>
                            {props.children}
                        </div>
                    </Tabs.TabPane>
                </>
            }
        </Tabs>
    </ >
}

export default LeftPage