import { useState } from 'react';
import { PageLoading } from '@ant-design/pro-layout';
import { notification, Modal, message } from 'antd';
import { RequestConfig, history } from 'umi';
import type { RequestOptionsInit } from 'umi-request';
import { UserDataType, addQiankunMicroApps, getQiankunMicroApps } 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 {url} = options;
  const _response: {
    errorMessage: any;
    message: any;
    data?: any;
    status: number;
    success?: boolean;
    msg?: string;
  } = await response.clone().json();


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

    if(url != '/centerSys/menu/checkKeygen'){
      message.success({
        content:`操作成功！`,
        duration:1
    });
    }

    return {
      status: _response.status,
      success: true,
    };
  } else {
    console.log({ _response });
    notification.error({
      message: '错误：',
      description:`${_response.msg ? _response.msg : _response.message ? _response.message : _response.errorMessage}`
    });
    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: '抱歉，你的登录已过期，请重新登录！',
        okText: '确定',
        cancelText: '取消',
        maskClosable: false,
        // cancelButtonProps:
        onOk: () => {
          logoutHandle();
          return Promise.resolve(true);
        },
      });
      return;
    }

    if (errorMessage.length > 20) {
      notification.error({
        message: ` ${errorCode}:出现错误！`,
        description: errorMessage,
      });
    } else if (false) {

    } else {
      notification.error({
        message: '错误',
        description:` ${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 = async () => {
  console.log('process.env', process.env);
  const { NODE_ENV } = process.env;
  //NODE_ENV == 'development'
  if (NODE_ENV == 'development') {
    return {
      apps: [
        // {
        //   name: 'microApp', // 唯一 id
        //   entry: '//localhost:8808', // 开发
        // },
        // {
        //   name: 'app1', // 唯一 id
        //   entry: '//120.27.235.181:8804',  //测试
        // },
        // {
        //   name: 'reviewMana', // 唯一 id
        //   entry: '//120.27.235.181:5000/pfmview/',
        //   //entry: '//localhost:8804',  //本地调试
        //   //entry: '//198.198.203.161:5000/pfmview/', //淮南
        // },
        {
          name: 'budgetManaSystem', // 唯一 id
          //entry: '//localhost:8002',
          entry: '//120.27.235.181:5000/perform/',  //开发
          //entry: '//47.96.149.190:5000/perform/', //演示
          //entry: '//198.198.203.161:5000/perform/', //淮南
        },
        {
          name: 'pfmBackMana', // 唯一 id
          //entry: '//localhost:8001'
          entry: '//120.27.235.181:5000/pfmManager/', // 开发
        },
        {
          name: 'CostAccountingSys', // 唯一 id
          entry: '//localhost:8001'
          //entry: '//120.27.235.181:5000/costAccount/', // 开发
        },
      ]
    }
  }else{
      const resp = await getQiankunMicroApps();
      if (resp) {
        return {
          apps:resp.list?resp.list:resp
        }
      }
  }
  
}


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

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

  return {
    masterState,
    setMasterState,
  };
}



// //@/pages/platform/setting/reports/index
export function patchRoutes({ routes }: { routes: any }) {

  const treeLoop = (treeData: any) => {

    if (treeData.path.indexOf('/platform') != -1) {
      if (treeData.routes) {
        const paths = [...new Array(100).keys()].map((a, index) => ({
          path: `${treeData.path == '/' ? '' : treeData.path}/reports/${index}`,
          exact: true,
          component: require('@/pages/platform/setting/reports/index.tsx').default,
        }));

        const lanhuPagePaths = [...new Array(100).keys()].map((a, index) => ({
          path: `${treeData.path == '/' ? '' : treeData.path}/static/${index}`,
          exact: true,
          component: require('@/pages/platform/setting/static/index.tsx').default,
        }));

        //console.log({paths});

        paths.forEach((a: any) => {
          treeData.routes.push(a);
        });

        lanhuPagePaths.forEach((a: any) => {
          treeData.routes.push(a);
        });
      }
    }

    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,
  };
};
