import { SetStateAction, useCallback, useEffect, useState } from 'react'
import { Layout, Menu, Space, ConfigProvider, Watermark, App, message } from 'antd';
import { DesktopOutlined, MessageOutlined, SendOutlined, CloudOutlined, TeamOutlined, HomeOutlined, PaperClipOutlined, ContainerOutlined, AlipayCircleOutlined, StopOutlined, QrcodeOutlined, DatabaseOutlined, ReadOutlined, MobileOutlined, FundViewOutlined, RadarChartOutlined, BarChartOutlined, WechatOutlined, BookOutlined, FileImageOutlined, EyeOutlined, UserOutlined, AlertOutlined, FieldTimeOutlined, ApiOutlined } from '@ant-design/icons';
import { ReactComponent as LaunchSvg } from '../public/svg/launch.svg'
import { ReactComponent as AdLaunchSvg } from '../public/svg/adLaunch.svg'
import { ReactComponent as MaterialSvg } from '../public/svg/material.svg'
import { ReactComponent as GameSvg } from '../public/svg/game.svg'
import { ReactComponent as OrdrtListSvg } from '../public/svg/ordrtList.svg'
import { ReactComponent as PosSvg } from '../public/svg/pos.svg'
import { ReactComponent as PayInstallSvg } from '../public/svg/payInstall.svg'
import { ReactComponent as UseSvg } from '../public/svg/use.svg'
import { ReactComponent as PayBoxSvg } from '../public/svg/payBox.svg'
import { ReactComponent as ExtensionSvg } from '../public/svg/extension.svg'
import { ReactComponent as ExtensionListSvg } from '../public/svg/extensionList.svg'
import { ReactComponent as MediaSvg } from '../public/svg/media.svg'
import { ReactComponent as PositionSvg } from '../public/svg/position.svg'
import { ReactComponent as GameListSvg } from '../public/svg/gameList.svg'
import { ReactComponent as RoleListSvg } from '../public/svg/roleList.svg'
import { ReactComponent as RealNameSvg } from '../public/svg/realName.svg'
import { ReactComponent as CorpWechatSvg } from '../public/svg/corpWechat.svg'
import { ReactComponent as MsgSvg } from '../public/svg/msg.svg'
import { ReactComponent as WeComSvg } from '../public/svg/weCom.svg'
import { ReactComponent as BusinessPlanSvg } from '../public/svg/businessPlan.svg'
import { ReactComponent as ImageSvg } from '../public/svg/image.svg'
import { ReactComponent as BooKSvg } from '../public/svg/book.svg'
import { ReactComponent as PaSvg } from '../public/svg/pa.svg'
import { ReactComponent as GroupChatSendSvg } from '../public/svg/groupChatSend.svg'
import { ReactComponent as MomentsSvg } from '../public/svg/moments.svg'
import Avatar from './AvatarDropdown';
import styles from './index.less'
import { useLocation, useNavigate } from 'react-router-dom';
import globaStore from '../store';
import { getItem } from '@/utils/utils';
import zhCN from 'antd/locale/zh_CN';
import moment from 'dayjs';
import 'dayjs/locale/zh-cn';
import useNewToken from '@/Hook/useNewToken';
import React from 'react';
import { useInterval, useLocalStorageState, useUpdateEffect } from 'ahooks';
import versions from '@/utils/versions';
moment.locale('zh-cn');
const { Header, Content, Sider } = Layout;
type Props = {
    data: any,//路由数据
    name: string,//当前路由名称对应data的key
    children: any,//渲染的数据
}

