Untitled

 avatar
unknown
plain_text
2 years ago
5.2 kB
4
Indexable
import arrayToTree from "array-to-tree";

import { Button, Form, Select, Space } from "antd";
import { FormContainer } from "components/shared-components/Form";
import { debounce } from "lodash";
import { useEffect, useMemo } from "react";
import { useLazyGetEnterpriseQuery, useLazyGetEnterprisesQuery } from "store/services/admin/enterprises/enterpriseApiSlice";
import { useLazyGetMenuItemsQuery } from "store/services/admin/menuApiSlice";
import { filterOption } from "utils/select-options";

const authTypes = [
  { value: "client", label: "Cliente" },
  { value: "franchise", label: "Franquia" },
  { value: "admin", label: "Administrador" },
];

export function EnterpriseForm({ onFinish }) {
  const [form] = Form.useForm();

  const [getEnterprises, {
    data: enterprises,
    isFetching: enterprisesIsFetching,
    isError: enterprisesIsError,
  }] = useLazyGetEnterprisesQuery();

  const [getEnterprise, {
    data: enterprise,
    isFetching: enterpriseIsFetching,
    isError: enterpriseIsError,
  }] = useLazyGetEnterpriseQuery();

  const [getMenuItems, {
    data: menuItems,
    isFetching: menuItemsIsFetching,
    isError: menuItemsIsError,
  }] = useLazyGetMenuItemsQuery();

  const authTypeValue = Form.useWatch("authType", form);

  const enterpriseOptions = useMemo(() => {
    if (!enterprises) return [];

    if (enterprisesIsError) return [];

    return enterprises?.data?.map(enterprise => ({
      value: enterprise.uuid,
      label: enterprise.name,
    }));
  }, [enterprises, enterprisesIsFetching, enterprisesIsError]);

  const authTypeOptions = useMemo(() => {
    if (!enterprise) return [];
    if (enterpriseIsFetching) return [];
    if (enterpriseIsError) return [];

    return authTypes.filter(({ value }) => enterprise.type_auth.includes(value));
  }, [enterprise, enterpriseIsFetching, enterpriseIsError]);

  const accessGroupOptions = useMemo(() => {
    if (!menuItems) return [];
    if (menuItemsIsError) return [];

    return arrayToTree((menuItems), {
      parentProperty: "master",
      customID: "uuid",
    }).map(menuItem => ({
      value: menuItem.uuid,
      label: menuItem.label,
    }));

  }, [menuItems, menuItemsIsFetching, menuItemsIsError]);

  const onSearch = debounce(value => {
    getEnterprises({
      queryParams: {
        search: value,
      },

      columnsToSearch: ["name"],
    });
  }, 800);

  useEffect(() => {
    getEnterprises({
      queryParams: {
        search: "",
      },

      columnsToSearch: ["name"],
    });
  }, []);

  useEffect(() => {
    if (authTypeOptions.length === 1) {
      const [authType] = authTypeOptions;

      form.setFieldValue("authType", authType.value);
    }
  }, [authTypeOptions]);

  useEffect(() => {
    if (authTypeValue) {
      getMenuItems({ userType: authTypeValue });
    }
  }, [authTypeValue]);

  return (
    <FormContainer form={form} onFinish={onFinish}>
      <Form.Item label={"Empresa"} required className="mb-0">
        <div style={{
          display: "flex",
          gap: 8,
          flexWrap: "wrap"
        }}>
          <Form.Item label="Empresa" name={"enterpriseId"} rules={[{ required: true }]} noStyle>
            <Select
              showSearch
              placeholder={"Selecione uma empresa"}
              notFoundContent={enterprisesIsFetching ? "Carregando..." : "Nenhum resultado encontrado"}
              defaultActiveFirstOption={false}
              filterOption={false}
              loading={enterprisesIsFetching}
              options={enterpriseOptions}
              onSearch={onSearch}
              onChange={(enterpriseId) => {
                form.setFieldValue("authType", null);
                form.setFieldValue("accessGroup", null);
                getEnterprise({ enterpriseId });
              }}
              style={{
                width: "100%",
                maxWidth: 320,
              }}
            />
          </Form.Item>

          <Form.Item label="Tipo de usuário" name={"authType"} rules={[{ required: true }]} noStyle>
            <Select
              showSearch
              filterOption={filterOption}
              placeholder={"Selecione o tipo de usuário"}
              options={authTypeOptions}
              loading={enterpriseIsFetching}
              disabled={authTypeOptions.length === 1}
              style={{
                width: "100%",
                maxWidth: 220,
              }}
            />
          </Form.Item>

          <Form.Item label="Grupo de acesso" name={"accessGroup"} rules={[{ required: true }]} noStyle>
            <Select
              showSearch
              filterOption={filterOption}
              placeholder={"Grupo de acesso"}
              options={accessGroupOptions}
              loading={enterpriseIsFetching}
              style={{
                width: "100%",
                maxWidth: 220,
              }}
            />
          </Form.Item>

          <Button type="primary" htmlType="submit">Buscar</Button>
        </div>
      </Form.Item>
    </FormContainer>
  );
}
Editor is loading...