import { DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import {
  Button,
  Col,
  Empty,
  Modal,
  Row,
  Space,
  Spin,
  Tabs,
  TabsProps,
  message,
} from 'antd';
import classNames from 'classnames';
import React, { useEffect, useState } from 'react';
import Icon, { IconImg } from '../../components/Icon';
import Truly from '../../components/Truly';
import Upload from '../../components/Upload';
import { SUPPORT_IMAGE_ACCEPT } from '../../constants';
import { FileController } from '../../services';
import {
  clearSvgColor,
  getPureSvgText,
  getSvgText,
  isSvg,
} from '../../utils/html';
import styles from './index.less';

interface TabPanelProps {
  type: string;
  picType: string;
}

const TabPanel: React.FC<TabPanelProps> = (props) => {
  const { type, picType } = props;
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const {
    data: fileList,
    loading: getFileListLoading,
    run: getFileListRun,
  } = useRequest(FileController.getListApi, {
    manual: true,
  });

  useEffect(() => {
    getFileListRun({ type, picType });
    setSelectedKeys([]);
  }, [getFileListRun, picType, type]);

  const onDelete = (deleteList: string[]) => {
    Modal.confirm({
      content: `是否确认执行图片删除操作？`,
      maskClosable: true,
      onOk: async () => {
        const deleteKeys = deleteList.join(',');
        await FileController.delApi(deleteKeys);
        getFileListRun({ type, picType });
        setSelectedKeys([]);
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  const onUpload = async (files: any) => {
    const [file] = files || [];
    if (!SUPPORT_IMAGE_ACCEPT.includes(file.type)) {
      message.error('不支持的图片格式!');
      throw new Error('error');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片最大不超过2MB!');
      throw new Error('error');
    }
    const forms = new FormData();
    forms.append('type', type);
    forms.append('picType', picType);
    forms.append('file', file);
    forms.append('isSvg', '2');
    await FileController.uploadApi(forms);
    getFileListRun({ type, picType });
  };

  const onUploadSvg = async (files: any) => {
    const [file] = files || [];
    const svgText = await getSvgText(file);
    const isSvgFlag = isSvg(svgText);
    if (!isSvgFlag) {
      message.error('svg图片格式有误!');
      throw new Error('error');
    }
    const fileContent = clearSvgColor(getPureSvgText(svgText));
    const forms = new FormData();
    forms.append('type', type);
    forms.append('picType', picType);
    forms.append('fileContent', fileContent);
    forms.append('isSvg', '1');
    await FileController.uploadApi(forms);
    getFileListRun({ type, picType });
  };

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <div style={{ marginBottom: 8 }}>
          <Row gutter={16}>
            <Col span={12}>
              <Upload
                accept={SUPPORT_IMAGE_ACCEPT.join(',')}
                onUpload={onUpload}
                trigger={
                  <div className={styles.uploadBlock}>
                    <Space>
                      <UploadOutlined />
                      <span>上传图片</span>
                    </Space>
                  </div>
                }
              ></Upload>
            </Col>
            <Col span={12}>
              <Truly truly={picType === '1'}>
                <Upload
                  accept="image/svg+xml"
                  onUpload={onUploadSvg}
                  trigger={
                    <div className={styles.uploadBlock}>
                      <Space>
                        <UploadOutlined />
                        <span>上传SVG</span>
                        <span style={{ color: '#999' }}>
                          （具有着色、缩放不失真等优点）
                        </span>
                      </Space>
                    </div>
                  }
                ></Upload>
              </Truly>
            </Col>
          </Row>
        </div>
      </div>
      <div>
        <div className={styles.imageNotice}>
          <span>单击可切换图片的选中状态，可删除选中的图片</span>
          <Button
            danger
            type="link"
            icon={<DeleteOutlined />}
            disabled={selectedKeys.length === 0}
            onClick={() => onDelete(selectedKeys)}
          >
            批量删除
          </Button>
          <Button
            type="link"
            disabled={selectedKeys.length === 0}
            onClick={() => {
              setSelectedKeys([]);
            }}
          >
            取消选中
          </Button>
        </div>
        <div className={styles.imagePanel}>
          <Truly truly={getFileListLoading}>
            <div className={styles.imageLoading}>
              <Spin></Spin>
            </div>
          </Truly>
          <Truly
            truly={(fileList || []).length > 0}
            falsyRender={<Empty description=""></Empty>}
          >
            <div className={styles.imageItems}>
              {(fileList || []).map((item) => {
                return (
                  <div
                    className={classNames({
                      [styles.imageItem]: true,
                      [styles.imageItemActive]: selectedKeys.includes(
                        item?.fileId || '',
                      ),
                      [styles.imageItemIcon]: item.picType === '1',
                    })}
                    key={item.fileId}
                    onClick={() =>
                      setSelectedKeys((pre) => {
                        const { fileId = '' } = item || {};
                        if (selectedKeys.includes(fileId)) {
                          return pre.filter(
                            (selectedKey) => selectedKey !== fileId,
                          );
                        }
                        return [...pre, fileId];
                      })
                    }
                  >
                    <Truly
                      truly={item.isSvg === '1'}
                      falsyRender={
                        <IconImg
                          url={item?.filePath || ''}
                          style={{ maxHeight: '100%', maxWidth: '100%' }}
                        ></IconImg>
                      }
                    >
                      <Icon svg={item.fileContent} size={32}></Icon>
                      <span className={styles.imageItemTitle}>svg</span>
                    </Truly>
                  </div>
                );
              })}
            </div>
          </Truly>
        </div>
      </div>
    </div>
  );
};

export default () => {
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: `菜单图标`,
      children: <TabPanel type="0" picType="1" />,
    },
    {
      key: '2',
      label: `应用logo`,
      children: <TabPanel type="0" picType="2" />,
    },
    {
      key: '9',
      label: `其他`,
      children: <TabPanel type="0" picType="9" />,
    },
  ];
  return (
    <ProCard>
      <Tabs defaultActiveKey="1" items={items} destroyInactiveTabPane />
    </ProCard>
  );
};
