import { Button, Card, Input, message, Modal } from 'antd';
import { ProTable } from '@ant-design/pro-table';
import { ProForm, ProFormDateTimePicker } from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import { FormattedMessage, useIntl } from 'umi';
import { bindUsers, validateUsersRequest } from '../server';
import { memo, useState } from 'react';
import { useGetAppId } from '../utils/hooks';
import { reloadReactNode } from '../utils/jsxformat';
import { PlusOutlined } from '@ant-design/icons';
import { formatUserRender } from '../utils';
import moment from 'moment';

/**
 * @description 这个组件用来添加用户的组件
 */
interface AddUserProps {
  /**
   * @description 选择类型，目前只支持四种类型的数据添加用户
   */
  type: 'feature' | 'option' | 'policy' | 'role'; // 选择类型
  /**
   * @description 选择什么type，就传入对应type的id。比如选了feature添加用户，那么就要传入featureId进来。
   */
  id: number; // 默认参数
  /**
   * @description type选了option，就需要传入flagId。
   */
  flagId?: number;
  /**
   * @description 在添加用户成功后回调的函数，可不传。
   */
  reload?: () => void;
  /**
   * @description 默认是新增按钮。
   * @default (<Button type="primary" key="create" onClick={() => { setOpen(true); }} >
        <PlusOutlined /> <FormattedMessage id="public.user.new" defaultMessage="新增" />
      </Button>)
   */
  children?: React.ReactNode;
}
const AddUser = ({ id, flagId, type, reload, children }: AddUserProps) => {
  const { formatMessage } = useIntl();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [open, setOpen] = useState(false);
  const appId = useGetAppId();
  const [form] = ProForm.useForm();
  const columns: ProColumns<API.User & API.UserSearch>[] = [
    {
      title: <FormattedMessage id="public.user.id" defaultMessage="用户账号" />,
      dataIndex: 'accounts',
      valueType: 'textarea',
      hideInTable: true,
      fieldProps: {
        placeholder: formatMessage({ id: 'component.user.add.user.id.placeholder' }),
        rows: 4,
      },
      colSize: 2,
      renderFormItem: () => <Input.TextArea />,
    },
    {
      title: <FormattedMessage id="public.user.id" defaultMessage="用户账号" />,
      dataIndex: 'id',
      ellipsis: true,
      search: false,
      hideInSearch: false,
      render: (text, record) => formatUserRender(record),
    },
  ];
  const tableExtraRender = () => {
    return (
      <Card
        bordered={false}
        bodyStyle={{ paddingTop: 0, paddingBottom: 0, marginBottom: -24, marginTop: -24 }}
      >
        <ProForm form={form} layout="horizontal" submitter={{ render: () => null }}>
          <ProFormDateTimePicker
            name="expires"
            fieldProps={{
              disabledDate: (current) => {
                return current && current < moment().startOf('day');
              },
            }}
            label={
              <div style={{ width: 80 - 14 }}>
                <FormattedMessage id="component.user.add.user.expires" />
              </div>
            }
            placeholder={formatMessage({ id: 'component.user.add.user.expires.placeholder' })}
          />
        </ProForm>
      </Card>
    );
  };
  const triggerRender = () => {
    return reloadReactNode(
      <Button
        type="primary"
        key="create"
        onClick={() => {
          setOpen(true);
        }}
      >
        <PlusOutlined /> <FormattedMessage id="public.user.new" defaultMessage="新增" />
      </Button>,
      setOpen,
      children,
    );
  };
  return (
    <>
      <Modal
        title={<FormattedMessage id="component.user.add.user.title" />}
        width="900px"
        open={open}
        destroyOnClose={true}
        onCancel={() => {
          setOpen(false);
        }}
        onOk={async () => {
          const { expires } = form.getFieldsValue();
          if (selectedRowKeys?.length < 1) {
            return;
          }
          try {
            await bindUsers(
              type,
              selectedRowKeys?.map((userId) => ({
                appId,
                userId,
                expiredAt: expires ? Math.floor(moment(expires).valueOf() / 1000) : expires,
                [`${type}Id`]: id,
                flagId,
              })),
            );
            reload?.();
            setOpen(false);
            message.success(formatMessage({ id: 'component.user.add.user.success' }));
          } catch (error) {}
        }}
      >
        <ProTable
          columns={columns}
          search={{
            labelWidth: 80,
          }}
          rowKey="id"
          pagination={false}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
          }}
          tableAlertRender={false}
          options={false}
          manualRequest={true}
          tableExtraRender={tableExtraRender}
          request={async (data) => {
            const req = await validateUsersRequest({
              accounts: data.accounts?.trim()?.split(',') || [],
              appId,
              [`${type}Id`]: id,
              flagId,
            });
            setSelectedRowKeys(req?.map((d) => d.id) || []);
            return { data: req };
          }}
        />
      </Modal>
      {triggerRender()}
    </>
  );
};
export default memo(AddUser);
