import React, {forwardRef, useEffect, useState,} from 'react';
import {CnStep as UICnStep, CnStepItem} from '@cainiaofe/cn-ui-m';
import {
  calculateTextExprValue,
  executeFunction,
  getRealResponse,
  isArrayNotEmpty,
  isDesignMode,
  isEmptyButNotZero,
  isRequestConfig,
  setDataToDs,
} from '@/common/util/util';
import isPlainObject from 'lodash/isPlainObject';
import {__step_activeKey__, __step_current__, __step_currentItem__, __step_list__,} from '@/common/util/expr-const';
import {dataOriginRequest} from '@/common/util/const';
import {makeRequest} from '@/common/manager/request';
import {filterHiddenStep} from '@/components/cn-step/util';

const CnStep = forwardRef((props, ref) => {
  if (!UICnStep) {
    return null;
  }

  const {
    steps: propSteps,
    stepStyle,
    current: propsCurrent,
    leftButtons,
    rightButtons,
    _dataSource,
    _dataSourceName,
    _context,
    dataOrigin,
    requestConfig,
    events,
  } = props;
  const isDesign = isDesignMode(props);
  const {_customRenderStepContent} = stepStyle || {};

  const findCurrent = (list, tempCurrent) => {
    let result = tempCurrent;
    if (typeof tempCurrent === 'number') {
    } else {
      const tempActiveKey = calculateTextExprValue(tempCurrent, {
        state: _context?.state,
        recordDataSource: {},
      });
      if (typeof tempActiveKey === 'number') {
        result = tempActiveKey;
      } else {
        if (typeof result === 'function') {
          result = undefined;
        }
        for (const index in list) {
          const item = list[index];
          const {key} = item || {};
          if (key === tempActiveKey) {
            result = +index;
            break;
          }
        }
      }
    }
    return result;
  };

  let initialSteps = filterHiddenStep(propSteps, _context);
  if (dataOrigin === dataOriginRequest) {
    initialSteps = [];
  }
  const [steps, setSteps] = useState(initialSteps);
  const [current, setCurrent] = useState(findCurrent(steps, propsCurrent));

  useEffect(() => {
    if (dataOrigin !== dataOriginRequest) {
      setSteps(filterHiddenStep(propSteps, _context));
    }
  }, [propSteps]);

  useEffect(() => {
    if (dataOrigin !== dataOriginRequest) {
      setCurrent(findCurrent(steps, propsCurrent));
    }
  }, [propsCurrent]);

  const getActiveKeyByIndex = (list, index) => {
    if (typeof index === 'number' && isArrayNotEmpty(list)) {
      const temp = list[index];
      if (temp?.key) {
        return temp.key;
      }
    }
  };

  const changeStep = (newIndex, config) => {
    const {needSetState} = config || {};
    let realIndex;
    if (typeof newIndex === 'number') {
      realIndex = newIndex;
    } else {
      realIndex = findCurrent(steps, newIndex);
    }
    if (typeof realIndex === 'number') {
      if (needSetState) {
        setCurrent(realIndex);
      }
      setDataToDs({
        _context,
        _dataSource,
        _dataSourceName,
        data: {
          [__step_current__]: realIndex,
          [__step_activeKey__]: getActiveKeyByIndex(steps, newIndex),
          [__step_currentItem__]: steps[newIndex] || {},
        },
      });
    }
  };

  const handleStep = (steps) => {
    if (isDesign && dataOrigin === dataOriginRequest) {
      return [
        <CnStepItem key={'unique'} title={'动态Step，请到预览页面查看'}/>,
      ];
    }

    const result = [];
    if (Array.isArray(steps) && steps.length > 0) {
      steps.forEach((item, index) => {
        const {title, content, key, ...rest} = item;
        if (key) {
          result.push(
            <CnStepItem
              {...rest}
              key={index}
              title={title}
              content={content}
              // content={(a,b,c)=>{
              //   console.log(a,b,c,11111);
              //   return <div className="">
              //     1111
              //   </div>
              // }
              // }
              onClick={changeStep}
            />,
          );
        }
      });
    }
    if (isDesign && result.length === 0) {
      return [<CnStepItem key={'unique'} title={'步骤示例'}/>];
    }
    return result;
  };

  const stepProps = {
    ...stepStyle,
    current,
  };
  if (typeof _customRenderStepContent === 'function') {
    stepProps.contentRender = (item, index) => {
      return executeFunction(
        _customRenderStepContent,
        item,
        index,
        _context?.state,
      );
    };
  }

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

  useEffect(() => {
    if (dataOrigin === 'request') {
      let realSteps;
      let realCurrent;
      if (isRequestConfig(requestConfig)) {
        makeRequest({
          buttonConfig: {
            options: {
              requestConfig,
            },
          },
          urlParamsDataSource: getUrlParams(),
          recordDataSource: {},
          state: _context?.state || {},
          needSuccessToast: false,
          isDesign,
        })
          .then((res) => {
            const res2 = getRealResponse(res);
            const {success, data} = res2;
            if (success) {
              if (isPlainObject(data)) {
                const {list: originList, activeKey: originalActiveKey} = data;
                const list = filterHiddenStep(originList, _context);
                if (isArrayNotEmpty(list)) {
                  let tempCurrent;
                  const newList = [];
                  if (typeof originalActiveKey === 'number') {
                    tempCurrent = originalActiveKey;
                  }
                  for (const index in list) {
                    const {label, title, key} = list[index];
                    const value = list[index]?.value || key;
                    if (
                      typeof originalActiveKey === 'string' &&
                      originalActiveKey === value
                    ) {
                      tempCurrent = +index;
                    }
                    const temp = {
                      ...list[index],
                      title: label || title,
                      key: value || key,
                    };
                    if (title) {
                      temp.title = title;
                    }
                    newList.push(temp);
                  }
                  if (isEmptyButNotZero(tempCurrent)) {
                    tempCurrent = 0;
                  }
                  realSteps = newList;
                  realCurrent = tempCurrent;
                  setDataToDs({
                    _context,
                    _dataSource,
                    _dataSourceName,
                    data: {
                      [__step_list__]: newList,
                      [__step_current__]: tempCurrent,
                      [__step_activeKey__]: getActiveKeyByIndex(
                        newList,
                        tempCurrent,
                      ),
                      [__step_currentItem__]: newList[tempCurrent] || {},
                    },
                  });
                }
              }
            }
          })
          .finally(() => {
            setSteps(realSteps);
            setCurrent(realCurrent);
          });
      }
    } else {
      setDataToDs({
        _context,
        _dataSource,
        _dataSourceName,
        data: {
          [__step_list__]: steps,
          [__step_current__]: current,
          [__step_activeKey__]: getActiveKeyByIndex(steps, current),
        },
      });
    }
  }, []);

  return (
    <div className=''>
      <UICnStep {...stepProps}>{handleStep(steps)}</UICnStep>
    </div>
  );
});
CnStep.displayName = 'CnStep';
export default CnStep;
