import React from 'react';
import { BasicLayoutProps, Settings as LayoutSettings, MenuDataItem } from '@ant-design/pro-layout';
import { Button, notification, Result } from 'antd';
import { history, RequestConfig } 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, UserSwitchOutlined } 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 GdtSvg } from '@/assets/gdt.svg'
import { ReactComponent as MonitorSvg } from '@/assets/monitor.svg'
import { ReactComponent as AssetSvg } from '@/assets/asset.svg'
import { ReactComponent as AssetLibrarySvg } from '@/assets/assetLibrary.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 (sessionStorage.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(async (res: any) => {//获取菜单并处理
        let { code, data } = res
        let path = getMyMenu(code, data)
        if (userInfo?.data?.userInfo?.account === 'admin' && path.length > 0) {//假如是ADMIN加入api测试
          path[0].routes.push({ key: 0, path: '/operatePage/apitest', name: 'api测试', icon: '', component: './operatePage/apitest', roles: 'admin' })
        }
        return { data: path.reverse() }
      });
      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,
        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>,
  gdt: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><GdtSvg /></span>,
  monitor: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><MonitorSvg /></span>,
  eye: <EyeOutlined />,
  user: <UserSwitchOutlined />,
  asset: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><AssetSvg /></span>,
  assetLibrary: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><AssetLibrarySvg /></span>,
};
//处理菜单
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 string],
      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直接进入对应页面
        sessionStorage.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] || response.statusText;
    const { status, url } = response;
    notification.error({
      message: `请求错误 ${status}: ${url}`,
      description: errorText,
    });
  }

  if (!response) {
    notification.error({
      description: '您的网络发生异常，无法连接服务器',
      message: '网络异常',
    });
  }
  throw error;
};
//请求处理
export const request: RequestConfig = {
  errorHandler,
  timeout: 300000,
  headers: { ['Authorization']: 'Bearer ' + sessionStorage.getItem('Admin-Token') },
  errorConfig: {
    adaptor: (resData: any) => {
      let div: any
      // if (!document.getElementById('notificationPop')) {
      //   div = document.createElement('div')
      //   div.id = 'notificationPop'
      // }
      if (resData.code === 500) {
        let msg = sessionStorage.getItem('msg')
        if (resData.msg === '令牌验证失败') {//
          if (history.location.pathname !== '/user/login') {
            if (!msg) {
              // document.body.appendChild(div)
              const key = `open${Date.now()}`;
              const btn = (
                <Button type="primary" onClick={() => {
                  // setCookie('Admin-Token', '1', -300)
                  sessionStorage.removeItem('Admin-Token')
                  history.push('/user/login')
                  notification.close(key)
                  sessionStorage.removeItem('msg')
                  // document.body.removeChild(div)
                }}>
                  重新登录
                </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: () => {
                  // setCookie('Admin-Token', '1', -300)
                  sessionStorage.removeItem('Admin-Token')
                  history.push('/user/login')
                  sessionStorage.removeItem('msg')
                  // document.body.removeChild(div)
                }
              });
            }
            return { ...resData }
          } else {
            sessionStorage.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')
        sessionStorage.removeItem('Admin-Token')
        history.push('/user/login')
        if (!msg) {
          sessionStorage.setItem('msg', 'true')
          notification.error({
            message: resData.msg,
            onClose: () => {
              sessionStorage.removeItem('msg')
            }
          });
        }
      }
      return {
        ...resData,
      }
    },
  },
};