import React, { useState, useEffect, Fragment } from 'react';
import classNames from 'classnames';
import ConfirmModal from 'components/ConfirmModal';
import SortableItem from './SortableItem';
import cloneDeep from 'lodash/cloneDeep';
import styles from '../SortModal.less';

export default function SortModal({ data, children, onComplete }) {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [themePackList, setthemePack] = useState(data);

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

  const showModal = () => {
    setVisible(true);
  };

  const hideModal = () => {
    setVisible(false);
    setLoading(false);
  };

  const moveCard = (dragIndex, hoverIndex) => {
    const _themePackList = cloneDeep(themePackList);
    if (dragIndex > hoverIndex) {
      _themePackList.splice(hoverIndex, 0, _themePackList[dragIndex]);
      _themePackList.splice(dragIndex + 1, 1);
    } else {
      _themePackList.splice(hoverIndex + 1, 0, _themePackList[dragIndex]);
      _themePackList.splice(dragIndex, 1);
    }
    setthemePack(_themePackList);
  };

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

  return (
    <span>
      <span onClick={showModal}>{children}</span>
      <ConfirmModal
        title="主题包排序"
        contentStyle={{ padding: '0 24px 24px' }}
        visible={visible}
        footer={true}
        okText="保存"
        width={700}
        theme="black"
        onCancel={hideModal}
        onOk={handleComplete}
        confirmLoading={loading}>
        <Fragment>
          <div className={styles.formItem} style={{ margin: 0 }}>
            <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}>
                {themePackList.map((d: any, i) => (
                  <SortableItem className={styles.item} key={d.id} index={i} id={d.id} data={d} moveCard={moveCard} />
                ))}
              </ul>
            </div>
          </div>
        </Fragment>
      </ConfirmModal>
    </span>
  );
}
