import React from 'react';

import { EditableDataTable, FormEL } from '@components';

const Block = ({ dispatch, readOnly, loading, children, localCfg, remoteCfg, onFieldsChange, type, data, extraInfo ,id, mode, ...otherPorps }) => {

  const childrenWithProps = React.Children.map(children, (child) => {
    return React.cloneElement(child, {
      ...otherPorps,
      readOnly: readOnly ? true : !!remoteCfg.readOnly,
      disabled: readOnly ? true : !!remoteCfg.readOnly,
    });
  });

  // console.log(id, localCfg(data, '')[id], remoteCfg);
  let localFields = localCfg(data, mode, dispatch, loading, extraInfo)[id];
  const remoteFields = remoteCfg.fields;

  // Remove hidden fileds
  localFields = localFields.filter(lf => {
      const remoteHidden = remoteFields.find(rf => lf.dataIndex === rf.fieldId) && remoteFields.find(rf => lf.dataIndex === rf.fieldId).hidden;
      // console.log('lf', lf)
      const localHidden = lf.hidden
      return !localHidden && !remoteHidden;
    },
  );

  // console.log(localFields)

  if (type === 'form') {
    remoteFields.forEach(f => {
      let hit = localFields.find(lf => lf.dataIndex === f.fieldId);
      // console.log('hit before >>>> ', hit);
      if (hit) {
        if (f.required) {
          if (hit.options) {
            hit.options = {
              ...hit.options,
              rules: [...hit.options.rules && hit.options.rules, { required: true, message: '必填' }],
            };
          } else {
            hit.options = { rules: [{ required: true, message: '必填' }] };
          }
        }
        if (f.readOnly) {
          hit.readOnly = true;
        }
      }
      // console.log('hit after >>>> ', hit);
    });
  } else if (type === 'table') {
    remoteFields.forEach(f => {
      let hit = localFields.find(lf => lf.dataIndex === f.fieldId);
      // console.log('hit before >>>> ', hit);
      if (hit) {
        if (f.required) {
          hit.required = true;
        }
        if (f.readOnly) {
          // console.log(f);
          hit.readOnly = true;
        }
      }
      // console.log('hit after >>>> ', hit);
    });
  } else {

  }

  // console.log('localFields after >>>> ', localFields);

  // type === 'form' && console.log(onFieldsChange, otherPorps);

  return remoteCfg.hidden ? null :
    <div style={{ marginBottom: 10 }}>
      {
        type === 'form' ?
          <FormEL items={localFields} loading={loading} record={data} onFieldsChange={onFieldsChange}
                  readOnly={readOnly ? true : !!remoteCfg.readOnly} {...otherPorps} /> :
          type === 'table' ?
            <EditableDataTable columns={localFields} loading={loading} dataSource={data} dispatch={dispatch}
                               readOnly={readOnly ? true : !!remoteCfg.readOnly} {...otherPorps} /> :
            childrenWithProps
      }
    </div>;
};

export default Block;
