import { Form, Input, message, Modal, ModalProps } from 'antd';
import { FC, useEffect } from 'react';
import { InterDataType } from '~/api/interface';
import { listRoleInfoPageType } from '~/api/interface/systemManageType';
import { SystemManageAPI } from '~/api';

//账号权限-返回类型
type accountLimitType = InterDataType<listRoleInfoPageType>['list'];
type selfProps = {
  onOk: () => void;
  onCancel: () => void;
  currentLimit: accountLimitType[0] | undefined;
};

const AddOrEditLimitModal: FC<ModalProps & selfProps> = ({
  open,
  onCancel,
  onOk,
  currentLimit,
}) => {
  const [form] = Form.useForm<{ roleName: string; remark?: string }>();

  //表单提交
  const handleOk = () => {
    form.validateFields().then((value) => {
      SystemManageAPI[currentLimit ? 'updateRoleInfo' : 'insertRoleInfo']({
        ...value,
        id: currentLimit ? currentLimit.id : undefined,
      }).then(({ code }) => {
        if (code === '200') {
          message.success(currentLimit ? '编辑成功' : '新增成功');
          form.resetFields();
          onOk();
        }
      });
    });
  };
  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };
  useEffect(() => {
    if (currentLimit) {
      form.setFieldsValue({
        roleName: currentLimit.roleName,
        remark: currentLimit.remark || undefined,
      });
    }
  }, [currentLimit]);
  return (
    <Modal
      open={open}
      onCancel={handleCancel}
      title={currentLimit ? '编辑角色' : '新增角色'}
      onOk={handleOk}
    >
      <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 16 }}>
        <Form.Item
          label='角色名称'
          name='roleName'
          rules={[{ required: true, message: '请输入角色名称' }]}
        >
          <Input placeholder='请输入角色名称' maxLength={30} />
        </Form.Item>
        <Form.Item label='角色备注' name='remark'>
          <Input.TextArea placeholder='请输入备注信息' rows={4} maxLength={70} showCount />
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default AddOrEditLimitModal;
