import {
  ModalForm,
  ProFormDependency,
  ProFormTextArea,
} from '@ant-design/pro-components';
import React from 'react';
import Icon from '../../../components/Icon';

interface SvgEditFormProps {
  title: string;
  trigger: JSX.Element;
  onOk: (fileContent: string) => void;
}

const isSvg = (svg: string) => /<svg([\S\s]*?)>([\S\s]*?)<\/svg>/.test(svg);

const clearSvgColor = (svg: string) => svg.replace(/fill="([\S\s]*?)"/g, ''); // 清除svg的填充色

const getSvgContent = (svg: string) =>
  svg.replace(
    /<svg[\S\s]*?>([\S\s]*?)<\/svg>/,
    '<svg viewBox="0 0 1024 1024">$1</svg>',
  );

const SvgEditForm: React.FC<SvgEditFormProps> = ({ trigger, title, onOk }) => {
  return (
    <ModalForm<{ fileContent: string }>
      layout="horizontal"
      title={title}
      trigger={trigger}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
      }}
      width={1200}
      submitTimeout={2000}
      onFinish={async ({ fileContent = '' }) => {
        onOk(clearSvgColor(getSvgContent(fileContent)));
        return true;
      }}
    >
      <ProFormTextArea
        name="fileContent"
        label="svg内容"
        fieldProps={{ rows: 16, maxLength: 10000, showCount: true }}
        placeholder="用记事本打开svg格式的图片，将其全部的内容粘贴至处"
        required
        rules={[
          {
            validator: async (rule, value = '') => {
              if (!isSvg(value)) {
                throw new Error('svg内容格式不正确！');
              }
            },
          },
        ]}
      />
      <ProFormDependency name={['fileContent']}>
        {({ fileContent = '' }) => {
          if (isSvg(fileContent)) {
            return (
              <>
                <div style={{ textAlign: 'center' }}>
                  <Icon
                    svg={clearSvgColor(getSvgContent(fileContent))}
                    size={80}
                    color="#333"
                  ></Icon>
                </div>
                <div
                  style={{ textAlign: 'center', color: '#666', marginTop: 16 }}
                >
                  <span>预览图</span>
                </div>
              </>
            );
          }
        }}
      </ProFormDependency>
    </ModalForm>
  );
};

export default SvgEditForm;
