import React, { useState } from 'react';
import { connect } from 'react-redux';
import { Divider, Space } from '@easyv/antd';
import EasyvButton from 'components/EasyvButton';
import { Export } from '../../components';
import { Input, ConfigProvider } from '@easyv/react-gui';
import SortOption from '../../../screen-list/components/SortOption';
import styles from './index.less';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';
import { useProductionInfo } from 'components/easyUse';
import ResourceImport from '../../components/Import/ResourceImport';
import MaterialImport from '../../components/Import/MaterialImport';
import ExportResource from '../../components/Export/ExportResource';
import ExportMultiMaterisl from '../../components/Export/ExportMultiMaterisl';
import TemplateImport from '../../components/Import/TemplateImport';
import ExportModal from 'containers/resource/components/Export/ExportModal';
import ModalImport from 'containers/resource/components/Import/ModalImport';
import message from 'components/message';

const { Search } = Input;

function Toolbar({
  count,
  selectedList,
  edit,
  onEdit,
  onCancel,
  selectedAll,
  onSelectAll,
  onSearch,
  onUpload,
  onDelete,
  onSort,
  type,
  userInfo,
  refresh,
  storage,
  groupId
}) {
  const deletRef = useConfirmRef();
  const [searchKey, setSearchKey] = useState('');
  const productionInfo = useProductionInfo();
  const { isRenew } = productionInfo;

  const isNotUpload = storage?.used > storage?.total;

  const handleUpload = () => {
    if (isNotUpload) {
      message.error('您的资源数已超出上限，请删除部分资源后再试');
      return;
    }
    onUpload && onUpload();
  };

  const searchList = (e) => {
    const value = e.target.value;
    setSearchKey(value);
    onSearch(value);
  };

  const handleDelete = () => {
    onDelete(selectedList.map(({ id }) => id));
  };

  const handleSelectAll = () => {
    const allButton: any = document.querySelector('button[id=select-all]');
    allButton.blur();
    onSelectAll(!selectedAll);
  };

  const CENTER_TYPE = {
    TEMPLATE: 0,
    MATERIAL: 1,
    RESOURCE: 2,
    MODAL: 3
  };

  // 导入
  const IMPORT = {
    [CENTER_TYPE.TEMPLATE]: (
      <TemplateImport onComplete={refresh} groupId={groupId}>
        <EasyvButton theme="primary">模板导入</EasyvButton>
      </TemplateImport>
    ),
    [CENTER_TYPE.MATERIAL]: (
      <MaterialImport refresh={refresh}>
        <EasyvButton theme="default">资源导入</EasyvButton>
      </MaterialImport>
    ),
    [CENTER_TYPE.RESOURCE]: (
      <ResourceImport refresh={refresh}>
        <EasyvButton theme="primary">资源导入</EasyvButton>
      </ResourceImport>
    ),
    [CENTER_TYPE.MODAL]: (
      <ModalImport refresh={refresh}>
        <EasyvButton theme="default">资源导入</EasyvButton>
      </ModalImport>
    )
  };

  // 导出
  const EXPORT = {
    [CENTER_TYPE.TEMPLATE]: (
      <Export
        list={selectedList}
        onComplete={() => {
          onSelectAll(false);
          onCancel();
        }}>
        <EasyvButton disabled={!selectedList.length} theme="primary">
          导出
        </EasyvButton>
      </Export>
    ),
    [CENTER_TYPE.MATERIAL]: (
      <ExportMultiMaterisl
        data={selectedList.map((d) => ({ id: d.id, name: d.name }))}
        onReselect={() => {
          onSelectAll(false);
          onCancel();
        }}>
        <EasyvButton disabled={!selectedList.length} theme="primary">
          导出
        </EasyvButton>
      </ExportMultiMaterisl>
    ),
    [CENTER_TYPE.RESOURCE]: (
      <ExportResource
        data={selectedList.map((d) => ({ id: d.id, name: d.name }))}
        onReselect={() => {
          onSelectAll(false);
          onCancel();
        }}>
        <EasyvButton disabled={!selectedList.length} theme="primary">
          导出
        </EasyvButton>
      </ExportResource>
    ),
    [CENTER_TYPE.MODAL]: (
      <ExportModal
        data={selectedList.map((d) => ({ id: d.id, name: d.name }))}
        onReselect={() => {
          onSelectAll(false);
          onCancel();
        }}>
        <EasyvButton disabled={!selectedList.length} theme="primary">
          导出
        </EasyvButton>
      </ExportModal>
    )
  };

  return (
    <div className={styles.toolbar}>
      <div className={styles['toolbar-left']}>
        {edit ? (
          <p className={styles.fontStyle}>
            已选择 <span>{selectedList.length}</span> 个应用
          </p>
        ) : searchKey ? (
          <p className={styles.fontStyle}>
            搜索 <span>“{searchKey}”</span> {count}个结果
          </p>
        ) : (
          <Space size={0}>
            <p className={styles.fontStyle}>
              {type === 0 ? '模板' : '素材'}库 {count}个
            </p>
            {!window.appConfig.LOCAL && (
              <>
                <Divider type="vertical" style={{ borderColor: 'rgba(225,225,225,0.12)' }} />
                <a href={window.appConfig.HOME_URL + '/market'}>前往素材广场</a>
              </>
            )}
          </Space>
        )}
      </div>
      <div className={styles['toolbar-right']}>
        {edit ? (
          <Space>
            <EasyvButton id="select-all" theme="default" onClick={handleSelectAll}>
              {selectedAll ? '取消' : ''}全选
            </EasyvButton>
            <EasyvButton
              disabled={!selectedList.length}
              danger
              theme="danger"
              onClick={() => {
                if (selectedList.length <= 0) return;
                deletRef.current?.show();
              }}>
              删除
            </EasyvButton>
            {/* TODO后续抽离导出组件 */}
            {(window.appConfig.LOCAL || (type === 0 && userInfo?.edition?.id === 'saas_vip') || isRenew) && EXPORT[type]}
            {/* {EXPORT[type]} */}
            <EasyvButton theme="default" onClick={onCancel}>
              取消操作
            </EasyvButton>
          </Space>
        ) : (
          <Space>
            <ConfigProvider>
              <Search className={styles['search-input']} placeholder="搜索" onChange={searchList} value={searchKey} />
            </ConfigProvider>
            <SortOption
              onChange={(key) => {
                onSort(key === 'byUpdatedAt' ? 'updatedAt' : 'createdAt');
              }}
            />
            <EasyvButton theme="default" disabled={!count} onClick={onEdit}>
              批量管理
            </EasyvButton>
            {/* TODO导入功能先去掉 */}
            {(window.appConfig.LOCAL || isRenew) && IMPORT[type]}
            {/* {IMPORT[type]} */}
            {(type === 1 || type === 3) && (
              <EasyvButton theme="primary" onClick={handleUpload}>
                上传{type === 1 ? '素材' : '模型'}
              </EasyvButton>
            )}
          </Space>
        )}
      </div>
      <EasyvModal.Confirm
        content={<p style={{ whiteSpace: 'pre-wrap' }}>删除后不可恢复，是否删除？</p>}
        closable={false}
        title={`删除${type === 0 ? '模板' : '素材'}`}
        ref={deletRef}
        onOk={() => {
          handleDelete();
          deletRef.current?.close();
        }}
      />
    </div>
  );
}

const mapStateToProps = ({ user: { userInfo } }) => ({
  userInfo
});

export default connect(mapStateToProps)(Toolbar);
