【form校验】3.0项目多层list嵌套

【form校验】3.0项目多层list嵌套_第1张图片


const { required, phoneOrMobile } = CjmForm.rules;
export default function detail() {
  const { query } = getRouterInfo(location);

  const formRef = useRef(null);

  const [crumbList, setCrumbList] = useState([
    {
      url: "/wenling/Reviewer",
      name: "审核人员",
    },
    {
      name: query.type == "look" ? "查看" : "编辑",
    },
  ]);
  const [form, setForm] = useState({
    auditNodeConfig: [
      {
        nextAuditNode: "农办审批",
        userList: [
          {
            batchAudit: false,
            phone: "",
          },
        ],
      },
      {
        nextAuditNode: "农水局审批",
        userList: [
          {
            batchAudit: false,
            phone: "",
          },
        ],
      },
      {
        nextAuditNode: "同步财政局审核结果",
        userList: [
          {
            batchAudit: false,
            phone: "",
          },
        ],
      },
    ],
  });
  const [loading, setLoading] = useState(false);
  const [spinning, setSpinning] = useState(false);

  useEffect(() => {
    getConfigInfo();
  }, []);

  async function getConfigInfo() {
    setSpinning(true);
    const res = await configLook({ confId: query.confId });
    if (res.results && res.state && res.state == 200) {
      setForm(transformData(res.results));
    } else {
      if (query.processCode == "10001002") {
        setForm({
          auditNodeConfig: [
            {
              nextAuditNode: "农办审批",
              userList: [
                {
                  batchAudit: false,
                  phone: "",
                },
              ],
            },
          ],
        });
      }
    }
    setSpinning(false);
  }

  const rules = useMemo(() => {
    let newRule = {};
    form["auditNodeConfig"].forEach((item, key) => {
      item["userList"].forEach((record, recordKey) => {
        newRule[`auditNodeConfig.${key}.userList.${recordKey}.phone`] = [
          required,
          phoneOrMobile,
        ];
        newRule[`auditNodeConfig.${key}.userList.${recordKey}.userId`] = [
          required,
        ];
      });
    });
    return newRule;
  }, [form]);

  const modalForm = useMemo(() => {
    let newForm = {};
    form["auditNodeConfig"].forEach((item, key) => {
      item["userList"].forEach((record, recordKey) => {
        newForm[`auditNodeConfig.${key}.userList.${recordKey}.phone`] =
          record["phone"];
        newForm[`auditNodeConfig.${key}.userList.${recordKey}.userId`] =
          record["userId"];
      });
    });
    return newForm;
  }, [form]);

  const getValue = (eventOrvalue) => {
    const type = typeof eventOrvalue;
    if (
      type === "object" &&
      eventOrvalue !== null &&
      eventOrvalue.target &&
      eventOrvalue.target.value
    ) {
      return eventOrvalue.target.value;
    }
    return eventOrvalue;
  };

  const setFormData = (fieldName, index, recordKey) => {
    return (eventOrvalue) => {
      let value = getValue(eventOrvalue);
      if (fieldName == "batchAudit") {
        value = eventOrvalue.target.checked;
      }
      form["auditNodeConfig"][index]["userList"][recordKey][fieldName] = value;
      setForm(Object.assign({}, form));
    };
  };

  const addHandle = (index) => {
    const listLen = get(form, `auditNodeConfig[${index}].userList`, []).length;
    if (listLen >= 4) {
      Message.warning("最多添加4个审批人员!");
    } else {
      form["auditNodeConfig"][index]["userList"].push({
        batchAudit: false,
        phone: "",
      });
      setForm(Object.assign({}, form));
    }
  };

  const saveHandle = async () => {
    setLoading(true);
    const valid = await formRef.current.validate();
    if (valid) {
      let data = { ...form };
      data["confId"] = query.confId;
      data["processCode"] = query.processCode;
      const res = await configEdit(transformTree(data));
      if (res.state && res.state == 200) {
        Message.success("操作成功");
        historyBack();
      } else {
        Message.error("操作失败,请重试!");
      }
    }
    setLoading(false);
  };

  const delHandle = (index, recordKey) => {
    form["auditNodeConfig"][index]["userList"].splice(recordKey, 1);
    setForm(Object.assign({}, form));
  };

  return (
    <div className={styles.reviewerBox}>
      <Spin spinning={spinning}>
        <CrumbBar list={crumbList} />
        <CjmForm
          labelWidth="180px"
          ref={formRef}
          model={modalForm}
          rules={rules}
        >
          <CjmForm.Item label="审批类型:">
            <CjmInput
              value={query.processName}
              disabled={true}
              style={{ width: "380px" }}
            />
          </CjmForm.Item>
          {form &&
            form.auditNodeConfig.map((item, index) => {
              return (
                <div className={styles.auditItem} key={index}>
                  <h2 style={{ marginLeft: "24px" }}>
                    {item["nextAuditNode"]}
                  </h2>
                  {item["userList"] &&
                    item["userList"].map((record, recordKey) => {
                      return (
                        <div key={recordKey} className={styles.formItem}>
                          <CjmForm.Item
                            label="审批人名称:"
                            prop={`auditNodeConfig.${index}.userList.${recordKey}.userId`}
                          >
                            <RemoteSelect
                              style={{ width: "380px" }}
                              disabled={query.type == "look" ? true : false}
                              labelKey="userName"
                              valueKey="userId"
                              value={record.userId}
                              label={record.userName}
                              remoteUrl={`${api.reviewer.departmentId}?departmentId=${query.optDeptId}&disableFlag=1`}
                              onChange={{
                                userName: setFormData(
                                  "userName",
                                  index,
                                  recordKey
                                ),
                                userId: setFormData("userId", index, recordKey),
                                departmentId: setFormData(
                                  "deptId",
                                  index,
                                  recordKey
                                ),
                                mobileId: setFormData(
                                  "phone",
                                  index,
                                  recordKey
                                ),
                              }}
                            />
                          </CjmForm.Item>
                          <CjmForm.Item
                            label="审批人手机号:"
                            prop={`auditNodeConfig.${index}.userList.${recordKey}.phone`}
                          >
                            <CjmInput
                              disabled={query.type == "look" ? true : false}
                              style={{ width: "380px" }}
                              value={record.phone}
                              onChange={setFormData("phone", index, recordKey)}
                            />
                          </CjmForm.Item>
                          <CjmForm.Item label="审批操作:" prop="batchAudit">
                            <Checkbox
                              disabled={query.type == "look" ? true : false}
                              checked={record.batchAudit}
                              onChange={setFormData(
                                "batchAudit",
                                index,
                                recordKey
                              )}
                            >
                              批量通过
                            </Checkbox>
                            <span style={{ marginLeft: "24px" }}>
                              默认单个审核,设置批量审核后允许该节点可批量审核
                            </span>
                          </CjmForm.Item>
                          <Divider className={styles.line} />
                          {recordKey != 0 && (
                            <img
                              className={styles.close}
                              src={deleteImg}
                              onClick={() => delHandle(index, recordKey)}
                            />
                          )}
                        </div>
                      );
                    })}
                  {query.type !== "look" && index == 0 && (
                    <Button
                      type="primary"
                      style={{ marginLeft: "224px" }}
                      onClick={() => addHandle(index)}
                    >
                      +新增(最多添加4个审批人员)
                    </Button>
                  )}
                </div>
              );
            })}
        </CjmForm>
        <Button className={styles.btnLeave} onClick={() => historyBack()}>
          返回
        </Button>
        {query.type !== "look" && (
          <Button
            type="primary"
            className={styles.btnSave}
            loading={loading}
            onClick={saveHandle}
          >
            保存
          </Button>
        )}
      </Spin>
    </div>
  );
}

你可能感兴趣的:(list,javascript,前端)