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, getQiankunMicroApps } from '@/service/login';

import { logoutHandle } from './global';
import { KcimCenterSysId, Platforms } from './constant';
import { SpacicalPageParamsType } from './typings';
import { createFromIconfontCN } from '@ant-design/icons';
import { changeFavicon, getHospType, handleLogin } from './pages/login';
import { getSysParamsByCode } from './service';

// 全局变量声明
declare global {
  interface Window {
    isParentApp?: boolean;
  }
}

const loginPath = '/login';

// 获取医院标识
const getHospSign = (): string => {
  if (history?.location.query) {
    const queryHospSign = history.location.query.hospSign as string;
    if (queryHospSign) return queryHospSign;
  }
  return localStorage.getItem('hospSign') || '';
};

const hospSign = getHospSign();

const IconFont = createFromIconfontCN({
  scriptUrl: '/zhongtaiC.js',
}); 

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

interface InitialStateType {
  navData: any[];
  menuData: any[]; // 中台菜单
  customerType: string; // 客户类型
  userData?: UserDataType; // 登录返回用户信息
  userInfo: any; // 当前用户详细信息
  systemLists?: TopBar.Tab[]; // 当前医院可选子系统列表
  openedSysLists?: TopBar.Tab[]; // 当前已打开的系统列表
  currentSelectedSys?: TopBar.Tab; // 当前选中的tab
  logout?: () => Promise<boolean>;
  childAppIsShowMenu?: boolean;
  pageTitle: string;
  spacicalPageParamsType?: SpacicalPageParamsType[];
  getHospSubSystemListFunc?: () => Promise<any[]>;
}

interface MyRequestOptions extends RequestOptionsInit {
  prefix?: string; // 自定义前缀
}

/**
 * 获取用户信息
 */
const fetchUserInfo = async (): Promise<UserDataType | undefined> => {
  try {
    const queryParams = new URLSearchParams(location.search);
    const importUserData = queryParams.get('userData');
    const env = queryParams.get('env');

    if (importUserData) {
      localStorage.setItem('userData', importUserData);
      return JSON.parse(importUserData);
    }

    const userData = localStorage.getItem('userData');
    if (userData) {
      if (env === 'demo') {
        history.replace('/index');
      }
      return JSON.parse(userData);
    }

    if (env === 'demo') {
      const hospSign = queryParams.get('hospSign');
      const resp = await handleLogin('demo', '123456', hospSign || '');
      if (resp) {
        history.replace('/index');
        return resp;
      }
    }

    throw new Error('No user data found');
  } catch (error) {
    const currentUrlParams = new URLSearchParams(window.location.search);
    const defaultHospSign = 'yourDefaultHospSign';

    if (!currentUrlParams.has('hospSign')) {
      currentUrlParams.append('hospSign', defaultHospSign);
    }

    history.push(`${loginPath}?${currentUrlParams.toString()}`);
    return undefined;
  }
};

/**
 * 获取医院子系统列表
 */
const getHospSubSystemListFunc = async (): Promise<any[]> => {
  // TODO: 实现获取子系统列表的逻辑
  return [];
};

export async function getInitialState(): Promise<InitialStateType> {
  const logout = logoutHandle;
  const userData = await fetchUserInfo();

  let customerType: string | undefined;
  if (userData?.token) {
    customerType = await getHospType();
  }

  let systemLists: userRelationInfo.OwnAppsItem[] = [];
  if (userData) {
    systemLists = await getHospSubSystemListFunc();
  }

  const localInitData = localStorage.getItem('initialState');
  const currentSelectedTab = localStorage.getItem('currentSelectedTab');
  const currentSelectedSubHop = localStorage.getItem('currentSelectedSubHop');
  const userInfo = localStorage.getItem('userInfo');

  if (currentSelectedSubHop) {
    const { loginPic } = JSON.parse(currentSelectedSubHop);
    if (loginPic) {
      const [_, favicon] = loginPic.split('|');
      if (favicon) {
        changeFavicon(favicon);
      }
    }
  }

  return {
    currentSelectedSys: currentSelectedTab ? JSON.parse(currentSelectedTab) : undefined,
    openedSysLists: [],
    ...(localInitData ? JSON.parse(localInitData) : {}),
    userData,
    logout,
    pageTitle: '欢迎进入医管平台',
    favicon: '',
    customerType,
    userInfo: userInfo ? JSON.parse(userInfo) : null,
    spacicalPageParamsType: [],
    getHospSubSystemListFunc,
    systemLists,
  };
}

/**
 * 请求拦截器
 */
const requestInterceptorsHandle = (url: string, options: MyRequestOptions) => {
  const prefix = options.prefix || '/gateway';
  const userData = localStorage.getItem('userData');
  const authHeader = { token: '' };

  if (userData) {
    const { token } = JSON.parse(userData);
    if (!url.includes('/centerSys/route/list')) {
      authHeader.token = token;
    }
  }

  const finalUrl = url.startsWith(prefix) ? url : `${prefix}${url}`;

  return {
    url: finalUrl,
    options: { ...options, interceptors: true, headers: authHeader, timeout: 100000000 },
  };
};

