import {
  Form,
  Input,
  DatePicker,
  TimePicker,
  Select,
  Row,
  Col,
  InputNumber,
  Upload,
  message,
  Radio,
  TreeSelect,
  Button,
  AutoComplete,
  Image,
  Cascader,
  ConfigProvider,
  Rate,
} from "antd";
import moment from "moment";
import React, { useEffect, useMemo, useState } from "react";
import { LoadingOutlined, UploadOutlined } from "@ant-design/icons";
import { PlusOutlined } from "@ant-design/icons";
import EditTable from "../EditTable";
import CheckTable from "../CheckTable";
import Editor from "../Editor";
import mockfile from "./mockfile.js";
import zhCN from "antd/lib/locale/zh_CN";
import Diyrule from "../Diyrule";
 import Autocomplete from "../Autocomplete";
moment.locale("zh-cn");

const { TreeNode } = TreeSelect;
const { RangePicker } = DatePicker;
let { Option } = Select;
let loop = (data, title, key, children) =>
  data &&
  data?.length > 0 &&
  data?.map((item) => {
    let defaulttitle = title ? title : "title",
      defaultkey = key ? key : "key",
      defaultchildren = children ? children : "children";
    const titles = <span>{item[defaulttitle]}</span>;
    if (item[defaultchildren]) {
      return (
        <TreeNode
          value={item[defaultkey]}
          key={item[defaultkey]}
          title={titles}
        >
          {loop(item[defaultchildren])}
        </TreeNode>
      );
    } else {
      return (
        <TreeNode
          value={item[defaultkey]}
          key={item[defaultkey]}
          title={titles}
        />
      );
    }
  });

function filter(inputValue, path) {
  return path.some(
    (option) =>
      option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
  );
}

function formartData(item, val) {
  let formartValue = val;
  if (item.type == "upload") {
    let stepval = val ? (Array.isArray(val) ? val : val.fileList) : [];
    formartValue = stepval.map((it) => {
      if (it.response) {
        return it.response.data.dataList[0];
      } else {
        return it ? it : null;
      }
    });
    // if (item.limit == 1) {
    //   formartValue = formartValue[0] ? formartValue[0] : '';
    // }
  } else if (item.type == "datepicker") {
    formartValue = val
      ? val.format(item.format ? item.format : "YYYY-MM-DD")
      : null;
  } else if (item.type == "timepicker") {
    formartValue = val
      ? val.format(item.format ? item.format : "HH:mm:ss")
      : null;
  } else if (item.type == "daterange") {
    formartValue =
      val && Array.isArray(val)
        ? val.map((it) =>
            it
              ? moment(it).format(item.format ? item.format : "YYYY-MM-DD")
              : null
          )
        : [];
  } else if (item.type == "select" || item.type == "treeselect") {
    formartValue = val == 0 || val ? val : item.multiple ? [] : "";
  } else if (item.type == "input" || !item.type) {
    formartValue = val ? val?.replace(/^\s+|\s+$/g, "") : "";
  }
  return formartValue;
}

