import React, { useState, useEffect } from 'react'
import { history, Outlet, useLocation, matchRoutes, useModel } from '@umijs/max'
import { Menu, Tabs, Select } from 'antd'
import './SystemContentList.less'
import { formatRoute, getDefaultRoute } from '@/utils/routeUtils'
import styles from './TopNavBar.less'
import { Row, Col, Avatar, Dropdown, Button } from 'antd'
import { userInfo } from '@/utils/globalCommon'
import { HomeOutlined, SettingOutlined, LogoutOutlined } from '@ant-design/icons'
import { getPageQuery } from '@/utils/utils'
import menuTitle from '@/assets/img/memuTitle.png'
import menuTitle1 from '@/assets/img/memuTitle1.png'

const SystemContentList = (props) => {
    const dynamicRoute = window.dynamicRoute
    console.log(dynamicRoute)
    const location = useLocation()
    const pathName = location.pathname
    const [openKey, setOpenKey] = useState([])
    const [selectedKey, setSelectedKey] = useState([])
    const [menuItems, setMenuItems] = useState([])
    const [systemType, setSystemType] = useState('安全管理系统')
    let defaultKey = ''

    useEffect(() => {
        if (!dynamicRoute || dynamicRoute?.length === 0) return
        let newList = []
        let routes = []

        if (dynamicRoute?.length) {
            let tempRoute = dynamicRoute?.filter(item => pathName.indexOf(item.key) !== -1) ?? []

            newList = formatRoute(tempRoute[0]?.children)
            routes = formatRoute(tempRoute[0]?.children, true)
            defaultKey = getDefaultRoute(routes)
            const mathRoute = matchRoutes(routes, pathName)

            setRouteActive({ key: mathRoute?.length ? pathName : defaultKey }, routes)
        }

        setMenuItems(newList)
    }, [pathName])

    const setRouteActive = (value, menu) => {
        const curKey = value.key
        const tempMenu = menu ?? menuItems ?? []
        const mathRoute = matchRoutes(tempMenu, curKey)
        let openKeys = []
        let selectedKeys = []

        mathRoute?.map((item, index) => {
            mathRoute?.length !== index + 1 && (openKeys = [...openKeys, item.pathname])
            mathRoute?.length === index + 1 && (selectedKeys = [...selectedKeys, item.pathname])
        })

        setOpenKey(openKeys)
        setSelectedKey(selectedKeys)
        history.replace(curKey)
    }

    const { initialState: { menu }, setInitialState } = useModel('@@initialState')

    const loginOut = async () => {
        // await outLogin()
        const { redirect } = getPageQuery()

        if (window.location.pathname !== '/login/login' && !redirect) {
            history.replace({
                pathname: '/login',
                // search: stringify({
                //   redirect: window.location.href,
                // }),
            })

            setInitialState({ currentUser: null, menu: null, menuMap: null })
            window.dynamicRoute = null
            localStorage.clear()
        }
    }

    const handleMenuClick = (e) => {
        switch (e.key) {
            case 'logout':
                loginOut()
                break
            default:
                break
        }
    }

    const dropDownMenuItems = [
        {
            label: <><LogoutOutlined style={{ marginRight: '8px' }} />退出登录</>,
            key: 'logout'
        }
    ]

    const dropDownMenu = () => (
        <Menu items={dropDownMenuItems} onClick={handleMenuClick} selectedKeys={[]} className={styles.tabBarMenu} />
    )

    return (
        <div className='pageContainer systemContent'>
            <div className='leftMenu'>
                <div className='menuTitle' style={{ marginBottom: '10px' }}>
                    <img src={menuTitle} alt='menuTitle' style={{ marginTop: '20px', marginBottom: '2px' }} />
                    <img src={menuTitle1} alt='menuTitle1' />
                </div>
                <div style={{ textAlign: 'center', marginBottom: 16 }}>
                    <Select
                        value={systemType}
                        onChange={setSystemType}
                        style={{
                            width: 200,
                            borderColor: '#3D81FF',
                            backgroundColor: '#003AA7',
                            color: '#fff',
                            fontSize: 22,
                            fontWeight: 600
                        }}
                        options={[
                            { value: '安全管理系统', label: '安全管理系统' },
                            { value: '环保管理系统', label: '环保管理系统' }
                        ]}
                        dropdownStyle={{
                            backgroundColor: '#003AA7',
                            borderColor: '#3D81FF'
                        }}
                        popupClassName="custom-select-dropdown"
                        className="custom-select"
                    />
                </div>
                <style jsx>{`
                    .custom-select .ant-select-selector {
                        border-color: #3D81FF !important;
                        background-color: #003AA7 !important;
                        color: #fff !important;
                        fontSize: 22px !important;
                        fontWeight: 600 !important;
                    }
                    .custom-select .ant-select-selection-item {
                        color: #fff !important;
                        fontSize: 22px !important;
                        fontWeight: 600 !important;
                    }
                    .custom-select .ant-select-arrow {
                        opacity: 0.66 !important;
                        color: #fff !important;
                    }
                    .custom-select-dropdown .ant-select-item-option-selected {
                        background-color: #3D81FF !important;
                        color: #fff !important;
                    }
                    .custom-select-dropdown .ant-select-item-option-active:not(.ant-select-item-option-selected) {
                        background-color: rgba(61, 129, 255, 0.1) !important;
                        color: #fff !important;
                    }
                    .custom-select-dropdown .ant-select-item-option-content {
                        color: #fff !important;
                        font-size: 16px !important;
                        font-weight: 600 !important;
                    }
                `}</style>
                <Menu
                    openKeys={openKey}
                    selectedKeys={selectedKey}
                    items={menuItems}
                    onClick={value => setRouteActive(value)}
                    onOpenChange={value => setOpenKey(value)}
                    mode='inline'
                />
            </div>

            <div className='rightContent'>
                {/* <div style={{ width: '100%', backgroundColor: '#fff', marginBottom: '10px' }}> */}
                <div className='tabBarHeader'>
                    <Row className='tabBarRow'>
                        {/* <Col xs={16} sm={16} md={16} lg={16} xl={16} className='tabBarLeft'>
                            <img src={Logo} alt='logo' className='leftLogo' />

                            <Menu mode='horizontal' className='leftMenu' selectedKeys={[activeKey]} items={menuItems} onClick={value => setRouteActive(value)} />
                        </Col> */}

                        <Col xs={8} sm={8} md={8} lg={8} xl={8} className='tabBarRight'>
                            <Avatar className='tabBarRightAvaTor' src='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201707%2F31%2F20170731021444_2YUfe.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1669779871&t=ec025ed48a1668dee9cfa0e803b6f787' />

                            <span className='tabBarRightName'>{userInfo?.user_name_cn ? userInfo.user_name_cn : (userInfo?.user_name || '')}</span>

                            <Dropdown dropdownRender={dropDownMenu}>
                                <Button type='text' className='tabBarRightBtn'><SettingOutlined /></Button>
                            </Dropdown>
                        </Col>
                    </Row>
                </div>
                {/* </div> */}
                <div style={{ padding: '12px', height: '100%' }}>
                    <div className='rightContentMain'>
                        <Outlet />
                    </div>
                </div>

            </div>
        </div>
    )
}

export default SystemContentList


