import React, { useState, useEffect, useRef } from 'react';
import { Form, Button, Space, Input, message } from 'antd';
import { setTreeChapter } from '@/store/modules/user';
import { useDispatch, useSelector } from 'react-redux';
import { chapterEdit, chapterAdd, sectionAdd } from '../request';

const EditChapterTitle = (props) => {
  const {
    editValue,
    setEditValue,
    editKey,
    setEditKey,
    parentId,
    bookId,
    getChapterTreeList,
    expandedKeys,
    setExpandedKeys,
    editorLoading,
    newChapterChange,
  } = props;
  const dispatch = useDispatch();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [initValues, setInitValues] = useState({ title: editValue });
  const inputRef = useRef();

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, [editorLoading]);

  useEffect(() => {
    form.setFieldsValue({ title: editValue });
    setInitValues({ title: editValue });
  }, [editValue]);

  const onFinish = async (values) => {
    setLoading(true);
    let data = null;
    if (parentId) {
      data = await chapterAdd({
        pid: parentId === -1 ? 0 : parentId,
        book_id: bookId,
        name: values.title,
      });
    } else {
      data = await chapterEdit({ id: editKey, name: values.title });
      
    }
    await dispatch(setTreeChapter({ saveBookId: bookId, saveChapterId: data.id }));
    if (data) {
      if (parentId) {
        await sectionAdd({ book_id: bookId, chapter_id: data.id, content: '', word_count: 0 });
      }
      setEditKey(false);
      setEditValue(null);
      await getChapterTreeList();
      if (parentId) {
        let temp = [...expandedKeys, parentId];
        setExpandedKeys(temp);

        await newChapterChange(data.id, values.title);
      }
    }
    setLoading(false);
  };

  return (
    <Form layout='vertical' form={form} onFinish={onFinish} initialValues={initValues}>
      <Form.Item
        label='章节标题'
        name='title'
        rules={[{ required: true, message: '请输入章节标题' }]}
        extra='最多30个字符'
      >
        <Input ref={inputRef} autoFocus maxLength={30} placeholder='' allowClear />
      </Form.Item>
      <Form.Item className='editor-form-buttons' wrapperCol={{ offset: 9, span: 16 }}>
        <Space size={20}>
          <Button type='default' disabled={loading} onClick={() => setEditKey(false)}>
            取消
          </Button>
          <Button type='primary' loading={loading} htmlType='submit'>
            确认
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default EditChapterTitle;
