import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { setLocale } from 'umi';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig, RequestConfig } from 'umi';
import { history, Link, matchPath } from 'umi';
import type { RequestInterceptor, ResponseInterceptor } from 'umi-request';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { FormattedMessage } from 'umi';
import {
  currentUser as queryCurrentUser,
  token as getToken,
} from './services/mgr/api';
import {
  LinkOutlined,
  GoldOutlined,
  AppstoreAddOutlined,
  BarsOutlined,
  FundOutlined,
  ProfileOutlined,
  SettingOutlined,
  ScheduleOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { decodeToken } from 'react-jwt';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
let checkToken = true;

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * 菜单图标映射
 */
const iconMapping = {
  Gold: <GoldOutlined />,
  AppstoreAdd: <AppstoreAddOutlined />,
  bars: <BarsOutlined />,
  BarChartOutlined: <BarsOutlined />,
  FundOutlined: <FundOutlined />,
  profile: <ProfileOutlined />,
  setting: <SettingOutlined />,
  ScheduleOutlined: <ScheduleOutlined />,
  user: <UserOutlined />,
};

const authHeaderInterceptor: RequestInterceptor = (url, options) => {
  const token = localStorage.getItem('token');
  if (token && checkToken) {
    const decodedToken = decodeToken(token) as { exp: number };
    if (decodedToken) {
      const expSeconds = decodedToken.exp - Date.now().valueOf() / 1000;
      if (expSeconds > 0 && expSeconds < 3600) {
        checkToken = false;
        getToken()
          .then((value) => {
            if (value.success) {
              localStorage.setItem('token', value.data.token);
            }
          })
          .finally(() => {
            checkToken = true;
          });
      }
    }
  }
  const authHeader = token
    ? {
        Authorization: `Bearer ${token}`,
      }
    : {
        Authorization: '',
      };
  if (token) {
  }
  const prefix = process.env.NODE_ENV === 'development' ? '/api' : 'http://192.168.222.60:8088'
  return {
    url: prefix + url,
    options: {
      ...options,
      headers: {
        ...options.headers,
        ...authHeader,
      },
    },
  };
};
const _401ResponseInterceptor: ResponseInterceptor = (resp) => {
  if (resp.status == 401) {
    return {
      ...resp,
      json: async () => ({
        success: false,
        showType: 9,
        errorMessage: '',
      }),
      status: 200,
    };
  }
  return resp;
};

export const request: RequestConfig = {
  requestInterceptors: [authHeaderInterceptor],
  responseInterceptors: [_401ResponseInterceptor],
};

/**
 * 提取菜单数据所有的path属性
 *
 * @param data 菜单数据
 * @returns 菜单Path集合
 */
const extractMenuPath = (data: any[]) => {
  const stack = data.concat();
  const paths = [];
  while (stack.length !== 0) {
    const node = stack.pop();
    if (node?.path) {
      paths.push(node.path);
    }
    if (node?.routes) {
      for (let i = node?.routes.length - 1; i >= 0; i--) {
        if (node?.path && node.routes[i].path && node.routes[i].path?.substring(0, 1) != '/')
          node.routes[i].path = node.path + '/' + node.routes[i].path;
        stack.push(node.routes[i]);
      }
    }
  }
  return paths;
};

const extendMenuProp = (data: any[], defData: any[]) => {
  data.forEach((temp) => {
    let defTemp = defData.find((item) => {
      return item.name == temp.name;
    });
    if (defTemp) {
      temp.target = defTemp.target;
      temp.layout = defTemp.layout;
      let data2: any[] = temp.routes;
      let defData2: any[] = defTemp.routes;
      if (data2 != null) {
        data2.forEach((temp2) => {
          let defTemp2 = defData2?.find((item2) => {
            return temp2.name == item2.name;
          });
          if (defTemp2) {
            temp2.target = defTemp2.target;
            temp2.layout = defTemp2.layout;

            let data3: any[] = temp2.routes;
            let defData3: any[] = defTemp2.routes;
            if (data3 != null) {
              data3.forEach((temp3) => {
                let defTemp3 = defData3?.find((item3) => {
                  return temp3.name == item3.name;
                });
                if (defTemp3) {
                  temp3.target = defTemp3.target;
                  temp3.layout = defTemp3.layout;
                }
              });
            }
          }
        });
      }
    }
  });
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: Api.CurrentUser;
  menuPaths?: any;
  menuList?: any;
  permissions?: string[];
  loading?: boolean;
  fetchUserInfo?: () => Promise<Api.CurrentUser | undefined>;
}> {
  const token = history?.location?.query?.token as string | undefined;
  if (token) {
    localStorage.setItem('token', token);
  }
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      console.log('msgmsg', msg)
      if (msg && msg.code === 200) {
        return msg;
      } else {
        history.push(loginPath);
      }
    } catch (error) {
        history.push(loginPath);
    }
    return undefined;
  };
  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    console.log('currentUser', currentUser)
    if (currentUser && currentUser.user.locale) {
      console.log('locale', currentUser.user.locale)
      setLocale(currentUser.user.locale)
    }
    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}
if (!(typeof window !== 'undefined' && typeof window.document !== 'undefined')) {
  plus.screen.lockOrientation("landscape-primary"); // 把屏幕方向改变成横屏正方向
}
// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    menu: {
      params: {
        loginName: initialState?.currentUser?.user?.nickName,
      },
      request: async (params, defaultMenuData) => {
        if (params?.loginName) {
          const defaultResult = defaultMenuData.filter((item: any) => {
            return item.key?.substring(0, 3) == 'def';
          });
          const result = defaultResult;
          extendMenuProp([], defaultMenuData);
          const menuPaths = extractMenuPath(result);
          await setInitialState((s) => ({ ...s, menuPaths, menuList: result }));
          return result;
        } else return [];
      },
    },
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      // if (!initialState?.currentUser && location.pathname !== loginPath) {
      //   history.push(loginPath);
      // }
      // // 用于处理直接修改浏览器地址，进入页面
      // if (initialState?.menuPaths) {
      //   if (!matchPath(location.pathname, { path: initialState.menuPaths, exact: true })) {
      //     history.push('/404');
      //   }
      // }
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};
