import { useState } from 'react';
import { PageLoading } from '@ant-design/pro-layout';
import { notification, Modal } from 'antd';
import { RequestConfig, history, useModel } from 'umi';
import type { RequestOptionsInit } from 'umi-request';
import { getHospSubSystemList, UserDataType } from '@/service/login';

import { BasicLayoutProps } from '@ant-design/pro-layout';
import { logoutHandle } from './global';
import { Platforms } from './constant';
import { SpacicalPageParamsType } from './typings';


const loginPath = '/login';

let hospSign: string = ''; //医院标识

if (history && history.location.query) {
  hospSign = history.location.query.hospSign as string;
  if (!hospSign) {
    const localHospSign = localStorage.getItem('hospSign');
    hospSign = localHospSign ? localHospSign : '';
  }
}

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

type InitialStateType = {
  userData?: UserDataType;
  systemLists?: TopBar.Tab[]; //当前医院可选子系统列表
  openedSysLists?: TopBar.Tab[]; //当前已打开的系统列表
  currentSelectedSys?: TopBar.Tab; //当前选中的tab
  logout?: () => Promise<boolean>;
  childAppIsShowMenu?:boolean; 
  spacicalPageParamsType?: SpacicalPageParamsType[];
  getHospSubSystemListFunc?: () => Promise<any[]>;
};

export async function getInitialState(): Promise<InitialStateType> {
  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 getAppIcon = (name: string) => {
    return Platforms.filter((i) => i.name == name).length > 0 ? Platforms.filter((i) => i.name == name)[0].logo : '';
  };

  //获取当前账号所有子应用列表
  const getHospSubSystemListFunc = async () => {
    const data = await getHospSubSystemList();
    if (data) {
      const _data = data.map((t) => ({
        ...t,
        icon: getAppIcon(t.name),
        path: t.path,
      }));

      return _data;
    }
    return [];
  };

  const logout = logoutHandle;

  const userData = await fetchUserInfo();

  let systemLists: userRelationInfo.OwnAppsItem[] = [];

  if (userData) {
    systemLists = await getHospSubSystemListFunc();
  }

  const localInitData = localStorage.getItem('initialState');

  return {
    currentSelectedSys: undefined,
    openedSysLists: [],
    ...JSON.parse(localInitData ? localInitData : '{}'), //覆盖，恢复tab状态
    userData,
    logout,
    spacicalPageParamsType: [],
    getHospSubSystemListFunc,
    systemLists: systemLists,
  };
}

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

  if (userData) {
    const { token } = JSON.parse(userData);
    authHeader.token = token;
  }

  return {
    url: `/gateway${url}`,
    options: { ...options, interceptors: true, headers: authHeader,timeout:100000000, },
  };
};

const responseInterceptorsHandle = async (response: Response, options: RequestOptionsInit) => {


  const _response: {
    data?: any;
    status: number;
    success?: boolean;
    msg?: string;
  } = await response.clone().json();

  
  if (_response.status == 200) {
    if (_response.data) {
      return _response.data;
    }

    notification.success({
      message: `操作成功！`,
    });
    return {
      status: _response.status,
      success: true,
    };
  } else {
    notification.error({
      message:`${_response.msg}`,
    });
    return false
  }
};

interface ErrorInfoStructure {
  success: boolean; // if request is success
  data?: any; // response data
  status?: number;
  errorCode: number;
  errorMessage: string;
  showType?: number;
  traceId?: string;
  host?: string;
}

interface ResponseErr extends Error {
  data?: any; // 这里是后端返回的原始数据
  info: ErrorInfoStructure;
}

