import React, { useState, useEffect, Fragment } from 'react';
import { Select } from '@easyv/antd';
import classNames from 'classnames';
import ConfirmModal from 'components/ConfirmModal';
import SortableItem from './SortableItem';
import styles from '../SortModal.less';

const { Option } = Select;
export default function SortModal({ data, constants, children, onComplete }) {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [component, setComponent] = useState('');
  const [orders, setOrders] = useState({});

  useEffect(() => {
    if (visible && !component) {
      const hasThemeConstants = constants.filter((d) => data.some((o) => o.from === d.moduleName));
      if (hasThemeConstants.length > 0) {
        setComponent(hasThemeConstants[0].moduleName);
      }
    }
  }, [data, visible]);

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

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

  const handleComponentChange = (value) => {
    setComponent(value);
  };

  const moveCard = (dragIndex, hoverIndex) => {
    let prevOrders = orders[component];
    if (!prevOrders) {
      prevOrders = data.filter((d) => d.from == component && d.from === d.moduleName);
    }
    setOrders((prev) => {
      let dragCard = prevOrders[dragIndex];
      let newConstantsOrder = prevOrders.concat();
      newConstantsOrder.splice(dragIndex, 1);
      newConstantsOrder.splice(hoverIndex, 0, dragCard);
      return {
        ...prev,
        [component]: newConstantsOrder
      };
    });
  };

  const handleComplete = async () => {
    if (Object.keys(orders).length) {
      setLoading(true);
      let completeOrders = Object.entries(orders).map((d: any) => ({ name: d[0], list: d[1].map((d) => d.id) }));

      const result = await onComplete(completeOrders);

      setLoading(false);

      if (result) {
        hideModal();
      }
    } else {
      hideModal();
    }
  };

  const hasThemeConstants = constants.filter((d) => data.some((o) => o.from === d.moduleName));

  let currentConstants = [];
  if (orders[component]) {
    currentConstants = orders[component];
  } else {
    currentConstants = data.filter((d) => d.from == component && d.from === d.moduleName);
  }

  return (
    <span>
      <span onClick={showModal}>{children}</span>
      <ConfirmModal
        title="主题排序"
        visible={visible}
        footer={true}
        okText="保存"
        width={700}
        theme="black"
        onCancel={hideModal}
        onOk={handleComplete}
        confirmLoading={loading}>
        {hasThemeConstants.length > 0 ? (
          <Fragment>
            <div className={styles.formItem}>
              <label className={styles.label}>
                <b className={styles.requiredIcon}>*</b>组件类别：
              </label>
              <div className={styles.field}>
                <Select
                  showSearch
                  optionFilterProp="title"
                  value={component}
                  onChange={handleComponentChange}
                  dropdownClassName={styles.selectDrop}>
                  {hasThemeConstants.map((d) => (
                    <Option key={d.moduleName} value={d.moduleName} title={d.name}>
                      {d.name}
                    </Option>
                  ))}
                </Select>
              </div>
            </div>
            <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}>
                  {currentConstants.map((d: any, i) => (
                    <SortableItem className={styles.item} key={d.id} index={i} id={d.id} data={d} moveCard={moveCard} />
                  ))}
                </ul>
              </div>
            </div>
          </Fragment>
        ) : (
          <div>暂无可排序的主题</div>
        )}
      </ConfirmModal>
    </span>
  );
}
