import React, { Fragment, useState } from 'react';
import ConfirmModal from 'components/ConfirmModal';
import CategoryList from './CategoryList';
import { request } from 'utils/fetch';
import EasyvButton from 'components/EasyvButton';
import styles from './CategoryModal.less';
import { REQUEST_URL, REQUEST_PARAM } from './request';

export default function CategoryModal({ data, refresh, children, type, belongTo }) {
  const [visible, setVisible] = useState(false);
  const [adding, setAdding] = useState(false);

  const handleAdd = async (value) => {
    if (value) {
      await request(REQUEST_URL[belongTo].add, undefined, undefined, JSON.stringify({ name: value, type: REQUEST_PARAM[type].type }));
      refresh();
    }

    setAdding(false);
  };

  const handleDelete = async (id) => {
    await request(REQUEST_URL[belongTo].delete, { id });
    refresh();
  };

  const handleUpdate = async (value) => {
    const { id, ...rest } = value;
    await request(REQUEST_URL[belongTo].update, { id }, undefined, JSON.stringify(rest));
    refresh();
  };

  const handleSort = async ({ oldIndex, newIndex }: any) => {
    if (oldIndex === newIndex) {
      return;
    }

    const result = data.concat();
    const old = result[oldIndex];
    result.splice(oldIndex, 1);
    result.splice(newIndex, 0, old);

    const ids = result.reduce((all, item) => {
      return all.concat(item.id).concat(item.children.map((d) => d.id));
    }, []);

    await request(REQUEST_URL[belongTo].sort, undefined, undefined, JSON.stringify({ ids }));
    refresh();
  };

  const footer = (
    <div className={styles.footer}>
      <span className={styles.add} onClick={() => setAdding(true)}>
        + 添加分类
      </span>
      <EasyvButton onClick={() => setVisible(false)}>关闭</EasyvButton>
    </div>
  );

  return (
    <Fragment>
      <span onClick={() => setVisible(true)}>{children}</span>
      <ConfirmModal
        visible={visible}
        title="分类管理"
        onCancel={() => setVisible(false)}
        theme="black"
        footer={footer}
        contentStyle={{ padding: '16px 0' }}>
        <CategoryList
          adding={adding}
          categorys={data}
          onAdd={handleAdd}
          onUpdate={handleUpdate}
          onDelete={handleDelete}
          onSort={handleSort}
          refresh={refresh}
          type={type}
          belongTo={belongTo}
        />
      </ConfirmModal>
    </Fragment>
  );
}
