import React, { useState, useEffect } from 'react';
import classNames from 'classnames';
import SortableConstantItem from './SortableConstantItem';
import styles from './SortConstantModal.less';
import EasyvModal, { useActionModalRef } from 'components/EasyvModal';

export default function SortConstantModal({ data, children, onComplete }) {
  const [loading, setLoading] = useState(false);
  const [orders, setOrders] = useState(data);
  const modalRef = useActionModalRef();

  useEffect(() => {
    setOrders(data);
  }, [data]);

  const hideModal = () => {
    modalRef.current?.close();
    setLoading(false);
  };

  const moveCard = (dragIndex, hoverIndex) => {
    setOrders((prevOrders) => {
      const dragCard = prevOrders[dragIndex];
      const newConstantsOrder = prevOrders.concat();
      newConstantsOrder.splice(dragIndex, 1);
      newConstantsOrder.splice(hoverIndex, 0, dragCard);
      return newConstantsOrder;
    });
  };

  const handleComplete = async () => {
    if (orders.length) {
      setLoading(true);
      const result = await onComplete(orders.map((d) => d.id));
      setLoading(false);
      if (result) {
        hideModal();
      }
    } else {
      hideModal();
    }
  };

  return (
    <>
      <span onClick={() => modalRef.current?.show()}>{children}</span>
      <EasyvModal.ActionModal
        ref={modalRef}
        onCancel={hideModal}
        onOk={handleComplete}
        confirmLoading={loading}
        title="组件排序"
        width={704}
        maxHeight={474}
        content={
          <div className={styles.formItem}>
            <label className={styles.label}>
              <b className={styles.requiredIcon}>*</b>拖拽排序：
            </label>
            <div className={classNames(styles.field, styles.sort)}>
              <p className={styles.tip}>拖拽下列组件进行排序</p>
              <ul className={styles.sortContainer}>
                {orders.map((d, i) => (
                  <SortableConstantItem key={d.moduleName} index={i} id={d.moduleName} data={d} moveCard={moveCard} />
                ))}
              </ul>
            </div>
          </div>
        }
      />
    </>
  );
}