// =====================枚举转译服务端菜单icon=====================
const IconMap = {
    desktop: <DesktopOutlined />,
    message: <MessageOutlined />,
    send: <SendOutlined />,
    team: <TeamOutlined />,
    database: <DatabaseOutlined />,
    qrcode: <QrcodeOutlined />,
    read: <ReadOutlined />,
    mobile: <MobileOutlined />,
    fundView: <FundViewOutlined />,
    radarChart: <RadarChartOutlined />,
    barChart: <BarChartOutlined />,
    wechat: <WechatOutlined />,
    // book: <BookOutlined />,
    peoples: <UserOutlined />,
    'file-image': <FileImageOutlined />,
    pay: <AlipayCircleOutlined />,
    cloud: <CloudOutlined />,
    link: <PaperClipOutlined />,
    dashboard: <HomeOutlined />,
    time: <FieldTimeOutlined />,
    launch: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><LaunchSvg /></span>,
    adLaunch: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><AdLaunchSvg /></span>,
    material: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><MaterialSvg /></span>,
    game: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><GameSvg /></span>,
    order: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><OrdrtListSvg /></span>,
    pos: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><PosSvg /></span>,
    payInstall: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><PayInstallSvg /></span>,
    use: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><UseSvg /></span>,
    payBox: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><PayBoxSvg /></span>,
    extension: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><ExtensionSvg /></span>,
    extensionList: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><ExtensionListSvg /></span>,
    media: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><MediaSvg /></span>,
    position: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><PositionSvg /></span>,
    gameList: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><GameListSvg /></span>,
    roleList: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><RoleListSvg /></span>,
    realName: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><RealNameSvg /></span>,
    corpWechat: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><CorpWechatSvg /></span>,
    msg: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><MsgSvg /></span>,
    weCom: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><WeComSvg /></span>,
    businessPlan: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><BusinessPlanSvg /></span>,
    image: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><ImageSvg /></span>,
    book: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><BooKSvg /></span>,
    pa: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><PaSvg /></span>,
    groupChatSend: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><GroupChatSendSvg /></span>,
    moments: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><MomentsSvg /></span>,
    interdiction: <StopOutlined />,
    eye: <EyeOutlined />,
    alert: <AlertOutlined />,
    log: <ContainerOutlined />,
    apiOutlined: <ApiOutlined />
};

export const DispatchContext = React.createContext<{ config: any } | null>(null);
/**
 * 菜单路由
 * @param data 路由数据   clientele
 * @param name 当前路由名称对应data的key
 * */
