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

interface BatchFormProps {
  title: string;
  selectedRows?: BedController.BedFields[];
  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 bedStatus
   */
  const onBatch = async (bedStatus: string) => {
    setLoading({ [bedStatus]: true });
    try {
      const beds = (selectedRows || []).map(
        ({ bedCode, deptCode, orgCode }) => {
          return { bedCode, deptCode, orgCode };
        },
      );
      await BedController.batchApi({ beds, bedStatus });
      onSubmit?.();
      setOpen(false);
    } catch (error) {}
    setLoading({ [bedStatus]: false });
  };

  const onClickTrigger = () => {
    const isCancel = (selectedRows || []).some(
      (item) => item.bedStatus !== '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;
