import React, { useEffect, useState, useCallback } from 'react';
import { CnPage as UICnPage } from '@cainiaofe/cn-ui-m';
import {
  clearState,
  executeFlowList,
  handlePageDataSource,
  isDesignMode,
} from '@/common/util/util';
import { ButtonPosition } from '@/type/button-position';
import { getButtonAction } from '@/common/manager/button';
import { handleResultProcessFunc } from '@/common/manager/request';
import { CnPageRequestFinish, emitEvent } from '@/common/util/event-name';
import { dataOriginStatic } from '@/common/util/const';

const CnPage = (props) => {
  const { children, _context, componentDidMount, ...otherProps } = props;
  const [forceUpdate, setForceUpdate] = useState(false);

  const getUrlParams = () => {
    return _context?.state?.urlParams || {};
  };
  const isDesign = isDesignMode(props);

  // 最后一个阻塞页面渲染的请求名称
  let lastDeferRequest;
  if (componentDidMount && componentDidMount.requestList?.length > 0) {
    for (const req of componentDidMount.requestList) {
      if (req?.name && req?.deferPageRender) {
        lastDeferRequest = req.name;
      }
    }
  }

  const needDefer = !!lastDeferRequest && !isDesign;
  const [deferRender, setDeferRender] = useState(needDefer);

  const executeActionList = () => {
    if (!isDesign) {
      const { actionList } = componentDidMount || {};
      executeFlowList({
        list: actionList,
        _context,
        position: ButtonPosition.pageDidMount,
      }).finally((res) => {
        clearState({ _context });
      });
    }
  };

  useEffect(() => {
    (async () => {
      if (componentDidMount) {
        const { requestList = [] } = componentDidMount;
        if (requestList?.length > 0) {
          let needForceUpdate = false;
          for (const item of requestList) {
            const { name, requestConfig, dataOrigin, dataSource } = item;
            if (name) {
              if (dataOrigin === dataOriginStatic) {
                const tempP = {
                  dataOrigin,
                  dataSource,
                };
                handlePageDataSource({
                  componentProps: tempP,
                  state: _context?.state,
                });
                if (
                  tempP.dataSource !== undefined &&
                  tempP.dataSource !== null
                ) {
                  needForceUpdate = true;
                  _context?.setState({
                    [name]: tempP.dataSource,
                  });
                }
              } else if (requestConfig) {
                try {
                  const buttonConfig = {
                    optType: 'request',
                    position: ButtonPosition.pageDidMount,
                    options: {
                      requestConfig,
                    },
                  };
                  const action = getButtonAction(buttonConfig);
                  let result = await action?.({
                    position: ButtonPosition.pageDidMount,
                    urlParamsDataSource: getUrlParams(),
                    // recordDataSource: newFormValue,
                    state: _context?.state,
                    buttonConfig,
                    _context,
                    needSuccessToast: false,
                    noNeedHandleResult: true,
                    isDesign,
                  });
                  const resultProcessFunc =
                    handleResultProcessFunc(requestConfig);
                  if (typeof resultProcessFunc === 'function') {
                    result = resultProcessFunc(result, _context?.state);
                  }
                  if (result !== null && result !== undefined) {
                    needForceUpdate = true;
                    _context?.setState({
                      [name]: result,
                    });
                  }
                } catch (e) {
                  console.log(`${name} 的请求执行异常`, e);
                }
              }
              if (deferRender && name === lastDeferRequest) {
                setDeferRender(false);
              }
            }
          }
          if (needForceUpdate) {
            setForceUpdate(true);
          }
          emitEvent(CnPageRequestFinish, {});
          setTimeout(() => {
            executeActionList();
          });
        } else {
          executeActionList();
        }
      }
    })();
  }, []);

  return <UICnPage {...otherProps}>{!deferRender && children}</UICnPage>;
};
CnPage.displayName = 'CnPage';
export default CnPage;

export { CnPage };
