import React, { memo, useState, useEffect, Fragment } from 'react';
import { Select } from '@easyv/antd';
import { SortableContainer } from 'react-sortable-hoc';
import ConfirmModal from 'components/ConfirmModal';
import ModuleItem from './SortItem';
import classNames from 'classnames';
import styles from '../SortModal.less';

const MySortbaleContainer = SortableContainer(({ children }) => <div className={styles.sortContainer}>{children}</div>);

function SortModal({ children, categorys, data, onOk }) {
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [current, setCurrent] = useState<number>(categorys[0]?.children[0]?.id);
  const [orders, setOrders] = useState({});

  useEffect(() => {
    if (!visible) {
      setOrders({});
      setCurrent(categorys[0]?.children[0]?.id);
    }
  }, [visible, data]);

  useEffect(() => {
    if (categorys.length) {
      setCurrent(categorys[0]?.children[0]?.id);
    }
  }, [categorys]);

  const handleSortEnd = ({ oldIndex, newIndex }) => {
    let arr = filteredModules.slice();
    arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
    setOrders((prev) => ({ ...prev, [current]: arr }));
  };

  const handleOk = async () => {
    setConfirmLoading(true);
    let result = await onOk(orders, data);
    setConfirmLoading(false);
    if (result) {
      setVisible(false);
    }
  };

  const filteredModules = orders[current] ? orders[current] : data.filter((d) => d.officialCategoryId == current);

  return (
    <Fragment>
      <span onClick={() => setVisible(true)}>{children}</span>
      <ConfirmModal
        confirmLoading={confirmLoading}
        width={700}
        visible={visible}
        title="排序"
        okText="保存"
        footer={true}
        onCancel={() => setVisible(false)}
        onOk={handleOk}
        theme="black">
        <div className={styles.formItem}>
          <label className={styles.label}>组件类别：</label>
          <div className={styles.field}>
            <Select value={current} onChange={(value) => setCurrent(value)} dropdownClassName={styles.selectDrop}>
              {categorys.map((d) => (
                <Select.OptGroup key={d.id} label={d.name}>
                  {d.children?.map((v) => {
                    return (
                      <Select.Option key={v.id} value={v.id}>
                        {v.name}
                      </Select.Option>
                    );
                  })}
                </Select.OptGroup>
              ))}
            </Select>
          </div>
        </div>

        <div className={styles.formItem}>
          <label className={styles.label}>拖拽排序：</label>
          <div className={classNames(styles.field, styles.sort)}>
            <p className={styles.tip}>拖拽下列组件进行排序</p>
            <MySortbaleContainer axis="xy" onSortEnd={handleSortEnd}>
              {filteredModules.length ? (
                filteredModules.map((d, i) => <ModuleItem key={d.id} index={i} name={d.name} thumb={d.thumb} />)
              ) : (
                <div style={{ textAlign: 'center', flex: 1, lineHeight: '100px' }}>该分类下暂无组件</div>
              )}
            </MySortbaleContainer>
          </div>
        </div>
      </ConfirmModal>
    </Fragment>
  );
}

export default memo(SortModal);
