Modal.tsx 7.41 KB
/*
 * @Author: wangqiang@feewee.cn
 * @Date: 2022-06-29 10:44:56
 * @LastEditors: wangqiang@feewee.cn
 * @LastEditTime: 2022-11-30 14:34:02
 */
import {
  Button,
  Divider,
  Form,
  FormInstance,
  Input,
  message,
  Modal,
  Row,
  Select,
  Spin,
  Tag,
} from "antd";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import React, { useEffect, useState } from "react";
import { useStore } from "../index";
import { saveGroupApi } from "../api";
import { RoleTypeEnum, roleTypeTag } from "@/pages/admin/Role/entity";
import { checkNull, number2text } from "@/utils/validate";
import { FormListFieldData } from "antd/lib/form/FormList";

export default function RoleManagementGrooupModal() {
  const {
    pagination,
    roleInitial,
    visible,
    setVisible,
    disabled,
    setDisabled,
    current,
    setCurrent,
    formatRoleList,
  } = useStore();
  const [form] = Form.useForm();
  const [confirmLoading, setConfirmLoading] = useState(false);

  useEffect(() => {
    if (visible) {
      if (current) {
        form.setFieldsValue({
          name: current.name,
          roleList: current.roleStepList?.map((item) => {
            if (item.roleSteps && item.roleSteps?.length > 1) {
              return item.roleSteps.map((role) => role.roleCode);
            } else if (item.roleSteps && item.roleSteps.length == 1) {
              return item.roleSteps[0].roleCode;
            } else {
              return undefined;
            }
          }),
        });
        !disabled && formatRoleList(form.getFieldValue("roleList") || []);
      } else {
        form.setFieldsValue({
          roleList: [[]],
        });
      }
    }
  }, [visible, current, disabled]);

  const onOk = (val: any) => {
    setConfirmLoading(true);
    const params: RoleManagementGrooup.Detail = {
      id: current?.id,
      name: val?.name,
      roleList: (val?.roleList || []).map((role: string | string[]) => (Array.isArray(role) ? role.join(",") : role)
      ),
    };
    saveGroupApi(params)
      .then((res) => {
        message.success("操作成功");
        setVisible(false);
        pagination.setLoading(true);
      })
      .catch((error) => message.error(error.message))
      .finally(() => setConfirmLoading(false));
  };

  const groupValidator = (rule: any, value?: (string | string[])[]) => {
    console.log("vvvv", value);
    if (!value || (value && !value.length)) {
      console.log(111);
      return Promise.reject(Error("请添加管理组"));
    }
    if (value && value.length < 2) {
      console.log(222);
      return Promise.reject(Error("最少添加2个管理组"));
    }
    return Promise.resolve();
  };

  return (
    <Modal
      title={`${disabled ? "查看" : current ? "编辑" : "添加"}角色管理组`}
      visible={visible}
      maskClosable={false}
      confirmLoading={confirmLoading}
      onCancel={() => setVisible(false)}
      footer={[
        <Button loading={confirmLoading} onClick={() => setVisible(false)}>
          {disabled ? "关闭" : "取消"}
        </Button>,
        disabled ? null : (
          <Button loading={confirmLoading} type="primary" onClick={form.submit}>
            确定
          </Button>
        ),
      ]}
      afterClose={() => {
        setCurrent(undefined);
        form.resetFields();
        roleInitial.setLoading(true);
        setDisabled(false);
      }}
    >
      <Spin spinning={confirmLoading}>
        <Form
          form={form}
          onFinish={onOk}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
        >
          <Form.Item
            name="name"
            label="角色管理组名"
            rules={[{ required: true, message: "请输入角色管理组名" }]}
          >
            <Input
              allowClear
              placeholder="请输入角色管理组名"
              bordered={!disabled}
              readOnly={disabled}
            />
          </Form.Item>
          <Divider orientation="left">管理组</Divider>
          <Form.List name="roleList" rules={[{ validator: groupValidator }]}>
            {(fields, { add, remove }, { errors }) => (
              <>
                {fields.map((field, index) => {
                  return (
                    <Form.Item
                      {...field}
                      style={{ flex: 1 }}
                      label={
                        index > 0 ? `${number2text(index)}级管理` : "基础角色组"
                      }
                      rules={[
                        {
                          required: true,
                          message: `请选择${
                            index > 0
                              ? `${number2text(index)}级管理`
                              : "基础角色组"
                          }`,
                        },
                      ]}
                    >
                      <SelectRoleGroup
                        form={form}
                        fields={fields}
                        field={field}
                        index={index}
                        remove={remove}
                      />
                    </Form.Item>
                  );
                })}
                {!disabled ? (
                  <Button
                    type="dashed"
                    onClick={() => add()}
                    block
                    icon={<PlusOutlined />}
                  >
                    添加管理组
                  </Button>
                ) : null}
                <Form.ErrorList errors={errors} />
              </>
            )}
          </Form.List>
        </Form>
      </Spin>
    </Modal>
  );
}

interface SelectRoleGroupProps {
  form: FormInstance<any>;
  fields: FormListFieldData[];
  field: FormListFieldData;
  index: number;
  value?: any;
  onChange?: Function;
  remove: (index: number | number[]) => void;
}

function SelectRoleGroup({
  form,
  fields,
  field,
  index,
  value,
  onChange,
  remove,
}: SelectRoleGroupProps) {
  const { roleInitial, disabled, formatRoleList } = useStore();
  return (
    <Row justify="space-between" align="middle" key={field.key}>
      <Select
        allowClear
        showSearch
        disabled={disabled}
        value={value}
        onChange={(val) => onChange && onChange(val)}
        optionFilterProp="label"
        mode={index === 0 ? "multiple" : undefined}
        style={{ flex: 1 }}
        placeholder={`请选择${
          index > 0 ? `${number2text(index)}级管理` : "基础角色组"
        }`}
        onBlur={() => {
          formatRoleList(form.getFieldValue("roleList") || []);
        }}
      >
        {roleInitial.data.map((item) => (
          <Select.Option
            key={item.roleCode}
            value={item.roleCode!}
            item={item}
            label={item.roleName}
            disabled={checkNull(item.index) ? false : item.index !== index}
          >
            <span>
              <Tag color={roleTypeTag[item.roleType || 0]}>
                {RoleTypeEnum[item.roleType || 0]}
              </Tag>
              {`   ${item.roleName}`}
            </span>
          </Select.Option>
        ))}
      </Select>
      {/* {!disabled && fields.length > 1 && index == fields.length - 1 ? ( */}
      {!disabled ? (
        <MinusCircleOutlined
          style={{ marginLeft: 5 }}
          onClick={() => {
            remove(field.name);
            formatRoleList(form.getFieldValue("roleList") || []);
          }}
        />
      ) : null}
    </Row>
  );
}