import React from 'react';
import { BasicLayoutProps, Settings as LayoutSettings, MenuDataItem } from '@ant-design/pro-layout';
import { Button, notification, Result } from 'antd';
import { history } from 'umi';
import RightContent from '@/components/RightContent';
import { ResponseError } from 'umi-request';
import { queryCurrent, getMenu } from './services/user';
import defaultSettings from '../config/defaultSettings';
import { DesktopOutlined, MessageOutlined, SendOutlined, TeamOutlined, QrcodeOutlined, DatabaseOutlined, ReadOutlined, MobileOutlined, FundViewOutlined, RadarChartOutlined, BarChartOutlined, WechatOutlined, BookOutlined, FileImageOutlined, EyeOutlined, UserOutlined } from '@ant-design/icons';
import { getMyMenu, headrRouter } from '../config/routerConfig';
import { ReactComponent as LaunchSvg } from '@/assets/launch.svg'
import { ReactComponent as AdLaunchSvg } from '@/assets/adLaunch.svg'
import { ReactComponent as MaterialSvg } from '@/assets/material.svg'
import { ReactComponent as NumberSvg } from '@/assets/number.svg'
import { ReactComponent as GameSvg } from '@/assets/game.svg'
import { ReactComponent as GameServerSvg } from '@/assets/gameServer.svg'
import { ReactComponent as MediaSvg } from '@/assets/media.svg'
import { ReactComponent as PlayerSvg } from '@/assets/player.svg'
import { ReactComponent as RoleManageSvg } from '@/assets/roleManage.svg'
import { ReactComponent as MonitorSvg } from '@/assets/monitor.svg'
import versions from './utils/versions';


interface CurrentUser {
    avatar?: string;
    name?: string;
    title?: string;
    group?: string;
    signature?: string;
    tags?: {
        key: string;
        label: string;
    }[];
    userId?: string;
    powerLevel?: number;
    access?: 'user' | 'guest' | 'admin' | any;
    unreadCount?: number;
    companyList?: any[],
    onlineCompanyId?: number
}

export async function getInitialState(): Promise<{
    currentUser?: CurrentUser;
    settings?: LayoutSettings;
    menu?: any,
    loading?: boolean,
    collapsed?: string,
    onCollapse?: (onCollapse: boolean) => void
}> {
    // 如果是登录页面，不执行
    if (localStorage.getItem('Admin-Token')) {
        //开始版本号对比
        versions()
        try {
            sessionStorage.removeItem('msg')
            let currentUser = {}
            let userInfo: any = await queryCurrent();//用户信息
            let companyInfo = userInfo?.data?.companyRelationInfo?.filter((item: { companyId: number }) => item.companyId !== 4 && item.companyId !== 3)
            currentUser = { access: 'admin', powerLevel: userInfo?.data?.userInfo?.powerLevel, name: userInfo?.data?.userInfo?.nickname || '', userId: userInfo?.data?.userInfo?.userId, phone: userInfo?.data?.userInfo?.phone || '', companyList: companyInfo, onlineCompanyId: userInfo?.data?.onlineCompanyId }//处理个人信息 
            let menu: any = await getMenu().then((res: any) => {//获取菜单并处理
                let { code, data } = res
                let path = getMyMenu(code, data)
                return { data: path }
            });
            localStorage.setItem('sex', userInfo?.data?.userInfo?.sex)
            localStorage.setItem('userId', userInfo?.data?.userInfo?.userId)
            localStorage.setItem('name', userInfo?.data?.userInfo?.nickname)
            return {
                currentUser,
                settings: { ...defaultSettings },
                loading: false,
                menu: { ...menu, data: menu?.data?.reverse() },
                collapsed: '0',
                onCollapse: (collapsed: boolean) => {
                    let v = collapsed ? '1' : '0'
                    localStorage.setItem('collapsed', v)

                }
            };
        } catch (error) {
            console.log(111111, error)
            history.push('/user/login');
        }
    }
    return {
        settings: defaultSettings,
    };
}
// 枚举转译服务端菜单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 />,
    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>,
    number: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><NumberSvg /></span>,
    game: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><GameSvg /></span>,
    gameServer: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><GameServerSvg /></span>,
    media: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><MediaSvg /></span>,
    player: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><PlayerSvg /></span>,
    roleManage: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><RoleManageSvg /></span>,
    monitor: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><MonitorSvg /></span>,
    eye: <EyeOutlined />
};
//处理菜单
const loopMenuItem = (menus: MenuDataItem[],): MenuDataItem[] => {
    let menu = menus?.map(({ icon, routes, roles, ...item }) => {
        let newItem = JSON.parse(JSON.stringify(item))
        newItem.key = item?.path || item?.key
        return {
            ...newItem,
            hideInMenu: false,//校验隐藏菜单
            icon: icon && IconMap[icon as keyof typeof IconMap],
            children: routes && loopMenuItem(routes),
        }
    })
    return menu
}
export const layout = ({
    initialState
}: {
    initialState: { settings?: LayoutSettings; currentUser?: CurrentUser; menu?: any; loading: boolean, collapsed: string, onCollapse: any };
}): BasicLayoutProps => {
    return {
        menuDataRender: () => {
            return loopMenuItem(initialState?.menu?.data || [])
        },//解析服务端菜单
        rightContentRender: () => <RightContent />,
        disableContentMargin: false,
        collapsed: localStorage.collapsed === '1',
        onCollapse: initialState.onCollapse,
        breakpoint: false,
        // footerRender: () => <Footer />,
        onPageChange: () => {
            headrRouter(initialState, history)
            let { pathname, query } = history.location
            if (query?.t) {//带token直接进入对应页面
                localStorage.setItem('Admin-Token', decodeURIComponent(query.t as any))
                location.href = window.location.origin + '/#' + pathname
                location.reload()
            } else if (!initialState?.currentUser?.name && history.location.pathname !== '/user/login') {
                history.push('/user/login');
            }
        },
        splitMenus: true,//配合mix分割菜单
        menuHeaderRender: undefined,
        ...initialState?.settings,
    };
};
const codeMessage = {
    200: '服务器成功返回请求的数据。',
    201: '新建或修改数据成功。',
    202: '一个请求已经进入后台排队（异步任务）。',
    204: '删除数据成功。',
    400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
    401: '用户没有权限（令牌、用户名、密码错误）。',
    403: '用户得到授权，但是访问是被禁止的。',
    404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
    405: '请求方法不被允许。',
    406: '请求的格式不可得。',
    410: '请求的资源被永久删除，且不会再得到的。',
    422: '当创建一个对象时，发生一个验证错误。',
    500: '服务器发生错误，请检查服务器。',
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。',
};

