import React, { memo, useState } from 'react';
import { Popconfirm, Switch, Tooltip } from '@easyv/antd';
import { SortableElement, SortableHandle } from 'react-sortable-hoc';
import { request } from 'utils/fetch';
import EditableText from './EditableText';
import styles from './CategoryItem.less';
import CategoryList from './CategoryList';
import { DragPointOutlined, DeleteOutlined, PlusOutlined } from '@easyv/react-icons';
import { REQUEST_URL, REQUEST_PARAM } from './request';

const DragHandle = SortableHandle(() => (
  <Tooltip title="拖拽排序">
    <span className="iconsBox" style={{ cursor: 'move' }}>
      <DragPointOutlined className="categoryIcon" />
    </span>
  </Tooltip>
));

const CategoryItem = SortableElement(({ id, name, isNew, childrenData, onUpdate, onDelete, refresh, type, belongTo }) => {
  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, parentCategoryId: id })
      );
      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 = childrenData.concat();
    const old = result[oldIndex];
    result.splice(oldIndex, 1);
    result.splice(newIndex, 0, old);

    const ids = result.map((d) => d.id);

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

  const handleOk = (value) => {
    onUpdate({
      id,
      name: value
    });
  };

  return (
    <li className={styles.container} style={{ fontSize: childrenData ? 14 : 12 }}>
      <div className={styles.alignCenter} style={{ paddingLeft: childrenData ? 4 : 24 }}>
        <DragHandle />

        <EditableText text={name} onOk={handleOk}>
          {childrenData ? (
            <Switch
              className={styles.switch}
              checked={isNew}
              checkedChildren="new"
              unCheckedChildren="new"
              onChange={(checked) => onUpdate({ id, cornerMark: checked ? 'new' : '' })}
            />
          ) : null}
        </EditableText>
        <Popconfirm placement="top" title="此分类下若含有组件，分类删除后组件将被移入未分类下" onConfirm={() => onDelete(id)}>
          <span className="iconsBox">
            <DeleteOutlined className="categoryIcon" />
          </span>
        </Popconfirm>
        {childrenData && (
          <span className={styles.add} onClick={() => setAdding(true)}>
            <PlusOutlined className={styles.addIcon} />
          </span>
        )}
      </div>

      {childrenData && (
        <CategoryList
          adding={adding}
          categorys={childrenData}
          onAdd={handleAdd}
          onSort={handleSort}
          onUpdate={handleUpdate}
          onDelete={handleDelete}
          refresh={refresh}
          type={type}
          belongTo={belongTo}
        />
      )}
    </li>
  );
});

export default memo(CategoryItem);
