import React, { useState, useEffect, useMemo, useCallback, memo, useRef } from 'react';
import { Steps } from 'antd';
import ZdyTable from '@/webPublic/one_stop_public/Table';
import styles from '../style.less';

const { Step } = Steps;

const Child = memo(props => {
  const { value, json, partFormProps } = props;
  const diyProps = useMemo(() => {
    let b = {};
    if (value && typeof value === 'object') {
      b = {
        ...value,
      };
    }
    if (json.otherProps && typeof json.otherProps === 'string') {
      try {
        let a = new Function(json.otherProps)();
        if (a) {
          return {
            ...a,
            ...b,
          };
        }
        return b;
      } catch (e) {
        console.error('Step组件 otherProps错误');
      }
    } else {
      return b;
    }
  }, [json.otherProps, value]);

  // console.log(diyProps);

  const [current, setCurrent] = useState(diyProps?.StepsProps?.current || 0);

  const partFormKey = useMemo(() => {
    if (typeof current !== 'undefined') {
      let item = diyProps.Step.find((g, index) => {
        return index === current;
      });
      if (item) {
        return item.formKey;
      }
    }
    return undefined;
  }, [current]);

  useEffect(() => {
    if (diyProps?.StepsProps?.current !== current) {
      setCurrent(diyProps?.StepsProps?.current);
    }
  }, [diyProps?.StepsProps?.current]);

  return (
    <div style={diyProps.outSideDivStyle} className={styles.stepsInfo}>
      <Steps {...diyProps.StepsProps} current={current}>
        {Array.isArray(diyProps.Step) &&
          diyProps.Step.map(g => {
            return <Step {...g} key={g.title} />;
          })}
      </Steps>

      {Array.isArray(diyProps.Step) &&
        diyProps.Step.filter(g => !!g.formKey && g.formKey === partFormKey).map((g, index) => {
           // 解决禅道 31396 勤工助学学生申请岗位和填报岗位工时需要做手机端
          // 钟是志 切换step时 重新渲染formkey
          return (
            <div key={g.formKey}
                 style={{ display: partFormKey === g.formKey ? 'block' : 'none' }}
            >
              <ZdyTable
                {...partFormProps}
                currentFormTitle={'Steps组件的子表单' + g.formKey}
                key={g.formKey}
                currentFormKey={g.formKey}
                form={props.form}
                {...partFormProps?.datas[g.formKey]}
              />
            </div>
          );
        })}
    </div>
  );
});

export default function StepDiy(props) {
  const { value, json, partFormProps, form } = props;
  const js = useMemo(() => {
    return json;
  }, [json]);
  if (!js) {
    return null;
  }
  return <Child json={js} value={value} partFormProps={partFormProps} form={form} />;
}
