/*
 * @Author: your name
 * @Date: 2021-09-03 14:28:27
 * @LastEditTime: 2021-10-18 11:43:58
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /MedicalWisdomCheckSys/src/app.tsx
 */
import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import { RunTimeLayoutConfig } from 'umi';
import { history, Link } from 'umi';
import { notification, Modal } from 'antd';

import RightContent from '@/components/RightContent';
// import Footer from '@/components/Footer';
// import { currentUser as queryCurrentUser } from './services/ant-design-pro/api';
import { BookOutlined, LinkOutlined } from '@ant-design/icons';
import iconEnum from './menuIcons';
import {loginOut} from '@/utils';
import logoIcon from '../public/logo.png';

import { getMenus } from './services/user';
import {updateUserInfo} from '@/pages/user/Login/service'; 

const isDev = process.env.NODE_ENV === 'development';

const loginPath = '/user/login';

let hospSign:any='';

if(history){
  hospSign = history.location.query?.hospSign;
  if(!hospSign){
    hospSign = localStorage.getItem('hospSign');
  }
}


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


type menuDataItemType = {
  path:string,
  name:string,
  icon:any,
  component:string,
  children?:menuDataItemType[]
}

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUserData;
  logo?:String;
  isDev?:boolean,
  goSetting?:boolean,//设置栏触发
  resetPasswordHandle?:(formData:any)=>Promise<boolean>,
  fetchUserMenu?:()=>Promise<menuDataItemType[]>,
  menu?:menuDataItemType[],
  clearUserData?:() => Promise<boolean>;  //清空用户数据
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {

  const fetchUserInfo = async () => {
    try {
      const userData = localStorage.getItem('userData');
      if(userData){
        return JSON.parse(userData);
      }
      throw Error;
    } catch (error) {
     
      history.push(`${loginPath}?hospSign=${hospSign}`);
    }
    return undefined;
  };

  const fetchUserMenu = async ()=>{
      const menu =  await getMenus();
      if(menu){
           return menu;
      }
  }

  const resetPasswordHandle = async (data:API.EditUserInfoType)=>{
        const resp = await updateUserInfo(data);
        if(resp){
          return Promise.resolve(true);
        }
        return Promise.resolve(false);
  }

  const clearUserData = ()=>{
      localStorage.removeItem('userData');
      return Promise.resolve(true);
  };
  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      logo:logoIcon,
      clearUserData,
      menu:[],
      fetchUserMenu,
      resetPasswordHandle,
      isDev:process.env.NODE_ENV == 'development',
      settings: {
         navTheme:'dark',
         layout:'side'
      },
    };
  }

  return {
    fetchUserInfo,
    settings: {},
  };
}


type RequestOptionsInit = {
     [propsName:string]:any
}

const authHeaderInterceptor = (url: string, options: RequestOptionsInit) => {
  
  const userData = localStorage.getItem('userData');
  let authHeader = {token:''};
  

  if(userData){
       const {token}:API.CurrentUserData = JSON.parse(userData);
       authHeader.token = token;
  }
  return {
    url: `${url}`,
    options: { ...options, interceptors: true, headers: authHeader },
  };

};


const responseInterceptors = async (response: Response, options: RequestOptionsInit) => {
  // console.log({response,options});
  const requestMethod = options.method;
  const url = options.url;
  try {
    const {status} = response;
    if(status == 200){
        //网络请求成功
        const _response = await response.clone().json();
        const { status: dataStatus,errorCode,errorMessage,data} = _response;
        if(dataStatus == 200){
             //接口请求成功
             if(requestMethod=='POST'&&url != "/api/pfm/login"){
               notification.success({
                message:'操作成功！'
               });
             }

             if(data){
              return data;
             }
             return true;
        }else if(errorCode == 499){
          Modal.confirm({
            title: '抱歉，登录已过期请重新登录！',
            onOk: () => {
              loginOut();
            }
          });
        }else {
             //接口请求信息错误
             notification.error({
              message:errorMessage
             });
        }
        
    }else {
      //网络请求失败
       notification.error({
        message:'服务器错误！'
       });
       throw Error;
    }
  }catch(error){
      console.log({error});    
  }
  
  return response;
};


type RequestConfig = {
  [propsName:string]:any
}

export const request: RequestConfig = {
  // 新增自动添加AccessToken的请求前拦截器
  errorHandler: (error:any) => {
    console.log({ error });
    throw error;
  },
  requestInterceptors: [authHeaderInterceptor],
  responseInterceptors: [responseInterceptors],
};



//将服务端获取的菜单 icon 字符串映射为对应的 icon Dom
const mappingIcon = (menuData:menuDataItemType[]) => {
  if(menuData.length==0){
      console.log('空菜单');
      return [
        {
          path:'',
          name: '',
          icon: '',
          component: './404',
        }
      ]
  }else {
    const mappingMenu:menuDataItemType[] = menuData.map(item => ({
      ...item,
      icon: item.icon&&iconEnum[item.icon],
      children: item.children ? mappingIcon(item.children) : [],
    }));
    return mappingMenu;
  }
  
};



// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
 
  return {
    logo:initialState?.logo,
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      // content: initialState?.currentUser?.name,
    },
    // footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(`${loginPath}?hospSign=${hospSign}`);
      }
    },
    menu: {

      params:{
        currentUser:initialState?.currentUser
      },
      request: async () => {
        // initialState.currentUser 中包含了所有用户信息
        if(initialState){
          const { currentUser,isDev} = initialState;
          if(isDev){
            //开发环境或超级账号
            return []
          }
      
          if (currentUser) {
            const data:menuDataItemType[] = await getMenus();
            
            if(data){
              return mappingIcon(data);
            }
          } else {
            return [
              {
                component: './404',
              }
            ]
          }
        }
        return []
      },
    },
    links: isDev
      ? [
          <Link to="/umi/plugin/openapi" target="_blank">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </Link>,
          <Link to="/~docs">
            <BookOutlined />
            <span>业务组件文档</span>
          </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};
