import type { ActionType } from '@ant-design/pro-table';
import { Button, Drawer, Popconfirm, message } from 'antd';
import React, { cloneElement, isValidElement, useImperativeHandle, useRef, useState } from 'react';
import { FormattedMessage, request } from 'umi';
import CustomTable from '../CustomTable';
import UserSelect from '../UserSelect';
import UserSelectModal from '../UserSelectModal';
import { formatUserRender } from '../utils';
import PermissionManage from './PermissionManage';

const ManageAdmin = React.forwardRef(
  (
    {
      children,
      appId,
    }: {
      appId: number;
      children?: React.ReactElement<{ onClick: () => void }>;
    },
    ref,
  ) => {
    const [open, setOpen] = useState(false);
    const [manualOpen, setManualOpen] = useState(false);
    const [userId, setUserId] = useState<number>();
    const actionRef = useRef<ActionType>();
    const listFetch = async function (params: {
      pageSize?: number;
      current?: number;
      userId?: number;
      appId?: number;
    }) {
      const { data } = await request('/goapi/app/managerUser/list', {
        method: 'POST',
        data: params,
        headers: {
          'Content-Type': 'application/json',
        },
      });
      return {
        data: data?.filter((item) => (params?.userId ? item.id === params?.userId : true)),
        total: data?.length,
        success: true,
      };
    };
    const onClose = () => {
      setOpen(false);
    };
    const triggerRender = () => {
      if (!isValidElement(children)) {
        return;
      }

      return cloneElement(children, {
        onClick: () => {
          setOpen(true);
        },
      });
    };
    const columns = [
      {
        title: (
          <FormattedMessage id="components.ManageAdmin.user.account" defaultMessage="用户账号" />
        ),
        dataIndex: 'userId',
        colSize: 2,
        render: (id, record) => {
          return formatUserRender({
            id: record.id,
            name: record.nameZh,
            account: record.nameEn,
            state: record.state,
          });
        },
        renderFormItem: () => <UserSelect />,
      },
      {
        title: <FormattedMessage id="components.ManageAdmin.option" defaultMessage="设置" />,
        dataIndex: 'option',
        valueType: 'option',
        width: 140,
        render: (text, record) => [
          <Popconfirm
            key={`del-${record.id}`}
            title={
              <FormattedMessage
                id="components.ManageAdmin.del.confirm"
                defaultMessage="是否确认移除?"
              />
            }
            onConfirm={async () => {
              await request('/goapi/app/managerUser/delete', {
                method: 'POST',
                data: {
                  userId: record.id,
                  appId,
                },
              });
              message.success(
                <FormattedMessage
                  id="components.ManageAdmin.del.success"
                  defaultMessage="移除成功"
                />,
              );
              actionRef?.current?.reload();
            }}
          >
            <a key="delete">
              <FormattedMessage id="components.ManageAdmin.del" defaultMessage="移除" />
            </a>
          </Popconfirm>,
          <PermissionManage
            key="management"
            userId={record.id}
            appId={appId}
            onFinish={() => actionRef?.current?.reload()}
          >
            <a>
              <FormattedMessage id="components.ManageAdmin.management" defaultMessage="权限管理" />
            </a>
          </PermissionManage>,
        ],
      },
    ];
    const toolbar = {
      actions: [
        <UserSelectModal
          state={1}
          modalProps={{
            okText: <FormattedMessage id="components.ManageAdmin.next" defaultMessage="下一步" />,
            title: (
              <FormattedMessage id="components.ManageAdmin.create" defaultMessage="新增用户" />
            ),
          }}
          key="create"
          onChange={(val) => {
            setUserId(val);
            setManualOpen(true);
          }}
        >
          <Button type="primary">
            <FormattedMessage id="components.ManageAdmin.create" defaultMessage="新增用户" />
          </Button>
        </UserSelectModal>,
      ],
    };

    useImperativeHandle(ref, () => ({
      toggleDrawer: (value: boolean) => setOpen(value),
    }));

    return (
      <>
        {triggerRender()}
        <PermissionManage
          manualOpen={manualOpen}
          setManualOpen={setManualOpen}
          userId={userId}
          appId={appId}
          isCreate
          onFinish={() => actionRef?.current?.reload()}
        />
        <Drawer
          width={600}
          maskClosable={false}
          bodyStyle={{ paddingLeft: 0, paddingRight: 0, paddingTop: 0 }}
          title={<FormattedMessage id="components.ManageAdmin.title" defaultMessage="管理员设置" />}
          onClose={onClose}
          open={open}
          destroyOnClose
        >
          <CustomTable
            actionRef={actionRef}
            form={{ style: { marginBottom: 0 } }}
            search={{ span: 8 }}
            columns={columns as any[]}
            toolbar={toolbar}
            params={{ appId }}
            request={listFetch}
            pagination={false}
          />
        </Drawer>
      </>
    );
  },
);
export default ManageAdmin;
