import React, { memo, useState, useCallback } from 'react';
import { connect } from 'react-redux';
import ModuleSortModal from '../modulePanel/ModuleSortModal';
import { sortTemplate, getAllTemplates } from 'models/template';
import { useEffect } from 'react';
import EasyvButton from 'components/EasyvButton';

function TemplateSort({ categorys, sortTemplate, getAllTemplates }) {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState([]);

  useEffect(() => {
    if (visible) {
      getAllTemplates().then((list) => setList(list));
    }
  }, [visible]);

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

  const handleOk = useCallback(async (orders, oldList) => {
    setLoading(true);
    await sortTemplate(orders, oldList);
    setLoading(false);
    setVisible(false);
  }, []);


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

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

const mapDispatchToProps = {
  sortTemplate,
  getAllTemplates
};

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