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

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

const AuditPassOn = (props: AuditPassOnProps) => {
  const { chainId, auditId, batch, type = 'uac', disable = false, onComplete, auditDetail } = props;
  const { formatMessage } = useIntl();
  const [form] = useForm();
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

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

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

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

  /** 判断是否是管理员审批 */
  const managerAudit = () => {
    if (!currentUser?.id) return false;
    const { manager, owner } = auditDetail?.appInfo ?? {};
    const managerIds = Array.isArray(manager) ? manager.map((v: API.User) => v.id) : [];
    return managerIds.includes(currentUser.id) || owner?.id === currentUser.id;
  };

  // 暂时不支持bpm
  if (type !== 'uac' || managerAudit()) return null;
  return (
    <ModalForm
      title={title}
      trigger={
        <Button
          ghost
          type={'primary'}
          size={batch ? undefined : 'small'}
          disabled={disable || !chainId || !auditId}
        >
          {title}
        </Button>
      }
      form={form}
      width={600}
      modalProps={{
        destroyOnClose: true,
      }}
      labelAlign={'left'}
      layout={'horizontal'}
      onFinish={onFinish}
    >
      <label>{formatMessage({ id: 'component.AuditPassOn.tips' })}</label>

      <Form.Item
        label={formatMessage({ id: 'component.AuditPassOn.approver' })}
        name={'userId'}
        rules={[
          { required: true },
          {
            validator: async (__, value) => {
              if (value === currentUser?.id) {
                throw new Error(
                  formatMessage({ id: 'component.AuditPassOn.userSelect.validator' }),
                );
              }
            },
          },
        ]}
        style={{ marginTop: 24 }}
      >
        <UserSelect state={1} />
      </Form.Item>
    </ModalForm>
  );
};

export default AuditPassOn;
