import { ModalForm } from '@ant-design/pro-components';
import { Button, Space, message } from 'antd';
import React, { useState } from 'react';
import { OrgController } from '../../../../services';

interface BatchFormProps {
  title: string;
  selectedRows?: OrgController.OrgFields[];
  trigger: JSX.Element;
  onSubmit?: () => void;
}
const BatchForm: React.FC<BatchFormProps> = (props) => {
  const { title, trigger, selectedRows, onSubmit } = props;
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState<Partial<Record<string, boolean>>>({});
  /**
   * @name 批量启用/批量停用/批量审批/批量驳回
   * @param orgStatus
   */
  const onBatch = async (orgStatus: string) => {
    setLoading({ [orgStatus]: true });
    try {
      const orgCodes = (selectedRows || [])
        .map(({ orgCode }) => {
          return orgCode;
        })
        .join(',');
      await OrgController.batchApi({ orgCodes, orgStatus });
      onSubmit?.();
      setOpen(false);
    } catch (error) {}
    setLoading({ [orgStatus]: false });
  };

  const onClickTrigger = () => {
    const isCancel = (selectedRows || []).some(
      (item) => item.orgStatus !== '3',
    );
    if (isCancel) {
      return message.warning('请勾选状态为待审核的数据！');
    }
    setOpen(true);
  };
  return (
    <>
      {React.cloneElement(trigger, {
        onClick: onClickTrigger,
      })}
      <ModalForm
        layout="horizontal"
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 21 }}
        width={600}
        title={title}
        open={open}
        autoFocusFirstInput
        modalProps={{
          destroyOnClose: true,
          onCancel: () => setOpen(false),
        }}
        submitter={false}
      >
        <Space size={16} style={{ justifyContent: 'center', display: 'flex' }}>
          <Button
            key="refuse"
            type="primary"
            danger
            loading={loading['4']}
            disabled={loading['3']}
            onClick={() => onBatch('4')}
          >
            驳回
          </Button>
          <Button
            key="ok"
            type="primary"
            loading={loading['3']}
            disabled={loading['4']}
            onClick={() => onBatch('3')}
          >
            通过
          </Button>
        </Space>
      </ModalForm>
    </>
  );
};

export default BatchForm;
