import React, { useEffect, useMemo, useState } from 'react';
import { connect, useSelector } from 'react-redux';
import { Space } from '@easyv/antd';
import message from 'components/message';
import DeleteConfirmModal from 'components/DeleteConfirmModal';
import ExportFontsModal from './ExportFontsModal';
import ImportFontsModal from './ImportFontsModal';
import styles from '../style.less';
import { getFonts, deleteFonts } from 'models/font';
import EasyvTooltip from 'components/EasyvTooltip';
import classNames from 'classnames';
import { RootState } from 'models';
import EasyvButton from 'components/EasyvButton';
import PanelHeaderContainer from 'components/PanelHeaderContainer';
import EasyvTable from 'components/EasyvTable';
import { Input, ConfigProvider } from '@easyv/react-gui';

const { Search } = Input;

const FontPanel = ({ getFonts, deleteFonts }) => {
  const fonts = useSelector<RootState>((state) => state.fonts) as RootState['fonts'];
  const { list = [], loading = true } = fonts;
  const transfer = useSelector<RootState>((state) => state.transfer) as RootState['transfer'];
  const { deadline } = transfer;
  const [search, setSearch] = useState<string>('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [sorter, setSorter] = useState<{
    order?: 'descend' | 'ascend';
  }>({});

  useEffect(() => {
    document.title = '字体管理';
    dispatchGetFonts();
  }, []);

  const dispatchGetFonts = () => {
    getFonts();
  };

  const onSearchChange = (e) => {
    const value = e.target.value && e.target.value.trim();
    setSearch(value);
  };

  const onRowSelectChange = (selectedRowKeys) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const onExportComplete = () => {
    setSelectedRowKeys([]);
  };

  const onTableChange = (_pagination, _filter, sorter) => {
    setSorter(sorter);
  };

  const filterFont = () => {
    const { order = 'descend' } = sorter;
    const result = list.filter((d) => d.fullName.toLowerCase().includes(search.toLowerCase()));
    result.sort((a, b) => (order === 'descend' ? +new Date(b.create) - +new Date(a.create) : +new Date(a.create) - +new Date(b.create)));
    return result || [];
  };

  const dispatchDeleteFonts = async (fileList) => {
    const result = await deleteFonts(fileList);
    if (result) {
      message.success('删除成功');
      setSelectedRowKeys([]);
    }
  };

  const selectedFonts = useMemo(() => list.filter((d: any) => selectedRowKeys.includes(d.fullName)), [list, selectedRowKeys]);

  const columns = useMemo(
    () => [
      {
        title: '字体名称',
        dataIndex: 'fullName',
        width: '45%'
      },
      {
        title: '编辑时间',
        dataIndex: 'create',
        width: '35%',
        sorter: true,
        showSorterTooltip: false
      },
      {
        title: '操作',
        render: (_text, record: any) => (
          <Space>
            <EasyvTooltip title="导出">
              <i
                onClick={() => {
                  window.location.href = record.src;
                }}
                className={classNames('icon iconfont icon-daochu ' + styles.iconHover)}
              />
            </EasyvTooltip>
            <DeleteConfirmModal title="删除字体" onOk={() => dispatchDeleteFonts([record.fullName])}>
              <EasyvTooltip title="删除">
                <i className={classNames('icon iconfont icon-btn_delete ' + styles.iconHover)} />
              </EasyvTooltip>
            </DeleteConfirmModal>
          </Space>
        )
      }
    ],
    []
  );

  return (
    <div>
      <PanelHeaderContainer>
        <div>
          <ConfigProvider>
            <Search className={styles.searchInput} onChange={onSearchChange} placeholder="搜索字体名称" value={search} />
          </ConfigProvider>
          <ExportFontsModal fonts={selectedFonts} onComplete={onExportComplete}>
            <EasyvButton style={{ marginLeft: 16 }} disabled={!selectedRowKeys.length}>
              批量导出
            </EasyvButton>
          </ExportFontsModal>
          <DeleteConfirmModal title="批量删除字体" onOk={() => dispatchDeleteFonts(selectedFonts.map((d) => d.fullName))}>
            <EasyvButton style={{ marginLeft: 12 }} disabled={!selectedRowKeys.length}>
              批量删除
            </EasyvButton>
          </DeleteConfirmModal>
        </div>
        <div>
          <ImportFontsModal onComplete={dispatchGetFonts}>
            <EasyvButton theme="primary" style={{ marginRight: 12 }}>
              导入
            </EasyvButton>
          </ImportFontsModal>
        </div>
      </PanelHeaderContainer>

      <EasyvTable
        loading={loading}
        selectedRowKeys={selectedRowKeys}
        rowKey={(d: any) => d.fullName}
        dataSource={filterFont()}
        onRowSelectChange={onRowSelectChange}
        onChange={onTableChange}
        // pageSize={20}
        columns={columns}
        scroll={deadline ? { y: 'calc(100vh - 298px)' } : { y: 'calc(100vh - 250px)' }}
      />
    </div>
  );
};
function mapStateToProps({ fonts }) {
  return {
    fonts: fonts.list,
    loading: fonts.loading
  };
}

export default connect(mapStateToProps, {
  getFonts,
  deleteFonts
})(FontPanel);
