import React, { useState, useMemo } from 'react';
import Dropdown from 'antd/es/dropdown';
import 'antd/es/dropdown/style/index';
import Menu from 'antd/es/menu';
import 'antd/es/menu/style/index';
import Button from 'antd/es/button';
import 'antd/es/button/style/index';
import Spin from 'antd/es/spin';
import 'antd/es/spin/style/index';
import message from 'antd/es/message';
import 'antd/es/message/style/index';
import { MenuInfo } from 'rc-menu/es/interface';
import DownOutlined from '@ant-design/icons/DownOutlined';
import { loadFile } from '@jy-fe/utils/es/joyowoUmi';
import { getRoleKeyFromUrl } from '@jy-fe/business/es/authority';
import { XuiExportButtonProps } from './xui-export-button.d';

const ExportButton: React.FC<XuiExportButtonProps> = ({
  roleId,
  aidMap,
  aid,
  maximum = 0,
  total = 0,
  title = '导出',
  type = 'primary',
  listPageRef,
  selectedKeyNameForGet,
  selectedKeyNameForRequest,
  selectedKeys,
  searchParams,
  exportSearchRowApi,
  exportSelectedRowApi,
  interceptRequst,
  getPopupContainer,
  interceptRequstCallback,
  extraParams,
  extraOptions,
}) => {
  const [loading, setLoading] = useState(false);

  const aidVal = useMemo(() => {
    if (aid) return aid;
    if (aidMap) return aidMap[getRoleKeyFromUrl()];
    return '';
  }, [aid, aidMap]);

  const header = useMemo(
    () => ({
      rid: roleId || '',
      aid: aidVal,
    }),
    [roleId, aidVal],
  );

  const selectMenuItem = async (e: MenuInfo) => {
    const { key } = e;
    if (key === '1') {
      // 导出选中项
      let keys: React.Key[] = [];
      if (listPageRef && listPageRef.current) {
        keys = selectedKeyNameForGet
          ? listPageRef.current.selectedRows.map(row => row[selectedKeyNameForGet])
          : listPageRef.current.selectedRowKeys;
      } else {
        keys = selectedKeys || [];
      }
      if (keys.length === 0) {
        const currentMsg = '请先选择数据！';
        message.warn(currentMsg);
        return false;
      }
      if (maximum && keys.length > maximum) {
        const currentMsg = `导出数量超限，单次导出请控制在${maximum}条以内！`;
        message.warn(currentMsg);
        return false;
      }
      const params = selectedKeyNameForRequest
        ? { [selectedKeyNameForRequest]: keys }
        : { idList: keys };
      if (!interceptRequst && exportSelectedRowApi) {
        setLoading(true);
        const res = await exportSelectedRowApi(
          { ...params, ...extraParams },
          {
            header,
            ...extraOptions,
          },
        );
        const { status, msg, data } = res;
        if (!status) {
          loadFile(data);
        } else if (msg) {
          message.warn(msg);
        }
        setLoading(false);
      } else if (interceptRequstCallback) {
        interceptRequstCallback({
          activeKey: key,
          requestParams: params,
        });
      }
      return false;
    }
    if (key === '2') {
      // 导出筛选结果
      let currentTotal = 0;
      if (listPageRef && listPageRef.current) {
        currentTotal = listPageRef.current.total;
      } else {
        currentTotal = total;
      }
      if (currentTotal === 0) {
        const currentMsg = '暂无数据，无法导出';
        message.warn(currentMsg);
        return false;
      }
      if (maximum && currentTotal > maximum) {
        const currentMsg = `导出数量超限，单次导出请控制在${maximum}条以内！`;
        message.warn(currentMsg);
        return false;
      }
      let params = {};
      if (listPageRef && listPageRef.current) {
        params = listPageRef.current.searchState;
      } else {
        params = searchParams || {};
      }
      if (!interceptRequst && exportSearchRowApi) {
        setLoading(true);
        const res = await exportSearchRowApi(
          { ...params, ...extraParams },
          {
            header,
            ...extraOptions,
          },
        );
        const { status, msg, data } = res;
        if (!status) {
          loadFile(data);
        } else if (msg) {
          message.warn(msg);
        }
        setLoading(false);
      } else if (interceptRequstCallback) {
        interceptRequstCallback({
          activeKey: key,
          requestParams: params,
        });
      }
      return false;
    }
    return true;
  };

  return (
    <Dropdown
      trigger={['hover']}
      getPopupContainer={getPopupContainer}
      overlay={
        <Menu onClick={selectMenuItem}>
          <Menu.Item key='1'>导出选中项</Menu.Item>
          <Menu.Item key='2'>导出筛选结果</Menu.Item>
        </Menu>
      }
    >
      <Spin spinning={loading}>
        <Button type={type}>
          {title}
          <DownOutlined />
        </Button>
      </Spin>
    </Dropdown>
  );
};

export default ExportButton;
