import React, { useState, useCallback } from 'react';
import { connect } from 'react-redux';
import { useHistory } from 'react-router-dom';
import CreateModal from './CreateModal';
import ImportModal from './ImportModal';
import { searchActions, listActions, InteractionListState } from './models';
import styles from './Operate.less';
import EasyvButton from 'components/EasyvButton';
import EasyvSearchHeader from 'components/EasyvSearchHeader';
import { UserState } from 'models/user.types';
import TransferScroll from 'containers/TransferScroll';
import { useAuth } from 'components/easyUse';

function Operate({
  search,
  createLoading,
  addable,
  isImportExpired,
  onSearch,
  onCreate,
  getList,
  interactionListLength,
  updateInteractionSortType
}) {
  const [visible, setVisible] = useState(false);
  const [importVisible, setImportVisible] = useState(false);
  const history = useHistory();
  const { checkAuth } = useAuth();

  const onClose = useCallback(() => {
    setVisible(false);
  }, []);
  const onOk = useCallback(async (value) => {
    const result = await onCreate(value);
    if (result) {
      history.push(`/app/edit/${result.id}/${result.pages[0].id}`);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const handleSearch = useCallback((e) => {
    onSearch(e.target.value);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleCloseImport = useCallback(() => {
    setImportVisible(false);
  }, []);

  const handleImportComplete = useCallback(() => {
    setImportVisible(false);
    getList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onSelectSortTypeChange = (e) => {
    if (e === 'byUpdatedAt') {
      //按修改时间排序
      updateInteractionSortType('byUpdatedAt');
      return;
    }
    //按创建时间排序
    updateInteractionSortType('byCreatedAt');
  };

  return (
    <div className={styles.wrapper}>
      <TransferScroll type="other" />
      <div className={styles.btn_wrapper}>
        {addable ? (
          <EasyvButton
            theme="primary"
            onClick={() => setVisible(true)}
            style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <i className="icon iconfont icon-constant-custom" style={{ position: 'relative', top: '1px' }} />
            新建应用
          </EasyvButton>
        ) : (
          <div />
        )}
        {!isImportExpired && (
          <EasyvButton theme="default" onClick={() => setImportVisible(true)}>
            应用导入
          </EasyvButton>
        )}
      </div>

      <div className={styles.search_wrapper}>
        <EasyvSearchHeader
          onSearchChange={handleSearch}
          search={search}
          isNoTrashedScreen={false}
          currentGroupName={'我的终端应用'}
          onSelectSortTypeChange={onSelectSortTypeChange}
          currentAllScreenLength={interactionListLength}
          filterScreenLength={interactionListLength}
        />
      </div>
      {visible && <CreateModal visible={visible} onClose={onClose} onOk={onOk} confirmLoading={createLoading} />}
      {importVisible && <ImportModal checkAuth={checkAuth} onClose={handleCloseImport} onComplete={handleImportComplete} />}
    </div>
  );
}

function mapStateToProps({ interactionList, user }: { interactionList: InteractionListState; user: UserState }) {
  const { search, createLoading, list = [], sortType } = interactionList;

  return {
    search,
    createLoading,
    addable: !(window.appConfig.LOCAL && user.userInfo.type === 'education'),
    isImportExpired: user.userInfo.isImportExpired,
    interactionListLength: list
      .filter((d) => d.name.toLowerCase().includes(search.toLowerCase()))
      .sort((a, b) => {
        if (sortType === 'byUpdatedAt') {
          return Number(a.updatedAt < b.updatedAt);
        }
        return Number(a.createdAt < b.createdAt);
      }).length
  };
}

const mapDispatchToProps = {
  onSearch: searchActions.onSearch,
  updateInteractionSortType: searchActions.updateInteractionSortType,
  onCreate: listActions.create,
  getList: listActions.getList
};

export default connect(mapStateToProps, mapDispatchToProps)(Operate);
