import React, { FC, useState, useEffect, Component } from 'react';
import DynamicForm, {
  Store,
  ValidateErrorEntity,
  useForm,
} from '@alitajs/dform';
import { PageGeneratorProps } from './interface';
import styles from './index.less';
import arrowRightIcon from './assets/arrowRightIcon.png';
import { bcmcDformStates } from './utils/bcmcDformState';
import classnames from 'classnames';
import { CardDiv, FooterBtn, ProjectInfo, Enclosure } from '../index';

const PageGenerator: FC<PageGeneratorProps> = (props) => {
  const {
    form,
    formsValues,
    data = [],
    dFormItemChange = (e: any) => undefined,
    dFormImagePickerChange = (e: any) => undefined,
    dFormItemBlur = (e: any) => undefined,
    dFormItemClick = (e: any) => undefined,
    dFormitemOnChangeLevel = (e: any) => undefined,
    eventParameters,
    onFinish = (values: Store) => undefined,
    onFinishFailed = (errorInfo: ValidateErrorEntity) => undefined,
    changeFormObj,
    initDformState = {},
    optionObjs = [],
    uploadImg = (e: any) => undefined,
    ...otherProps
  } = props;

  const uploadFile = () => {
    return (
      <div
        className={classnames({
          [styles.footerViewTop]: true,
          [styles.rightView]: true,
        })}
      >
        上传附件
        <input
          className={styles.footerInput}
          name="file"
          accept="/*"
          type="file"
          onChange={uploadImg}
        />
      </div>
    );
  };

  const arrRight = () => (
    <div className={'alitajs-dform-arrow-horizontal'}></div>
  );

  const onItemChange = (value: any, key: string) => {
    dFormItemChange({
      value,
      key,
      content: {
        formsValues,
        ...eventParameters,
      },
    });
  };

  // 输入框失焦事件
  const onItemBlur = async (value: any, key: string) => {
    dFormItemBlur({
      value,
      key,
      content: { formsValues, ...eventParameters },
    });
  };

  // 点击事件
  const onItemClick = (key: string) => {
    dFormItemClick({
      key,
      content: { formsValues, ...eventParameters },
    });
  };

  // 多级选择弹窗事件
  const onChangeLevel = (value: any, key: string) => {
    dFormitemOnChangeLevel({
      key,
      value,
      content: { formsValues, ...eventParameters },
    });
  };

  // 图片处理
  const onImagePickerChange = (
    key: string,
    files: any,
    type: string,
    index: number,
  ) => {
    // 上传
    const mValue = files as any;
    const fileCon =
      mValue &&
      mValue[mValue.length - 1] &&
      mValue[mValue.length - 1].url.split(',')[1];
    const fileName =
      mValue &&
      mValue[mValue.length - 1] &&
      mValue[mValue.length - 1].file.name;
    dFormImagePickerChange({
      key,
      value: files,
      index,
      type,
      fileCon,
      fileName,
      content: {
        formsValues,
        ...eventParameters,
      },
    });
  };

  // 表单组件
  const renderDform = (row: any) => {
    const { formStateKey, isEdit = false } = row;
    const initMethod =
      bcmcDformStates[formStateKey] || initDformState[formStateKey];
    let eleArr: any[] =
      (!!initMethod &&
        initMethod({
          ...row,
          form,
          isEdit,
          formsValues,
          onChange: onItemChange,
          onBlur: onItemBlur,
          onClick: onItemClick,
          onChangeLevel,
          onImagePickerChange,
          optionObjs,
          extra: {
            arrRight: arrRight(),
            noExtra: <div></div>,
            addressPickerNoData: <div>暂无数据</div>,
            uploadFile: uploadFile(),
          },
          content: { ...eventParameters },
        })) ||
      [];
    return eleArr.map((ele: any) => {
      return ele;
    });
  };

  const renderContentItem = (row: any, footer = false) => {
    const {
      title,
      rightView,
      type,
      customChildren,
      subContent = [],
      componentProps = {},
    } = row;
    switch (type) {
      case 'general':
        return (
          <CardDiv title={title} style={styles.cardDiv} rightView={rightView}>
            {renderDform(row)}
          </CardDiv>
        );
      case 'nestCard':
        return subContent.map((val: any) => {
          return renderContentItem(val, footer);
        });
      case 'bcmcFooterBtn': // 底部按钮
        return <FooterBtn {...componentProps} />;
      case 'bcmcProjectInfo': // 产品信息
        return <ProjectInfo {...componentProps} />;
      case 'bcmcEnclosure': // 附件列表
        return <Enclosure {...componentProps} />;
      case 'custom':
        return React.cloneElement(customChildren, {
          ...(customChildren.props || {}),
        });
      default:
        return null;
    }
  };
  // 内容
  const renderContent = (footer = false) => {
    const rows = data.map((row: any, index: number) => {
      // 区分上下模块
      if (footer === !!!row.bottom) return null;
      return renderContentItem(row, footer);
    });
    return rows;
  };
  const formProps = {
    onFinish,
    onFinishFailed,
    formsValues,
    autoLineFeed: false,
    failScroll: true,
  };
  return (
    <div className={styles.container}>
      {/* 内容 */}
      <div className={styles.main}>
        {!!form ? (
          <DynamicForm form={form} {...formProps}>
            {renderContent()}
          </DynamicForm>
        ) : (
          renderContent()
        )}
      </div>
      {renderContent(true)}
    </div>
  );
};

export default React.memo(PageGenerator);
