import React, { memo, useState, useCallback } from 'react';
import { connect } from 'react-redux';
import ModuleSortModal from './ModuleSortModal';
import { sortModules } from 'models/module';
import EasyvButton from 'components/EasyvButton';

function ModuleSort({ categorys, modules, sortModules }) {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleCancel = useCallback(() => {
    setVisible(false);
  }, []);

  const handleOk = useCallback(async (orders) => {
    let orderKeys = Object.keys(orders);
    if (orderKeys.length) {
      setLoading(true);
      const result = await sortModules(orders);
      setLoading(false);
      if (result) {
        setVisible(false);
      }
    } else {
      setVisible(false);
    }
  }, []);

  return (
    <span>
      <EasyvButton style={{ marginRight: 12 }} onClick={() => setVisible(true)}>
        组件排序
      </EasyvButton>
      <ModuleSortModal
        visible={visible}
        confirmLoading={loading}
        categorys={categorys}
        modules={modules}
        onCancel={handleCancel}
        onOk={handleOk}
      />
    </span>
  );
}

const mapStateToProps = ({ modules }) => {
  return {
    modules: modules.list,
    categorys: modules.categorys
  };
};

const mapDispatchToProps = {
  sortModules
};

export default connect(mapStateToProps, mapDispatchToProps)(memo(ModuleSort));
