import { Button, Modal, Space, Typography, Upload, message } from 'antd';

import { DownloadOutlined, UploadOutlined } from '@ant-design/icons';
import { memo, useState } from 'react';
import { useGetAppId } from '../utils/hooks';
import { uploadFile } from '../server';
import { FormattedMessage, useIntl } from 'umi';
import Flex from '../Flex';
const { Text, Link, Paragraph } = Typography;

interface ImportFileProps {
  /**
   * @description 成功以后的提示
   */
  successTitle?: string | React.ReactNode;
  /**
   * @description 自定义导入弹窗的title
   */
  title?: string | React.ReactNode;
  /**
   * @description 需要自定义传入文档链接
   * //https://huolala.feishu.cn/wiki/EWQLwNmWliPNkkkiysTcbfAzn7g
   */
  docUrl?: string;
  /**
   * @description 自定义描述信息
   */
  description?: string | React.ReactNode;
  /**
   * @description 下载模版地址
   */
  demoUrl: string;
  /**
   * @description 导入的类型
   */
  type:
    | 'feature'
    | 'option'
    | 'policy'
    | 'role'
    | 'user_feature'
    | 'user_role'
    | 'user_option'
    | 'user_policy';
  /**
   * @description 传的参数
   */
  params?: {};
  /**
   * @description 成功以后执行的操作
   */
  refresh?: () => void;
  /**
   * @description 触发node
   */
  trigger?: string | React.ReactNode;
  /**
   * @description footer description by@edith
   */
  footer?: string | React.ReactNode;
}

const ImportFile = ({
  successTitle,
  params,
  type = 'feature',
  title,
  trigger,
  description,
  footer,
  demoUrl = '',
  docUrl = '',
  refresh,
}: ImportFileProps) => {
  const { formatMessage } = useIntl();
  const [open, setOpen] = useState(false);
  const appId = useGetAppId();
  const typeMap = {
    feature: 'feature/upload',
    option: 'option/import',
    policy: 'policy/upload',
    role: 'role/upload',
    user_feature: 'relation/user_feature/upload',
    user_role: 'relation/user_role/upload',
    user_option: 'relation/user_option/upload',
    user_policy: 'relation/user_policy/upload',
  };
  return (
    <>
      <Modal
        width={560}
        destroyOnClose
        title={title || formatMessage({ id: 'component.ImportFile.title' })}
        footer={null}
        open={open}
        onCancel={() => setOpen(false)}
      >
        <Space direction="vertical" size={12} style={{ width: '100%' }}>
          <Paragraph>
            <pre style={{ padding: 12 }}>
              <Flex>
                <Text disabled>
                  <Text type="danger" style={{ marginRight: 10 }}>
                    *
                  </Text>
                  {description || formatMessage({ id: 'component.ImportFile.description' })}
                </Text>
                {docUrl ? (
                  <Link href={docUrl} target="_blank">
                    <FormattedMessage id="component.ImportFile.info" />
                  </Link>
                ) : null}
              </Flex>
            </pre>
          </Paragraph>

          <Paragraph style={{ fontSize: 14 }}>
            <pre style={{ padding: 24 }}>
              <Flex>
                <Text>
                  <FormattedMessage id="component.ImportFile.download.content" />
                </Text>

                <Button
                  onClick={() => {
                    window.open(demoUrl, '_blank');
                  }}
                >
                  <DownloadOutlined />
                  <FormattedMessage id="component.ImportFile.download" />
                </Button>
              </Flex>
            </pre>
          </Paragraph>

          <Paragraph>
            <pre style={{ padding: 12 }}>
              <Space direction="vertical" style={{ width: '100%' }}>
                <Text>
                  <FormattedMessage id="component.ImportFile.upload.content" />
                </Text>
                <Text>{successTitle}</Text>
                <Upload
                  // name="file"
                  // action="/goapi/feature/upload"
                  // accept=".xlsx"
                  // withCredentials={true}
                  // data={{ appId: appId }}
                  // headers={{
                  //   'Uac-Token': getToken(),
                  // }}
                  customRequest={async ({ file, onSuccess, onError }) => {
                    const formData = new FormData();
                    formData.append('file', file);
                    formData.append('appId', `${appId}`);
                    for (const key in params) {
                      formData.append(key, params[key]);
                    }
                    try {
                      const response = await uploadFile(typeMap[type], formData);
                      if (response?.ret === 0) {
                        // @ts-ignore
                        onSuccess(response, file);
                        message.success(
                          formatMessage({ id: 'component.ImportFile.upload.success' }),
                        );
                      } else {
                        // @ts-ignore
                        onError(response?.msg);
                      }
                    } catch (error) {
                      // @ts-ignore
                      onError(error);
                    }
                    refresh?.();
                  }}
                >
                  <Button icon={<UploadOutlined />}>
                    <FormattedMessage id="component.ImportFile.upload" />
                  </Button>
                </Upload>
                {footer}
              </Space>
            </pre>
          </Paragraph>
        </Space>
      </Modal>
      <Space
        onClick={() => {
          setOpen(true);
        }}
      >
        {trigger ? (
          trigger
        ) : (
          <Button>
            <FormattedMessage id="component.ImportFile.import" defaultMessage="导入" />
          </Button>
        )}
      </Space>
    </>
  );
};

export default memo(ImportFile);