/**
 * 响应拦截器
 */
const responseInterceptorsHandle = async (response: Response, options: RequestOptionsInit) => {
  const { url, method } = options;
  const _response = await response.clone().json();

  if (_response.errorCode === 401) {
    Modal.confirm({
      title: '抱歉，你的登录已过期，请重新登录！',
      okText: '确定',
      cancelText: '取消',
      maskClosable: false,
      onOk: () => {
        logoutHandle();
        return Promise.resolve(true);
      },
    });
    return;
  }

  if (_response.status === 200) {
    if (url !== '/centerSys/menu/checkKeygen' && method === 'POST') {
      message.success({
        content: '操作成功！',
        duration: 1,
      });
    }

    return _response.data ?? true;
  }

  const errorMessage = _response.msg || _response.message || _response.errorMessage;
  if (errorMessage?.toLowerCase().includes('token')) {
    Modal.confirm({
      title: '抱歉，你的登录已过期，请重新登录！',
      okText: '确定',
      cancelText: '取消',
      maskClosable: false,
      onOk: () => {
        logoutHandle();
        return Promise.resolve(true);
      },
    });
    return;
  }

  notification.error({
    message: '错误：',
    description: 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 || errorCode == 401) {
      //token过期
      Modal.confirm({
        title: '抱歉，你的登录已过期，请重新登录！',
        okText: '确定',
        cancelText: '取消',
        maskClosable: false,
        // cancelButtonProps:
        onOk: () => {
          logoutHandle();
          return Promise.resolve(true);
        },
      });
      return;
    }

    if (errorMessage.length > 20) {
      notification.error({
        top: 72,
        message: ` ${errorCode}:出现错误！`,
        description: errorMessage,
        icon: <IconFont type="icon-jinggaotishi" />,
        style: { padding: 16, margin: 0, borderRadius: 8 },
      });
    } else if (false) {
    } else {
      notification.error({
        top: 72,
        message: '错误',
        description: ` ${errorCode}:${errorMessage}`,
        icon: <IconFont type="icon-jinggaotishi" />,
        style: { padding: 16, margin: 0, borderRadius: 8 },
      });
    }
  } catch (err) {
    console.log({ errorHandlerFunc: err });
    notification.error({
      top: 72,
      message: '提示',
      description: '遇到未知错误，查看控制台！',
      icon: <IconFont type="icon-jinggaotishi" />,
      style: { padding: 16, margin: 0, borderRadius: 8 },
    });
  }
};

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: 'nursingWorkersManaSystem', // 唯一 id
        //   entry: '//116.169.61.56:29528', //测试
        // },
        // {
        //   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/', // 开发
        },
        {
          name: 'MediResourceManaSys', // 唯一 id
          //entry: '//localhost:8001',
          entry: '//120.27.235.181:5000/costAccount/', // 开发
        },
        // {
        //   name: 'MedicalWisdomCheckSys', // 唯一 id
        //   entry: '//localhost:8804',
        //   //entry: '//120.27.235.181:5000/pfmview/', // 开发
        // },
        // {
        //   name: 'personnelManaSystem', // 唯一 id
        //   entry: '//192.168.0.118:8005'
        //   //entry: '//120.27.235.181:5000/costAccount/', // 开发
        // },
        // {
        //   name:'devServer',
        //   entry: '//localhost:8005'
        // }
      ],
      // 生命周期钩子
      lifeCycles: {
        // beforeMount:(props:any) => {
        //   console.log('子应用挂载前', props);
        // },
        // afterMount: (props:any) => {
        //   console.log('子应用加载完成', props);
        // },
        // beforeUnmount:(props:any)=>{
        //   console.log('子应用卸载前', props);
        // }
      },
    };
  } else {
    const resp = await getQiankunMicroApps();
    if (resp) {
      let apps = resp.list ? resp.list : resp;
      return {
        apps: [...apps],
      };
    }
  }
};

//向子应用透传
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,
        }));

        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]);
}

// 定义布局组件的类型
interface BasicLayoutProps {
  headerRender?: boolean;
  rightContentRender?: () => React.ReactNode;
  footerRender?: () => React.ReactNode;
  onPageChange?: () => void;
  menuHeaderRender?: React.ReactNode;
}

// 布局组件配置
export const layout = ({ initialState }: { initialState?: InitialStateType }): BasicLayoutProps => {
  // 解构初始状态数据，设置默认值
  const { navData = [], menuData = [], customerType = '' } = initialState || {};

  return {
    headerRender: false,
    rightContentRender: () => <>right</>,
    footerRender: () => null,
    onPageChange: () => {
      // 页面变化时的逻辑
    },
    menuHeaderRender: undefined,
  };
};
