import React, { createElement, memo, useRef, useState } from 'react';
import {
  ProForm,
  ProFormDependency,
  ProFormSelect,
  ProFormText,
  ProFormGroup,
  ProFormList,
  ProCard,
} from '@ant-design/pro-components';
import moment, { defaultFormat } from 'moment';
import { doFetch } from '@/utils/doFetch';
import styles from './index.less';
import FormItems from './FormItems';
import { Input, Col } from 'antd';
import { useDebounceFn } from 'ahooks';
import ColumnsTrans from './ColumnsTrans';

function upperCase(str) {
  const newStr = str.slice(0, 1).toUpperCase() + str.slice(1);
  return newStr;
}

let FormRender = memo(({ fields = [], colProps, proformRef }) => {
  return (
    <>
      {fields
        .filter((it) => it.hideInForm !== true)
        .map((item, index) => {
          let key = item?.valueType ? upperCase(item?.valueType) : 'Input';
          let { hideInForm } = item;
          item.formItemProps = item.formItemProps ?? { rules: [] };
          if (item.valueType == 'split') {
            return (
              <div className={styles.title} style={{ borderWidth: index == 0 ? 0 : 1 }}>
                {item.title}
              </div>
            );
          }
          if (item?.valueType == 'nosubmit') {
            return (
              <Col {...(item.colProps ?? { span: 12 })} style={{ marginBottom: 24 }}>
                <label style={{ marginBottom: 8, display: 'block' }}>{item?.title}</label>
                <Input disabled value={item?.initialValue} />
              </Col>
            );
          }

          if (hideInForm && Object.keys(hideInForm)) {
            return (
              <ProFormDependency name={Object.keys(hideInForm)}>
                {(params) => {
                  let ifs = true;
                  let res = Object.keys(hideInForm).map((its) => {
                    if (Array.isArray(hideInForm[its])) {
                      return !hideInForm[its].includes(params[its]);
                    } else {
                      let vals = hideInForm[its].reverse; //取反 即不存在当前数组中的
                      return vals.indexOf(params[its]) != -1;
                    }
                  });
                  ifs = res.includes(false);
                  if (ifs) {
                    return;
                  } else {
                    return (
                      <>
                        {createElement(FormItems[key], {
                          item: item,
                          colProps: colProps,
                          key: item.dataIndex,
                          formRef: proformRef,
                        })}
                      </>
                    );
                  }
                }}
              </ProFormDependency>
            );
          } else {
            return (
              <>
                {createElement(FormItems[key], {
                  item: item,
                  colProps: colProps,
                  key: item.dataIndex,
                  formRef: proformRef,
                })}
              </>
            );
          }
        })}
    </>
  );
});

function InitForm(props) {
  let {
    formRef,
    onFinish = (vals) => {
      //console.log(vals);
    },
    formKey,
    params = {},
    detailpath = '',
    defaultFormValue = {},
    detailFormat,
    submitter,
    fields,
    extendField = '',
    colProps = { xs: 24, sm: 24, md: 12, lg: 12, xl: 12, xxl: 12 },
    onValuesChange = (changedValues, allValues) => {
      //console.log(changedValues, allValues);
    },
    val,
    style = {},
  } = props;

  const { run } = useDebounceFn(onFinish, { wait: 400 });
  let proformRef = useRef();
  proformRef = formRef ?? proformRef;
  return fields?.length == 0 ? (
    <ColumnsTrans />
  ) : (
    <ProForm
      style={{ overflow: 'hidden', ...style }}
      formRef={proformRef}
      onFinish={run}
      formKey={formKey ?? parseInt(Math.random() * 1000000)}
      params={params}
      submitter={submitter ?? true}
      grid={true}
      rowProps={{
        gutter: 12,
      }}
      request={async (params) => {
        if (detailpath && val != 'add') {
          let res = await doFetch({ url: detailpath, params });
          if (extendField) {
            let obj = {};
            res?.data?.data[extendField]?.forEach?.((it) => {
              obj[it?.fieldId] = it?.fieldRealValue;
            });

            // console.log({
            //   ...obj,
            //   ...defaultFormValue,
            //   ...(res?.data?.data ?? {}),
            // });

            return {
              ...obj,
              ...defaultFormValue,
              ...(res?.data?.data ?? {}),
              ...relationSupplierList,
            };
          }

          //反填参数 格式化
          const relationSupplierList = res?.data?.data?.relationSupplierList
            ? {
                relationSupplierList: res?.data?.data?.relationSupplierList?.map?.((it, i) => {
                  return {
                    ...it,
                    id: it?.supplierId,
                  };
                }),
              }
            : {};

          const supplierList = res?.data?.data?.supplierList
            ? {
                supplierList: res?.data?.data?.supplierList?.map?.((it, i) => {
                  return {
                    ...it,
                    id: it?.supplierId,
                  };
                }),
              }
            : {};

          let result = res?.data?.data;
          if (result?.nrList) {
            result.nrList = result?.nrList?.map((it) => {
              it.sort = it.sort - 1;
              return it;
            });
          }

          return {
            ...defaultFormValue,
            ...(result ?? {}),
            ...relationSupplierList,
            ...supplierList,
          };
        } else {
          // console.log({
          //   ...defaultFormValue,
          // });
          return {
            ...defaultFormValue,
          };
        }
      }}
      autoFocusFirstInput
      onValuesChange={(changedValues, allValues) => {
        onValuesChange?.(changedValues, allValues);
      }}
    >
      <FormRender
        fields={fields?.filter((it) => it.valueType != 'option')}
        colProps={colProps}
        proformRef={proformRef}
      />
    </ProForm>
  );
}

export default InitForm;
