import { useRef, useState, memo, useMemo, useImperativeHandle } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { FormattedMessage, useIntl } from 'umi';
import { CustomTable, DepartSelect, UserSelect } from '../index';
import AppDetail from '../AppDetail';
import { batchRemoveUser, batchUnbind, getUserList, queryUserDepartures } from './api';
import type { FormInstance } from 'antd';
import { Button, Drawer, Popconfirm, message } from 'antd';
import { formatUserRender } from '../utils';
import React from 'react';

type LeavingUserManagerProps = {
  appId?: number;
  isDrawer?: boolean;
  auditType?: number;
  readOnly?: boolean;
  trigger?: () => React.ReactNode;
};

const LeaveTable = ({
  appId,
  auditType,
  isDrawer,
  readOnly,
}: {
  appId?: number;
  auditType?: number;
  isDrawer?: boolean;
  readOnly?: boolean;
}) => {
  const { formatMessage } = useIntl();
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [detailOpen, setDetailOpen] = useState(false);
  const [currentAppId, setCurrentAppId] = useState(appId);
  const [title, setTitle] = useState<string>();
  const [currentUserId, setCurrentUserId] = useState<number>();
  const [batchLoading, setBatchLoading] = useState(false);

  // 用户端离职员工列表
  const userColumns = [
    {
      title: <FormattedMessage id="base.app.name" defaultMessage="应用名称" />,
      dataIndex: 'appName',
      ellipsis: true,
      hideInSearch: true,
      order: 1,
      width: 120,
    },
    {
      title: <FormattedMessage id="public.user.id" defaultMessage="用户账号" />,
      dataIndex: 'userId',
      renderFormItem: () => <UserSelect />,
      ellipsis: true,
      width: 120,
      order: 2,
      render: (_text, record) => {
        return formatUserRender({
          nameZh: record?.userInfo?.nameZh,
          account: record?.userInfo?.account,
          state:
            record?.userInfo?.account || record?.userInfo?.nameZh ? record?.userInfo?.state : 1,
        });
      },
    },
    {
      title: <FormattedMessage id="public.user.department" defaultMessage="用户部门" />,
      dataIndex: 'departmentId',
      ellipsis: true,
      width: 180,
      order: 3,
      render: (_text, record) => {
        return record?.userInfo?.department;
      },
      renderFormItem: () => <DepartSelect />,
    },
    {
      title: <FormattedMessage id="public.user.post" defaultMessage="用户岗位" />,
      dataIndex: 'jobName',
      hideInSearch: true,
      width: 130,
      order: 4,
      ellipsis: true,
      render: (_text, record) => {
        return record?.userInfo?.jobName;
      },
    },
  ];

  // 管理端离职员工列表
  const manageColumns = [
    {
      title: <FormattedMessage id="public.user.id" defaultMessage="用户账号" />,
      dataIndex: 'userIds',
      renderFormItem: () => <UserSelect mode="multiple" />,
      ellipsis: true,
      width: 120,
      order: 1,
      render: (_text, record) => {
        return formatUserRender({
          nameZh: record?.nameZh,
          account: record?.account,
          state: record?.account || record?.nameZh ? record?.state : 1,
        });
      },
    },
    {
      title: <FormattedMessage id="public.user.department" defaultMessage="用户部门" />,
      dataIndex: 'fuzzyDepartName',
      ellipsis: true,
      width: 180,
      order: 2,
      render: (_text, record) => {
        return record?.departPath.reverse().join('>');
      },
    },
    {
      title: <FormattedMessage id="public.user.post" defaultMessage="用户岗位" />,
      dataIndex: 'jobName',
      hideInSearch: true,
      width: 130,
      order: 3,
      ellipsis: true,
    },
  ];

  const OperateColumns = [
    {
      title: <FormattedMessage id="base.common.operation" defaultMessage="操作" />,
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 200,
      render: (_text, record, _index, action) =>
        [
          <a
            key="detail"
            onClick={() => {
              setDetailOpen(true);
              setCurrentAppId(record?.appId ?? appId);
              setCurrentUserId(record?.userInfo?.id ?? record.id);
              setTitle(
                auditType
                  ? `${record?.userInfo?.nameZh}(${record?.userInfo?.account}) ${record?.appName}`
                  : `${record?.nameZh}(${record?.nameEn})`,
              );
            }}
          >
            <FormattedMessage id="component.LeavingUserManager.view" />
          </a>,

          <Popconfirm
            key={`del${record?.id}`}
            title={formatMessage({
              id: 'component.LeavingUserManager.unbind.and.delete.tips',
              defaultMessage: '是否确认解绑所有权限并删除？',
            })}
            onConfirm={async () => {
              try {
                if (auditType) {
                  const users = [{ appId: record.appId, userId: record.userInfo?.id }];
                  await batchRemoveUser(users, auditType);
                } else {
                  await batchUnbind([record?.id], appId as number, 'all');
                }
                message.success(formatMessage({ id: 'base.operation.success' }));
                action?.reload();
              } catch (error) {}
            }}
          >
            <a key="delete">
              <FormattedMessage
                id="component.LeavingUserManager.unbind.and.delete"
                defaultMessage="解绑所有权限并删除"
              />
            </a>
          </Popconfirm>,
        ].filter((_, i) => (readOnly ? i === 0 : true)),
    },
  ];

  const tableColumns = useMemo(() => {
    return [...(auditType ? userColumns : manageColumns), ...OperateColumns] as ProColumns<
      Record<string, any>,
      'text'
    >[];
  }, [auditType]);

  const tableAlert = ({ selectedRowKeys, selectedRows, onCleanSelected }) => [
    {
      label: (
        <FormattedMessage
          id="component.LeavingUserManager.batch.unbind.and.delete"
          defaultMessage="批量解绑所有权限并删除"
        />
      ),
      loading: batchLoading,
      onClick: async () => {
        try {
          setBatchLoading(true);
          // 批量操作用户端跟管理端接口不同
          if (auditType) {
            const users = selectedRows?.map((item) => {
              return { appId: item.appId, userId: item.userInfo?.id };
            });
            await batchRemoveUser(users, auditType);
          } else {
            await batchUnbind(
              selectedRows?.map((item) => item.id),
              appId as number,
              'all',
            );
          }
          message.success(formatMessage({ id: 'base.operation.success' }));
          actionRef.current?.reload();
          onCleanSelected();
        } catch (error) {
          console.error(error);
        } finally {
          setBatchLoading(false);
        }
      },
    },
  ];
  return (
    <>
      <CustomTable
        rowKey={(record: any) => {
          if (auditType) {
            return record?.appId + '-' + record?.userInfo.id;
          }
          return record.id;
        }}
        actionRef={actionRef}
        columns={tableColumns}
        request={(argument: any) => {
          if (auditType) {
            return queryUserDepartures({ ...argument, auditType });
          }
          const ids = argument?.userIds?.map((item) => item.id);
          const fuzzyDepartName = argument?.fuzzyDepartName || undefined;
          return getUserList({
            ...argument,
            userIds: ids,
            fuzzyDepartName,
            appId,
            userState: 0,
          });
        }}
        rowSelection={{}}
        tableAlert={tableAlert}
        search={{ span: isDrawer ? 8 : 6 }}
        formRef={formRef}
      />
      {detailOpen && (
        <AppDetail
          key="detail"
          appId={currentAppId as number}
          title={title}
          open={detailOpen}
          userId={currentUserId}
          setOpen={() => {
            setDetailOpen(false);
          }}
        />
      )}
    </>
  );
};

const LeavingUserManager = React.forwardRef<
  { toggleDrawer: (value: boolean) => void },
  LeavingUserManagerProps
>(({ appId, isDrawer, auditType, trigger, readOnly }, ref) => {
  const [open, setOpen] = useState(false);

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

  if (!isDrawer) {
    return <LeaveTable appId={appId} auditType={auditType} isDrawer={isDrawer} />;
  }

  return (
    <>
      <Drawer
        width="70%"
        title={<FormattedMessage id={'component.LeavingUserManager.title'} />}
        onClose={() => setOpen(false)}
        open={open}
      >
        <LeaveTable appId={appId} auditType={auditType} isDrawer={isDrawer} readOnly />
      </Drawer>
      {trigger?.()}
    </>
  );
});

export default memo(LeavingUserManager);
