import React,{useEffect,useState} from 'react';
import { Settings as LayoutSettings, PageLoading } from '@ant-design/pro-layout';
import {message, notification} from 'antd';
import qs from 'qs';
import { history, RequestConfig, RunTimeLayoutConfig, ErrorShowType } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { ResponseError } from 'umi-request';
import {
  queryCurrent,
  selectNavList
} from './services/user';
import defaultSettings from '../config/defaultSettings';
import DataTable from "@/components/common/DataTable";

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

export async function getInitialState(): Promise<{
  settings?: LayoutSettings;
  currentUser?: API.CurrentUser;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  fetchNavList?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const currentUser = await queryCurrent();
      currentUser.data.token = currentUser.token;
      return currentUser.data;
    } catch (error) {
      history.push('/user/login');
    }
    return undefined;
  };
  const fetchNavList = async () => {
    try {
      const currentNavList = await selectNavList();
      return currentNavList.data;
    } catch (error) {
      history.push('/user/login');
    }
    return undefined;
  };
  // 如果是登录页面，不执行
  if (history.location.pathname !== '/user/login') {
    const currentUser = await fetchUserInfo();
    const currentNavList = await fetchNavList();
    return {
      fetchUserInfo,
      fetchNavList,
      currentUser,
      currentNavList,
      settings: defaultSettings,
    };
  }
  return {
    fetchUserInfo,
    fetchNavList,
    settings: defaultSettings,
  };
}

export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== '/user/login') {
        history.push('/user/login');
      }
    },
    menuDataRender: (menuData)=>{
      console.debug(initialState)
      if(initialState.currentNavList && initialState.currentNavList.length>0){
        return [{
          name: 'list.table-list',
          icon: 'table',
          path: '/order',
          component: './Order/Billing',
        },{
          path: '/welcome',
          name: 'welcome',
          icon: 'smile',
          hideInMenu: true,
          component: './Welcome',
        }]
      }
       return [];
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};

/**
 * 异常处理程序
 * {
 *  "name":"BizError",        //name 为BizError是因为success为false
 *  "data":{
 *    "error":[{"field":"","message":"账号或密码不匹配。"}],
 *    "token":"90c77e0f-cd3b-4555-89bf-21b69dc8b454"
 *  },
 *  "info":{
 *    "success":false,
 *    "data":null,
 *    "errorCode":"",
 *    "errorMessage":"账号或密码不匹配。",
 *    "showType":2,
 *    "traceId":"-1",
 *    "host":"-1"
 *  }
 * }
 */
const errorHandler = (error: ResponseError) => {
  const { info } = error;
  if (error.name === 'BizError') {
    if(info.errorCode === '403'){
      message.warning('登录超时请重新登录');
      history.push('/user/login');
    }else{
      message.warning(info.errorMessage);
    }
  }
  if (!info) {
    notification.error({
      description: '您的网络发生异常，无法连接服务器',
      message: '网络异常',
    });
  }
  throw info;
};

export const request: RequestConfig = {
  errorHandler,
  errorConfig: {
    adaptor: (resData,ctx)=>{
      return {
        success: resData.error && resData.error.length === 0,
          data: resData.error || null,
        errorCode: (resData.error && resData.error.length > 0) ? resData.error[0].field : 0,
        errorMessage: (resData.error && resData.error.length > 0) ? resData.error[0].message : '',
        showType: (resData.error && resData.error.length > 0) ? (resData.error[0].field === '403' ? ErrorShowType.REDIRECT : ErrorShowType.ERROR_MESSAGE) : 0,
        traceId: ctx.res ? ctx.res.token : '',
        host: ctx.req ? ctx.req.originUrl : '-1',
      };
    },
    errorPage: '/user/login',       // showType为9是跳这个地址
  },
  requestInterceptors: [
    (url, config) => {
      if (config.method === 'post') {
        config.data = qs.stringify({
          ...(config.data || {}),
        });
      }
      config.headers = {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;',
        'X-Requested-With' : 'XMLHttpRequest',
      }
      return {
        url: `${url}`,
        options: { ...config, interceptors: true },
      };
    },
  ],
  middlewares: [
    async function middlewareA(ctx, next) {
      await next();
    }
  ],
  responseInterceptors: [
    async (config) => {
      return config;
    }
  ]
};