let InitForm = ({
  fields,
  onChange,
  submitting,
  submitData,
  actions,
  col,
  mode,
  formRef,
  style,
  reset,
  row,
  rowCol,
  autoSubmit,
  bottomNode,
  topNode,
}) => {
  let token = localStorage.getItem("TOKENY")
    ? localStorage.getItem("TOKENY")
    : "b60ef0c40b7f1b7e63c2b24b127988d4";
  let [Dom, cDom] = useState([]),
    [cururl, setcururl] = useState(""),
    [loading, sload] = useState(false),
    [form] = Form.useForm(),
    [filelist, cfilelist] = useState({}),
    [link, clink] = useState({}),
    [belink, cbelink] = useState({}),
    [visible, setVisible] = useState(false),
    [optiondom, cdom] = useState({}),
    [len, clen] = useState(0),
    [ind, cind] = useState(0);

  form = formRef ? formRef : form;

  useEffect(() => {
    let Doms = [],
      klink = {},
      belinked = {},
      defaultfiles = {},
      allenin = 0;
    for (let i in fields) {
      let record = fields[i];
      if (record.defaultValueIndex || record.defaultValueIndex === 0) {
        allenin++;
      }
      //获取linked key
      if (record.linked === true) {
        klink[i] = record.value;
      }
      //获取belinked key
      if (record.belinked) {
        belinked[i] = record.belinked;
      }
      //初始化filelist
      if (record.type === "upload") {
        let curfileList =
          record.value && record.value.length > 0
            ? mockfile(
                Array.isArray(record.value) ? record.value : [record.value]
              )
            : [];
        //default value
        defaultfiles[i] = curfileList
          ? curfileList.fileList
            ? curfileList.fileList
            : []
          : [];
        //formart value
        record.value = curfileList;
      } else if (record.type === "datepicker") {
        record.value = record.value ? moment(record.value) : undefined;
      } else if (record.type === "timepicker") {
        record.value = record.value
          ? moment(record.value, record?.formart ?? "HH:mm:ss")
          : undefined;
      } else if (record.type === "daterange") {
        record.value =
          record.value && Array.isArray(record.value)
            ? record.value.map((it) => it && moment(it))
            : [];
      }

      Doms.push(record);
    }
    clink(klink);
    cbelink(belinked);
    cfilelist(defaultfiles);
    cDom(Doms);
    clen(allenin);
  }, [fields]);

  useEffect(() => {
    //联动数据
    for (let i in fields) {
      let extraprops = getSelectLinked(fields[i]);
      let { options } = extraprops;
      getOptions(options, fields[i]);
    }
  }, [link]);

  const getCol = (itemcol) => {
    if (itemcol) {
      return itemcol;
    } else {
      return col ? col : { xs: 24, sm: 24, md: 12, lg: 12, xl: 12, xxl: 12 };
    }
  };

  //表格 联动声明
  const getTableLinked = (item) => {
    let extraparams = {},
      oldparams = item.extraparams;
    if (oldparams && Object.keys(oldparams).length > 0) {
      for (let i in oldparams) {
        if (oldparams[i] == "linked") {
          extraparams = {
            ...extraparams,
            [i]: form.getFieldValue(i), //获取联动数据
          };
        } else {
          extraparams = {
            ...extraparams,
            [i]: oldparams[i], //获取props传入数据
          };
        }
      }
    }
    return extraparams;
  };

  //下拉框联动声明
  const getSelectLinked = (item) => {
    let names = item.belinked && Object.keys(item.belinked),
      hides = item.hides,
      options = item.options;
    if (names && names.length > 0) {
      if (item.belinked.hides && item.belinked.hides.length > 0) {
        let requiredlist = item.belinked.hides
          .filter((it) => {
            return it.required;
          })
          .map((it) => {
            if (it.equalvalue) {
              let equalvalue =
                it.equalvalue &&
                Array.isArray(it.equalvalue) &&
                it.equalvalue.length > 0
                  ? it.equalvalue.indexOf(link[it.name]) != -1
                  : link[it.name] == it.equalvalue;
              return equalvalue;
            } else if (it.unequalvalue) {
              let unequalvalue =
                it.unequalvalue &&
                Array.isArray(it.unequalvalue) &&
                it.unequalvalue.length > 0
                  ? it.unequalvalue.indexOf(link[it.name]) == -1
                  : link[it.name] != it.unequalvalue;
              return unequalvalue;
            } else {
              return true;
            }
          });

        let unrequiredlist = item.belinked.hides
          .filter((it) => {
            return !it.required;
          })
          .map((it) => {
            if (it.equalvalue) {
              let equalvalue =
                it.equalvalue &&
                Array.isArray(it.equalvalue) &&
                it.equalvalue.length > 0
                  ? it.equalvalue.indexOf(link[it.name]) != -1
                  : link[it.name] == it.equalvalue;
              return equalvalue;
            } else if (it.unequalvalue) {
              let unequalvalue =
                it.unequalvalue &&
                Array.isArray(it.unequalvalue) &&
                it.unequalvalue.length > 0
                  ? it.unequalvalue.indexOf(link[it.name]) == -1
                  : link[it.name] != it.unequalvalue;
              return unequalvalue;
            } else {
              return true;
            }
          });
        let rq = requiredlist.some((it) => it == true);
        let unrq = unrequiredlist.some((it) => it == true);
        hides = hides ? hides : rq || unrq;
      }

      if (!Array.isArray(item.belinked.options) && item.belinked.options) {
        let { database, params } = item.belinked.options,
          newparams = {};
        //获取传参联动的值
        for (let i in params) {
          if (params[i] == "linked") {
            newparams[i] = form.getFieldValue(i);
          } else {
            newparams[i] = params[i];
          }
        }
        if (Array.isArray(database)) {
          options = database;
        } else {
          options = {
            database,
            params: newparams,
          };
        }
      }
    }
    return {
      hides,
      options,
    };
  };

  //格式化数据提交
  function formartSubmit(values) {
    let newvalue = { ...values };
    for (let i in fields) {
      newvalue[i] = formartData(fields[i], values[i]);
    }
    submitData(newvalue, () => {
      form.resetFields();
    });
  }

  useEffect(() => {
    if (autoSubmit && len == ind) {
      setTimeout(() => {
        form
          .validateFields()
          .then((values) => {
            formartSubmit(values);
          })
          .catch((error) => {});
      }, 200);
    }
  }, [len, ind]);

  const submitBtn = (
    <Button
      style={{ width: "100%", marginTop: row ? 18 : 0 }}
      htmlType="submit"
      type="primary"
      size={row ? "middle" : "large"}
      disabled={submitting || loading}
      onClick={() => {
        form
          .validateFields()
          .then((values) => {
            sload(true);
            formartSubmit(values);
            setTimeout(() => {
              sload(false);
            }, 1000);
          })
          .catch((error) => {});
      }}
    >
      {submitting || loading ? <LoadingOutlined /> : null}
      {submitting || loading ? "" : "提交"}
    </Button>
  );

  let getOptions = async (options, item) => {
    let curkey = item.name[0];
    if (Array.isArray(options)) {
      if (JSON.stringify(optiondom[curkey]) !== JSON.stringify(options)) {
        cdom((optiondom) => {
          return {
            ...optiondom,
            [curkey]: options,
          };
        });
      }
    } else if (options?.database) {
      let { database, params } = options ? options : {};
      let res = await database(params),
        dataList = [];
      if (res.code == "0000") {
        if (item.type == "treeselect") {
          dataList = res?.data.dataList;
        } else {
          dataList = res?.data?.dataList?.map((it, i) => {
            let label = item.formart ? item.formart[1] : "label",
              value = item.formart ? item.formart[0] : "value";
            if (
              (item?.defaultValueIndex || item?.defaultValueIndex === 0) &&
              i == item?.defaultValueIndex
            ) {
              form.setFieldsValue({
                [curkey]: it[value],
              });
              cind((ind) => {
                ind++;
                return ind;
              });
            }
            return item.type == "cascader"
              ? {
                  label: it[label],
                  value: it[value],
                  isLeaf: it.isHaveChild ? false : true,
                }
              : {
                  label: it[label],
                  value: it[value],
                };
          });
        }
        if (item.type == "cascader" && item.value && item.value.length) {
          dataList = res?.data.dataList;
          let valueArr = item.value,
            valueArrLength = item.value.length,
            valueObj = {};
          let all = async () => {
            for (let j = 0; j < valueArrLength; j++) {
              let isMultiple = item.otherOptions[j]?.multiple,
                key = item.otherOptions[j]?.paramsKey,
                dataBase = item.otherOptions[j]?.database,
                newData = [],
                val = valueArr[j];
              let res = dataBase
                ? await dataBase(key ? { [key]: isMultiple ? [val] : val } : {})
                : null;
              if (res?.code == "0000") {
                newData = res?.data?.dataList?.map((it) => {
                  return {
                    label: it.label,
                    value: it.value,
                    isLeaf: it.isHaveChild ? false : true,
                  };
                });
                valueObj[val] = { newData };
              }
            }

            return { valueObj };
          };

          all().then((res) => {
            const { valueObj } = res;
            for (let i in valueObj) {
              loopBack(dataList, i, valueObj[i].newData);
            }
            if (
              dataList.length == 0 &&
              Object.values(params).some((it) => !it)
            ) {
            } else {
              cdom((optiondom) => {
                return {
                  ...optiondom,
                  [curkey]: JSON.parse(JSON.stringify(dataList)),
                };
              });
            }
          });
        }
      }

      if (dataList.length == 0 && Object.values(params).some((it) => !it)) {
      } else {
        if (
          item.type != "cascader" ||
          (item.type == "cascader" && !item.value)
        ) {
          cdom((optiondom) => {
            return {
              ...optiondom,
              [curkey]: dataList,
            };
          });
        }
      }
    }
  };

  //获取级联下一级
  let getChildren = async (index, item, targetOption) => {
    let isMultiple = item.otherOptions[index]?.multiple,
      key = item.otherOptions[index]?.paramsKey,
      dataBase = item.otherOptions[index]?.database,
      newData = [],
      val = targetOption.value;
    let res = dataBase
      ? await dataBase(key ? { [key]: isMultiple ? [val] : val } : {})
      : null;
    if (res?.code == "0000") {
      targetOption.loading = false;
      newData = res?.data?.dataList?.map((it) => {
        return {
          label: it.label,
          value: it.value,
          isLeaf: it.isHaveChild ? false : true,
        };
      });
      targetOption.children = [...newData];
      cdom((optiondom) => {
        return JSON.parse(JSON.stringify(optiondom));
      });
    }
  };

  //递归级联回显
  const loopBack = (data, val, children) => {
    data &&
      data?.length > 0 &&
      data?.map((it) => {
        if (it.value == val) {
          (it.children = JSON.parse(JSON.stringify(children))),
            (it.loading = false);
          it.isLeaf = children ? false : true;
        } else if (it.children) {
          loopBack(it.children, val, children);
        }
      });
  };

  return (
    <div style={{ ...style, marginTop: -24 }}>
      <ConfigProvider locale={zhCN}>
        <Image
          src={cururl}
          width={0}
          height={0}
          preview={{
            visible,
            onVisibleChange: (visibles) => {
              if (visible) {
                setVisible(false);
              }
            },
          }}
        ></Image>
        <Form
          form={form}
          name="initform"
          layout="vertical"
          fields={Dom}
          onFinish={(values) => {
            // formartSubmit(values);
          }}
          onValuesChange={(changedValues, values) => {
            let newvalue = {};
            let linkkey = Object.keys(changedValues)[0];
            //联动逻辑
            for (let i in link) {
              if (i == linkkey) {
                clink({
                  ...link,
                  [i]: changedValues[i], //state修改当前value
                });
                //重置
                if (fields[i].linked) {
                  let keyarr = [];
                  for (let index in belink) {
                    if (
                      belink[index]?.options &&
                      belink[index]?.options?.params &&
                      Object.keys(belink[index]?.options?.params)?.indexOf(i) !=
                        -1
                    ) {
                      keyarr.push(index);
                    }
                  }
                  keyarr.map((it) =>
                    form.setFieldsValue({ [it]: fields[it].multiple ? [] : "" })
                  );
                }
              }
            }
            let allValues = form.getFieldsValue();
            for (let i in fields) {
              newvalue[i] = formartData(fields[i], allValues[i]);
              if (linkkey == i) {
                changedValues[i] = formartData(fields[i], allValues[i]);
              }
            }
            onChange && onChange(changedValues, newvalue);
          }}
        >
          <Row gutter={24} style={{ position: "relative" }}>
            <Input
              type="text"
              name="userName"
              style={{ position: "fixed", top: -999 }}
            ></Input>
            <Input
              type="password"
              style={{ position: "fixed", top: -999 }}
            ></Input>
            {topNode && <Col span={24}>{topNode}</Col>}
            {Dom.map((item, i) => {
              let extraprops = getSelectLinked(item);
              if (item.type == "input" || item.type == "password") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请输入${item.title}`,
                        },
                        {
                          validator: item.checkConfirm
                            ? item.checkConfirm
                            : null,
                        },
                        item.name[0].indexOf("phone") != -1
                          ? {
                              pattern: /^(((\d{3,4}-)?[0-9]{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/,
                              message: item.title+"格式不正确",
                            }
                          : item.name[0].indexOf("mail") != -1
                          ? {
                              pattern:
                                /^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-z]{2,}$/,
                              message: "邮箱格式不正确",
                            }
                          : {},
                      ]}
                      getValueFromEvent={(event) => {
                        return event.target.value.replace(/\s+/g, " ");
                      }}
                    >
                      {item.type == "password" ? (
                        <Input.Password
                          bordered={mode == "simple" ? false : true}
                          className={mode == "simple" ? "simple" : ""}
                          placeholder={
                            item.placeholder ? item.placeholder : item.title
                          }
                          allowClear
                          type={item.type}
                          maxLength={500}
                          disabled={item.disabled}
                        />
                      ) : (
                        <Input
                          bordered={mode == "simple" ? false : true}
                          className={mode == "simple" ? "simple" : ""}
                          placeholder={
                            item.placeholder ? item.placeholder : item.title
                          }
                          allowClear
                          type={item.type}
                          maxLength={500}
                          disabled={item.disabled}
                        />
                      )}
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "editor") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请输入${item.title}`,
                        },
                      ]}
                    >
                      <Editor
                        bordered={mode == "simple" ? false : true}
                        className={mode == "simple" ? "simple" : ""}
                        height={item.height}
                        rerender={item.rerender}
                        serverURL={item.serverURL}
                      ></Editor>
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "autoinput") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请输入${item.title}`,
                        },
                      ]}
                    >
                      <AutoComplete
                        allowClear
                        placeholder={item.title}
                        disabled={item.disabled}
                        options={
                          optiondom[item.name[0]] &&
                          optiondom[item.name[0]].length > 0 &&
                          optiondom[item.name[0]]
                        }
                        bordered={mode == "simple" ? false : true}
                        className={mode == "simple" ? "simple" : ""}
                        filterOption={(inputValue, option) => {
                          return (
                            option.value &&
                            option.value.toString().indexOf(inputValue) !== -1
                          );
                        }}
                      />
                    </Form.Item>
                  </Col>
                ) : null;
              }else if (item.type == "autocompleteinput") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请输入${item.title}`,
                        },
                      ]}
                    >
                      <Autocomplete  {...item} />
                      {/* <span style={{position:'relative',fontSize:"12px",color:'#c0c0c0c0'}}>登录账号为"用户名"，登录密码为IoT设置的密码</span> */}
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "textarea") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请输入${item.title}`,
                        },
                      ]}
                    >
                      <Input.TextArea
                        maxLength={item.maxLength ? item.maxLength : 1000}
                        rows={4}
                        allowClear
                        disabled={item.disabled}
                        bordered={mode == "simple" ? false : true}
                        className={mode == "simple" ? "simple" : ""}
                      />
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "select") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请选择${item.title}`,
                        },
                      ]}
                    >
                      <Select
                        allowClear={
                          item.allowClear
                            ? item.allowClear == "false"
                              ? false
                              : true
                            : true
                        }
                        placeholder="请选择"
                        style={{ width: "100%" }}
                        showSearch
                        mode={item.multiple ? "multiple" : ""}
                        filterOption={(input, option) =>
                          option.props.children
                            .toLowerCase()
                            .indexOf(input.toLowerCase()) >= 0
                        }
                        disabled={item.disabled}
                        maxTagCount={item.maxTagCount || 100}
                        bordered={mode == "simple" ? false : true}
                        className={mode == "simple" ? "simple" : ""}
                      >
                        {optiondom[item.name[0]] &&
                          optiondom[item.name[0]].length > 0 &&
                          optiondom[item.name[0]]
                            .filter((it) => !it.hides)
                            .map((it, n) => {
                              return (
                                <Option
                                  disabled={it.disabled}
                                  key={n}
                                  value={it.dicKey ? it.dicKey : it.value}
                                >
                                  {it.dicName ? it.dicName : it.label}
                                </Option>
                              );
                            })}
                      </Select>
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "cascader") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请选择${item.title}`,
                        },
                      ]}
                    >
                      <Cascader
                        fieldNames={item.fieldNames}
                        options={optiondom[item.name[0]]}
                        placeholder="请选择"
                        style={{ width: "100%" }}
                        showSearch={{ filter }}
                        bordered={mode == "simple" ? false : true}
                        disabled={item.disabled}
                        className={mode == "simple" ? "simple" : ""}
                        loadData={
                          !item.value
                            ? item.otherOptions
                              ? (selectedOptions) => {
                                  const targetOption =
                                      selectedOptions[
                                        selectedOptions.length - 1
                                      ],
                                    index = selectedOptions.length - 1;
                                  targetOption.loading = true;
                                  getChildren(index, item, targetOption);
                                }
                              : () => {}
                            : null
                        }
                        changeOnSelect={true}
                        onChange={
                          item.value
                            ? item.otherOptions
                              ? (value, selectedOptions) => {
                                  const targetOption =
                                      selectedOptions[
                                        selectedOptions.length - 1
                                      ],
                                    index = selectedOptions.length - 1;
                                  targetOption.loading = true;
                                  getChildren(index, item, targetOption);
                                }
                              : () => {}
                            : null
                        }
                      />
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "radio") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请选择${item.title}`,
                        },
                      ]}
                    >
                      <Radio.Group
                        disabled={item.disabled}
                        options={
                          optiondom[item.name[0]] &&
                          optiondom[item.name[0]].length > 0 &&
                          optiondom[item.name[0]]
                        }
                      />
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "datepicker") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请选择${item.title}`,
                        },
                      ]}
                    >
                      <DatePicker
                        className={mode == "simple" ? "simple" : ""}
                        style={{ width: "100%" }}
                        disabledDate={
                          item.disabledDate ? item.disabledDate : null
                        }
                        disabledTime={
                          item.disabledDateTime ? item.disabledDateTime : null
                        }
                        showToday={true}
                        picker={item.picker}
                        showTime={item.showTime}
                        format={item.format}
                        disabled={item.disabled}
                      />
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "timepicker") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请选择${item.title}`,
                        },
                      ]}
                    >
                      <TimePicker
                        style={{ width: "100%" }}
                        disabledTime={
                          item.disabledDateTime ? item.disabledDateTime : null
                        }
                        showNow={true}
                        format={item.format}
                        disabled={item.disabled}
                      />
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "daterange") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请选择${item.title}`,
                        },
                      ]}
                    >
                      <RangePicker
                        className={mode == "simple" ? "simple" : ""}
                        style={{ width: "100%" }}
                        disabledDate={
                          item.disabledDate ? item.disabledDate : null
                        }
                        disabledTime={
                          item.disabledDateTime ? item.disabledDateTime : null
                        }
                        format={item.format}
                        showToday={true}
                        picker={item.picker}
                        showTime={item.showTime}
                        disabled={item.disabled}
                      />
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "inputnumber") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请输入${item.title}`,
                        },
                      ]}
                    >
                      <InputNumber
                        bordered={mode == "simple" ? false : true}
                        className={mode == "simple" ? "simple" : ""}
                        style={{ width: "100%" }}
                        disabled={item.disabled}
                        min={item.min ? item.min : 0}
                        max={item.max}
                        formatter={item.formatter}
                        parser={item.parser}
                      />
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "rate") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请输入${item.title}`,
                        },
                      ]}
                    >
                      <Rate
                        bordered={mode == "simple" ? false : true}
                        className={mode == "simple" ? "simple" : ""}
                        style={{ width: "100%" }}
                        disabled={item.disabled}
                        allowHalf={item.allowHalf ? item.allowHalf : false}
                      />
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "upload") {
                function beforeUpload(file) {
                  const isJpgOrPng =
                    file.type === "image/jpg" ||
                    file.type === "image/jpeg" ||
                    file.type === "image/png";
                  if (!isJpgOrPng && item.listType == "img") {
                    message.error("只能上传.jpg/.jpeg/.png图片!");
                  }
                  if (item.listType == "img") {
                    return isJpgOrPng;
                  } else {
                    return true;
                  }
                }

                const props = {
                  name: "file",
                  action: "/wmspro/ngic-base-business/sysAttachment/uploadFile",
                  listType: item.listType == "img" ? "picture-card" : "text",
                  accept: item.listType == "img" ? ".jpg,.png,.jpeg," : "*",
                  multiple: item.multiple ? item.multiple : false,
                  beforeUpload: beforeUpload,
                  headers: { token },
                  defaultFileList: filelist[item.name[0]],
                  maxCount: item.limit ? item.limit : 1000,
                  onChange(info) {
                    let {
                      file: { name, status, response },
                      fileList,
                    } = info;
                    if (status == "uploading") {
                      cfilelist({
                        ...filelist,
                        [item.name[0]]: fileList,
                      });
                    } else if (status == "done" || status == "removed") {
                      cfilelist({
                        ...filelist,
                        [item.name[0]]: fileList.filter((it) =>
                          it.response ? it.response : it
                        ),
                      });
                    } else if (status == "error") {
                      message.error(`${info.file.name} 上传失败`);
                    } else {
                      cfilelist({
                        ...filelist,
                        [item.name[0]]: fileList.filter((it) => it.response),
                      });
                    }
                  },
                  onPreview(file) {
                    if (file.response) {
                      setcururl(file.response.data.dataList[0].url);
                    } else if (file.url) {
                      setcururl(file.url);
                    } else {
                      setcururl(file.thumbUrl);
                    }
                    setVisible(true);
                  },
                  disabled: item.disabled || false,
                };
                const uploadBtn =
                    item.listType == "img" ? (
                      <div>
                        <PlusOutlined />
                        <div style={{ marginTop: 8 }}>上传</div>
                      </div>
                    ) : (
                      <Button icon={<UploadOutlined />}>上传</Button>
                    ),
                  limit = item.limit ? item.limit : 1000;
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请选择${item.title}`,
                        },
                      ]}
                    >
                      <Upload {...props} style={{ width: "100%" }}>
                        {filelist[item.name[0]] &&
                        filelist[item.name[0]].length > limit - 1
                          ? null
                          : uploadBtn}
                      </Upload>
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "treeselect") {
                let { title, key, children } = item.formart || {};
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请选择${item.title}`,
                        },
                      ]}
                    >
                      <TreeSelect
                        style={{ width: "100%" }}
                        dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
                        disabled={item.disabled}
                        allowClear
                        showSearch
                        multiple={item.multiple}
                        treeDefaultExpandAll
                        placeholder={`请选择...`}
                      >
                        {optiondom[item.name[0]] &&
                          optiondom[item.name[0]].length > 0 &&
                          loop(optiondom[item.name[0]], title, key, children)}
                      </TreeSelect>
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "table") {
                let extraparams = getTableLinked(item); //声明需要被联动
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请输入${item.title}`,
                        },
                      ]}
                    >
                      <EditTable
                        columns={item.columns}
                        extraparams={extraparams}
                        path={item.path}
                        editable={item.editable}
                        rowKey={item.rowKey}
                        rowName={item.rowName}
                        defaultdataSource={item.dataSource}
                        pagination={item.pagination}
                        recordCreatorProps={item.recordCreatorProps}
                        value={item.value}
                        maxLength={item.maxLength}
                        linkconfig={item.linkconfig}
                      ></EditTable>
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "checktable") {
                let extraparams = getTableLinked(item); //声明需要被联动
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请输入${item.title}`,
                        },
                      ]}
                    >
                      <CheckTable
                        columns={item.columns}
                        extraparams={extraparams}
                        path={item.path}
                        editable={item.editable}
                        dataSource={item.dataSource}
                        rowKey={item.rowKey}
                        rowName={item.rowName}
                        pagination={item.pagination}
                        tabletype={item.tabletype}
                        isDisabled={item.isDisabled}
                        pageSize={item.pageSize}
                      ></CheckTable>
                    </Form.Item>
                  </Col>
                ) : null;
              } else if (item.type == "diyrule") {
                return !extraprops.hides ? (
                  <Col key={i} {...getCol(item.col)}>
                    <Form.Item
                      style={{}}
                      label={item.title}
                      name={item.name[0]}
                      rules={[
                        {
                          required: item.required,
                          message: `请选择${item.title}`,
                        },
                      ]}
                    >
                      <Diyrule
                        extraparams={item.extraparams ?? {}}
                        values={item.value}
                      ></Diyrule>
                    </Form.Item>
                  </Col>
                ) : null;
              }
            })}
            {bottomNode && <Col span={24}>{bottomNode}</Col>}
            {reset && (
              <Col
                span={row ? 2 : reset ? 12 : 0}
                {...rowCol}
                style={{ padding: 12, marginTop: row ? 18 : 0 }}
              >
                <Button
                  size={row ? "middle" : "large"}
                  style={{ width: "100%" }}
                  onClick={() => {
                    form.resetFields();
                    form
                      .validateFields()
                      .then((values) => {
                        sload(true);
                        formartSubmit(values);
                        setTimeout(() => {
                          sload(false);
                        }, 1000);
                      })
                      .catch((error) => {});
                  }}
                >
                  重置
                </Button>
              </Col>
            )}
            <Col
              span={row ? 2 : reset ? 12 : 24}
              {...rowCol}
              style={{ padding: actions ? 0 : 12 }}
            >
              {actions ? actions(form, submitBtn) : submitBtn}
            </Col>
          </Row>
        </Form>
      </ConfigProvider>
    </div>
  );
};

export default InitForm;