function MainLayout(props: Props) {
    let { data, name } = props
    const [topKey] = useState([name])
    const [letKey, setLetKey] = useState([])
    const [topMenu, setTopMenu] = useState<any>([])
    const [leftMenu, setLeftMenu] = useState<any>([])
    const { themeConfig } = useNewToken();
    const [config] = useState(themeConfig);
    const navigate = useNavigate();//跳转
    // =====================顶部菜单点击事件=====================

    const getParentKeys = (path) => {
        const keys = [];
        path.split('/').reduce((prev, curr) => {
            const key = `${prev}/${curr}`.replace('//', '/');
            if (key !== '/') keys.push(key);
            return key;
        });
        keys.shift()
        return keys;
    };
    const location1 = useLocation();
    const [openKeys, setOpenKeys] = useState(getParentKeys(location1.pathname));

    const handleTopKey = useCallback((menu: { pData: any; key: string; }) => {
        let topOpen = localStorage.getItem('topOpen')
        data = menu?.pData || data
        sessionStorage.setItem('name', menu.key)
        if (topOpen == '1') {//打开新页面
            window.open(window.location.origin + data[menu.key][0].path)
        } else {//当前页面
            if (name !== menu.key) {
                window.location.href = window.location.origin + data[menu.key][0].path
                let oldPath = sessionStorage.getItem('oldPath')
                if (!oldPath || oldPath?.split('/')?.length <= 2 || oldPath?.split('/')[1] !== menu.key) {//不存在路径或者路径的长度小于2或者主路径对不上
                    sessionStorage.setItem('oldPath', data[menu.key][0].path)
                }
            }
        }
    }, [data])

    //=====================左侧菜单点击事件=====================
    const handleLetKey = useCallback((menu: { domEvent: { target: { innerText: string; }; }; key: string; keyPath: SetStateAction<string[]>; }) => {
        handleTitle(menu?.domEvent?.target?.innerText)//设置title
        setLetKey([menu.key])
        setOpenKeys(menu.keyPath)//在这可以关闭上次展开的菜单
        let path = menu.key
        if (path) {
            navigate(path)
            sessionStorage.setItem('oldPath', path)
        }
    }, [data])
    // =====================首次默认跳转第一个菜单=====================
    useEffect(() => {
        let clickName = sessionStorage.getItem('name')
        if (clickName === 'imChat') {
            clickName = ''
            sessionStorage.removeItem('name')
        }
        const oldPath = location.hash.replace('#', '').split('?')?.[0]
        const thatName = name
        if (clickName && data[clickName]) {
            if (thatName !== clickName) {//更换一级菜单
                handleTopKey({
                    key: clickName,
                    pData: data
                })
            }
        }
        if (data[name]) {
            const item = data[thatName][0].children[0]
            if (!data[thatName][0].children[0]) {
                message.error('没有下级菜单，请联系管理员，确认是否开通了系统及菜单')
                return
            }
            let path = ''
            if (oldPath && oldPath?.split('/').length > 2) {//刷新页面时
                path = oldPath
            } else if (item?.children?.length > 0) {//假如有子菜单
                path = item?.children[0]?.path

            } else {//没有子菜单
                path = item?.path
            }
            navigate(path)//跳转到指定页面
            setLetKey([path])//指定页面名称选中样式
        }

        if (data) {
            // 顶部菜单
            const TopMenu = Object.values(data).sort((a: any, b: any) => { return a[0]?.orderNum - b[0]?.orderNum }).map((r: any) => {
                return getItem(r[0]?.title, r[0]?.belongPlatform, IconMap[r[0]?.icon as keyof typeof IconMap])
            })
            if (!sessionStorage.getItem('name') && TopMenu?.length > 0) {
                sessionStorage.setItem('name', TopMenu[0]?.key as string)
            }
            setTopMenu(TopMenu)
        }
    }, [data])

    useUpdateEffect(() => {
        const newKey = location.hash.replace('#', '').split('?')?.[0]
        if (newKey !== letKey?.[0]) {
            setLetKey([newKey])
        }
    }, [location.href])
    // ================后期items=================
    useEffect(() => {
        if (topKey && data[topKey[0]]) {
            const LeftMenu = data[topKey[0]][0].children.map((item: any, i: number) => {
                if (item.children?.length > 0) {
                    return getItem(item?.title, item?.path, IconMap[item?.icon as keyof typeof IconMap], item.children)
                }
                return getItem(item?.title, item?.path, IconMap[item?.icon as keyof typeof IconMap])
            })
            setLeftMenu(() => LeftMenu)
        }
    }, [topKey, data])

    const handleTitle = useCallback((str: string) => {
        if (str) {
            let title = document.head.getElementsByTagName('title')[0]
            let text = '趣程企微管理后台' + '-' + str
            title.innerText = text
        }
    }, [])

    // 版本
    useEffect(() => {
        versions()
    }, [])
    useInterval(versions, 1000 * 60);

    return <ConfigProvider
        /**语言*/
        locale={zhCN}
        /**尺寸*/
        componentSize='middle'
        theme={{
            ...config.default, token: {
                ...config.default.token,
            },
            algorithm: [...config.default.algorithm, ...config.algorithm]
        }}
    >
        <App>
            <div style={{ background: `url(${config?.myBgUrl || (config.bgUrl as any)[config.acPrimary]}) no-repeat 0% 0% /cover` }}>
                <Layout>
                    {/* 顶部 */}
                    <Header className={styles.header} style={{ borderBottom: '1px solid rgba(5, 5, 5, 0.06)' }}>
                        {/* logo */}
                        <div className={styles.logo} style={{ width: (globaStore.data.isMobile || globaStore.data.collapsed) ? '48px' : '205px' }}>
                            <Space size={16} align='center'>
                                <div style={{ display: 'flex' }}> <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" viewBox="0 0 200 200"><defs><linearGradient id="linearGradient-1" x1="62.102%" x2="108.197%" y1="0%" y2="37.864%"><stop offset="0%" stopColor="#4285EB"></stop><stop offset="100%" stopColor="#2EC7FF"></stop></linearGradient><linearGradient id="linearGradient-2" x1="69.644%" x2="54.043%" y1="0%" y2="108.457%"><stop offset="0%" stopColor="#29CDFF"></stop><stop offset="37.86%" stopColor="#148EFF"></stop><stop offset="100%" stopColor="#0A60FF"></stop></linearGradient><linearGradient id="linearGradient-3" x1="69.691%" x2="16.723%" y1="-12.974%" y2="117.391%"><stop offset="0%" stopColor="#FA816E"></stop><stop offset="41.473%" stopColor="#F74A5C"></stop><stop offset="100%" stopColor="#F51D2C"></stop></linearGradient><linearGradient id="linearGradient-4" x1="68.128%" x2="30.44%" y1="-35.691%" y2="114.943%"><stop offset="0%" stopColor="#FA8E7D"></stop><stop offset="51.264%" stopColor="#F74A5C"></stop><stop offset="100%" stopColor="#F51D2C"></stop></linearGradient></defs><g fill="none" fillRule="evenodd" stroke="none" strokeWidth="1"><g transform="translate(-20 -20)"><g transform="translate(20 20)"><g><g fillRule="nonzero"><g><path fill="url(#linearGradient-1)" d="M91.588 4.177L4.18 91.513a11.981 11.981 0 000 16.974l87.408 87.336a12.005 12.005 0 0016.989 0l36.648-36.618c4.209-4.205 4.209-11.023 0-15.228-4.208-4.205-11.031-4.205-15.24 0l-27.783 27.76c-1.17 1.169-2.945 1.169-4.114 0l-69.802-69.744c-1.17-1.169-1.17-2.942 0-4.11l69.802-69.745c1.17-1.169 2.944-1.169 4.114 0l27.783 27.76c4.209 4.205 11.032 4.205 15.24 0 4.209-4.205 4.209-11.022 0-15.227L108.581 4.056c-4.719-4.594-12.312-4.557-16.993.12z"></path><path fill="url(#linearGradient-2)" d="M91.588 4.177L4.18 91.513a11.981 11.981 0 000 16.974l87.408 87.336a12.005 12.005 0 0016.989 0l36.648-36.618c4.209-4.205 4.209-11.023 0-15.228-4.208-4.205-11.031-4.205-15.24 0l-27.783 27.76c-1.17 1.169-2.945 1.169-4.114 0l-69.802-69.744c-1.17-1.169-1.17-2.942 0-4.11l69.802-69.745c2.912-2.51 7.664-7.596 14.642-8.786 5.186-.883 10.855 1.062 17.009 5.837L108.58 4.056c-4.719-4.594-12.312-4.557-16.993.12z"></path></g><path fill="url(#linearGradient-3)" d="M153.686 135.855c4.208 4.205 11.031 4.205 15.24 0l27.034-27.012c4.7-4.696 4.7-12.28 0-16.974l-27.27-27.15c-4.218-4.2-11.043-4.195-15.254.013-4.209 4.205-4.209 11.022 0 15.227l18.418 18.403c1.17 1.169 1.17 2.943 0 4.111l-18.168 18.154c-4.209 4.205-4.209 11.023 0 15.228z"></path></g><ellipse cx="100.519" cy="100.437" fill="url(#linearGradient-4)" rx="23.6" ry="23.581"></ellipse></g></g></g></g></svg></div>
                                {(!globaStore.data.isMobile && !globaStore.data.collapsed) && <h2 style={{ color: 'white', margin: 0 }}>企微运营系统</h2>}
                            </Space>
                        </div>
                        <Menu items={topMenu} mode="horizontal" onClick={(menu: any) => { handleTopKey(menu) }} selectedKeys={topKey} style={{ width: '55%', borderBottom: 0, background: 'transparent' }} />
                        {/* 右侧操作 */}
                        <div className={styles.action}>
                            <Space className={`${styles.right} ${styles.dark}`} >
                                <Avatar config={config} />
                            </Space>
                        </div>
                    </Header>
                    <Layout>
                        {/* 左侧菜单 */}
                        <Sider
                            width={230}
                            className={`site-layout-background ${styles.sider}`}
                            breakpoint="lg"
                            collapsedWidth={globaStore.data.isMobile ? '0' : '80'}
                            collapsible
                            id={styles.sider}
                            collapsed={globaStore.data.collapsed}
                            onCollapse={(c) => {
                                globaStore.menuCollapsed(c)
                            }}
                            trigger={!globaStore.data.isMobile && null}
                        >
                            <Menu
                                mode="inline"
                                style={{ height: '100%' }}
                                openKeys={openKeys}
                                onClick={(menu: any) => { handleLetKey(menu) }}
                                onOpenChange={setOpenKeys}
                                selectedKeys={letKey}
                                items={leftMenu}
                                theme="dark"
                            />
                        </Sider>
                        {/* 内容 */}
                        <Layout style={{ position: 'relative', background: 'transparent' }} >
                            <Watermark content={sessionStorage.getItem('userName') || ''} gap={[100, 100]} font={{ color: 'rgba(255, 93, 93, 0.1)', fontSize: 20 }}>
                                <Content
                                    className={`site-layout-background ${styles.section}`}
                                    style={{
                                        padding: '20px 0 0 16px',
                                        boxSizing: 'border-box',
                                        margin: 0,
                                        minHeight: 280,
                                        backgroundColor: '#f0f2f5'
                                    }}
                                >
                                    <div style={{ marginRight: 16, paddingBottom: 10, position: 'relative' }}>{props.children}</div>
                                </Content>
                            </Watermark>
                        </Layout>
                    </Layout>
                </Layout>
            </div>
        </App>
    </ConfigProvider>
}
export default MainLayout