/**
 * 异常处理程序
 */
const errorHandler = (error: ResponseError) => {
    const { response } = error;
    if (response && response.status) {
        const errorText = codeMessage[response.status as keyof typeof codeMessage] || response.statusText;
        const { status, url } = response;
        notification.error({
            message: `请求错误 ${status}: ${url}`,
            description: errorText,
        });
    }

    if (!response) {
        notification.error({
            description: '您的网络发生异常，无法连接服务器',
            message: '网络异常',
        });
    }
    throw error;
};
//请求处理
export const request: any = {
    errorHandler,
    timeout: 300000,
    headers: { ['Authorization']: 'Bearer ' + localStorage.getItem('Admin-Token') },
    errorConfig: {
        adaptor: (resData: any) => {
            if (resData.code === 500) {
                let msg = sessionStorage.getItem('msg')
                if (resData.msg === '令牌验证失败') {//
                    if (history.location.pathname !== '/user/login') {
                        if (!msg) {
                            const key = `open${Date.now()}`;
                            const btn = (
                                <Button type="primary" onClick={() => {
                                    localStorage.removeItem('Admin-Token')
                                    history.push('/user/login')
                                    notification.close(key)
                                    sessionStorage.removeItem('msg')
                                }}>重新登录</Button>
                            );
                            const description = (
                                <Result
                                    status="500"
                                    title='令牌验证失败！'
                                    subTitle="长时间没有操作，令牌失效请重新登录！"
                                    extra={btn}
                                />
                            )
                            sessionStorage.setItem('msg', 'true')
                            notification.open({
                                message: '',
                                description,
                                duration: null,
                                getContainer: () => document.getElementById('notificationPop') || document.getElementById('root') as HTMLElement,
                                key,
                                style: { zIndex: 999999, right: '50%', top: '50%', transform: 'translate(50%, -50%)', position: 'fixed', transition: 'all 0s' },
                                onClose: () => {
                                    localStorage.removeItem('Admin-Token')
                                    history.push('/user/login')
                                    sessionStorage.removeItem('msg')
                                }
                            });
                        }
                        return { ...resData }
                    } else {
                        localStorage.removeItem('Admin-Token')
                    }
                }
                if (!msg) {
                    sessionStorage.setItem('msg', 'true')
                    notification.error({
                        message: resData.msg,
                        onClose: () => {
                            sessionStorage.removeItem('msg')
                        }
                    });
                }

            }
            if (resData.code === 310) {//权限错误
                let msg = sessionStorage.getItem('msg')
                localStorage.removeItem('Admin-Token')
                history.push('/user/login')
                if (!msg) {
                    sessionStorage.setItem('msg', 'true')
                    notification.error({
                        message: resData.msg,
                        onClose: () => {
                            sessionStorage.removeItem('msg')
                        }
                    });
                }
            }
            return {
                ...resData,
            }
        },
    },
};