const errorHandlerFunc = (error: ResponseErr) => {

  try {
    const { info } = error;
    const { errorCode , errorMessage } = info;
    
    if (errorCode == 499) {
      //token过期
      Modal.confirm({
        title: '抱歉，你的登录已过期，请重新登录！',
        // closable:false,
        maskClosable: false,
        // cancelButtonProps:
        onOk: () => {
          logoutHandle();
          return Promise.resolve(true);
        },
      });
      return;
    }

    if (errorMessage.length > 20) {
      notification.error({
        message: ` ${errorCode}:出现错误！`,
        description: errorMessage,
      });
    } else {
      notification.error({
        message: ` ${errorCode}:${errorMessage}`,
      });
    }
  } catch (err) {
    console.log({ errorHandlerFunc: err });
    notification.error({
      message: '遇到未知错误，查看控制台！',
    });
  }
};

export const request: RequestConfig = {
  timeout: 10000,
  errorConfig: {
    adaptor: (resData) => {

      if (!resData.success && resData.status != 200) {
        return {
          ...resData,
        };
      } else {
        return {
          success: true,
          status: 200,
        };
      }
    },
  },
  errorHandler: (err: any) => errorHandlerFunc(err),
  middlewares: [
    async function middlewareA(ctx, next) {
      await next();
    },
    async function middlewareB(ctx, next) {
      await next();
    },
  ],
  requestInterceptors: [requestInterceptorsHandle],
  responseInterceptors: [responseInterceptorsHandle],
};

// 从接口中获取子应用配置，export 出的 qiankun 变量是一个 promise
export const qiankun = fetch('/config').then(() => ({
  // 注册子应用信息
  apps: [
    // {
    //   name: 'microApp', // 唯一 id
    //   entry: '//localhost:8808', // 开发
    // },
    {
      name: 'app1', // 唯一 id
      entry: '//112.124.59.133:8804',  //测试
      //entry: '//118.31.245.65:8804', //线上
      //entry:'//192.168.50.143:8804',//本机
      //entry: '//localhost:8804', // 开发
    },
    {
      name: 'reviewMana', // 唯一 id
      entry: '//112.124.59.133:8807',  //测试
      //entry: '//118.31.245.65:8807', //线上
      //entry:'//192.168.50.143:8804',//本机
      //entry: '//localhost:8804', // 开发
    },
    {
      name: 'budgetManaSystem', // 唯一 id
      //entry: '//localhost:8001'
      entry: '//112.124.59.133:5000/perform/', // 开发
    },
    {
      name: 'PFMBackC', // 唯一 id
      entry: '//112.124.59.133:5000/pfmManager/index.html'
      //entry: '//112.124.59.133:5000/perform/', // 开发
    },
  ],
  // 完整生命周期钩子请看 https://qiankun.umijs.org/zh/api/#registermicroapps-apps-lifecycles
  lifeCycles: {
    afterMount: (props: any) => {},
  },
  // 支持更多的其他配置，详细看这里 https://qiankun.umijs.org/zh/api/#start-opts
}));

//向子应用透传
export function useQiankunStateForSlave() {

  const [masterState, setMasterState] = useState({});

  return {
    masterState,
    setMasterState,
  };
}



//@/pages/platform/setting/reports/index
export function patchRoutes({ routes }:{routes:any}) {
  const paths = [...new Array(100).keys()].map((a,index)=>({
    path: `/platform/setting/reports/${15+(index+1)}`,
    exact: true,
    component: require('@/pages/platform/setting/reports/index.tsx').default,
  }));


  const treeLoop = (treeData:any)=>{
        //console.log({treeData})
        if(treeData.path == '/platform'){
          paths.forEach((a:any)=>{
            treeData.routes.push(a); 
          })
          return;  
        }else{
            if(treeData.routes&&treeData.routes.length>0){
              treeData.routes.forEach((a:any)=>{
                  treeLoop(a);
              })
            }
        }
  }

  treeLoop(routes[0]);
}


export const layout = ({ initialState: { userData } }: { initialState: InitialStateType }): BasicLayoutProps => {
  return {
    headerRender: false,
    rightContentRender: () => <>right</>,
    footerRender: () => null,
    onPageChange: () => {
      //如果没有登录，重定向到 login
      if (!userData && location.pathname !== '/login') {
        // history.push('/login');
      }
    },
    menuHeaderRender: undefined,
    // ...initialState?.settings,
  };
};
