import { ModalForm } from '@ant-design/pro-form';
import { Button, Form, message, Radio } from 'antd';
import { useForm } from 'antd/lib/form/Form';
import _ from 'lodash';
import { type Key } from 'react';
import { useIntl } from 'umi';
import UserSelect from '../UserSelect';
import { auditCountersign } from './api';

export interface AuditCountersignProps {
  chainId?: string;
  auditId?: Key | Key[] | ((type: string) => Key[]);
  batch?: boolean;
  type?: 'uac' | 'bpm';
  disable?: boolean;
  onComplete?: () => void;
}

const AuditCountersign = (props: AuditCountersignProps) => {
  const { chainId, auditId, batch = false, type = 'uac', disable = false, onComplete } = props;
  const { formatMessage } = useIntl();
  const [form] = useForm();

  const onFinish = async (vals: any) => {
    if (!chainId || !auditId) return;

    const { target, userId } = vals;
    await auditCountersign({
      auditId: _.isFunction(auditId) ? auditId(type) : auditId,
      chainId,
      type,
      target,
      userId,
    });
    message.success(formatMessage({ id: 'component.AuditCountersign.success' }));
    onComplete?.();
    return true;
  };

  const title = formatMessage({
    id: `component.AuditCountersign.${batch ? 'batch.title' : 'title'}`,
  });

  // 暂时不支持bpm
  if (type !== 'uac') return null;
  return (
    <ModalForm
      title={title}
      trigger={
        <Button
          ghost
          type={'primary'}
          size={batch ? undefined : 'small'}
          disabled={disable || !chainId || !auditId}
        >
          {title}
        </Button>
      }
      form={form}
      initialValues={{ target: 1 }}
      width={600}
      modalProps={{
        destroyOnClose: true,
      }}
      labelAlign={'left'}
      layout={'horizontal'}
      onFinish={onFinish}
    >
      <Form.Item
        label={formatMessage({ id: 'component.AuditCountersign.position' })}
        name={'target'}
        rules={[{ required: true }]}
      >
        <Radio.Group>
          <Radio value={1}>
            {formatMessage({ id: 'component.AuditCountersign.position.front' })}
          </Radio>
          <Radio value={2}>
            {formatMessage({ id: 'component.AuditCountersign.position.after' })}
          </Radio>
        </Radio.Group>
      </Form.Item>

      <Form.Item
        label={formatMessage({ id: 'component.AuditCountersign.approver' })}
        name={'userId'}
        rules={[{ required: true }]}
      >
        <UserSelect state={1} />
      </Form.Item>
    </ModalForm>
  );
};

export default AuditCountersign;
