import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react'
import { Modal, Divider, ColorPicker, Input, Space, Button, Form, Spin, message, Select, Row, Col } from 'antd'
import { SlateTransforms, SlateEditor, DomEditor, SlateElement } from '@wangeditor/editor'

import { fontSizeList } from '../utils/setting'
import EditorSimple from '@/common/editor-simple'
import './index.less'
import { addExpandRead, expandReadInfo } from '../utils/request'

const ExpandModal = (props, ref) => {
  const {
    editor,
    ossClient,
    bookId,
    chapterId,
    setExpandVisible,
    setExpandInfo,
    expandInfo,
    selectionSize = 18
  } = props

  const [form] = Form.useForm()
  const flexValue = Form.useWatch('flex', form)
  const [loadLoading, setLoadLoading] = useState(false)
  const [content, setContent] = useState('')
  const [themeValue, setThemeValue] = useState('#ab1941')
  const [oldFlex, setOldFlex] = useState(null)
  const [initvalues, setInitValue] = useState({
    flex: 1,
    name: '',
    title: '',
    content: '',
    theme: '#ab1941',
    fontSize: selectionSize || 18
  })
  const [nowRandom, setNowRandom] = useState(null)
  // const [fontsize, setFontsize] = useState(selectionSize);

  const getExpandInfo = async random => {
    setLoadLoading(true)
    const data = await expandReadInfo({
      book_id: bookId,
      chapter_id: chapterId,
      position: nowRandom || random
    })
    if (data) {
      setContent(data.content)
      // setInitValue({ ...data });
      // form.setFieldsValue({ ...data });
    }
    setLoadLoading(false)
  }

  const textColorChange = value => {
    const hex = typeof value === 'string' ? value : value?.toHexString()
    setThemeValue(hex)
    form.setFieldsValue({ theme: hex })
  }

  useEffect(() => {
    if (Object.entries(expandInfo).length > 0) {
      ;(async () => {
        setLoadLoading(true)
        let obj = { ...expandInfo, flex: parseInt(expandInfo.flex), fontSize: expandInfo.fontsize }
        setThemeValue(expandInfo.theme)
        setOldFlex(parseInt(expandInfo.flex))
        setInitValue(obj)
        form.setFieldsValue(obj)
        setNowRandom(expandInfo.random)
        await getExpandInfo(expandInfo.random)
        setExpandInfo({})
        // setFontsize(expandInfo.fontsize);
        setLoadLoading(false)
      })()
    }
  }, [expandInfo])

  const removeInlineElement = (editor, type) => {
    const { selection } = editor
    if (!selection) return
    const [inlineNode] = SlateEditor.nodes(editor, {
      match: node => SlateElement.isElement(node) && node.type === type
    })
    console.log('inlineNode', inlineNode)
    if (!inlineNode) return
    const [parent] = SlateEditor.parent(editor, inlineNode[1])
    if (!parent || SlateElement.isElement(parent)) {
      Transforms.removeNodes(editor, { match: node => node.type === type })
    } else {
      Transforms.removeNodes(editor, { at: inlineNode[1] })
    }
  }

  const onFinish = async values => {
    editor.restoreSelection()
    if (parseInt(values.flex) === 1) {
      const nodeEntries = SlateEditor.nodes(editor, {
        match: node => {
          // JS syntax
          if (SlateElement.isElement(node)) {
            if (node.type === 'paragraph') {
              return true // 匹配 paragraph
            }
          }
          return false
        },
        universal: true
      })
      for (let nodeEntry of nodeEntries) {
        const [node, path] = nodeEntry
        if (node.children[0].text === '') {
          SlateTransforms.removeNodes(editor)
        }
      }
    }
    setLoadLoading(true)

    const { flex, theme, fontSize, ...other } = values
    if (nowRandom) {
      let props = {
        flex: parseInt(values.flex),
        name: values.name,
        title: values.title,
        random: nowRandom,
        theme: values.theme,
        fontsize: values.fontSize
      }

      if (parseInt(oldFlex) !== flex) {
        SlateTransforms.removeNodes(editor)
        if (parseInt(values.flex) === 1) {
          editor.insertNode({
            type: 'chapterExpandRead',
            ...props,
            children: [{ text: '' }]
          })
        } else {
          editor.insertNode({
            type: 'chapterExpandReadSimple',
            ...props,
            children: [{ text: '' }]
          })
        }
      } else {
        if (parseInt(flex) === 2) {
          editor.move(1)
          editor.deleteBackward()

          editor.insertNode({
            type: 'chapterExpandReadSimple',
            ...props,
            children: [{ text: '' }]
          })

          // const nodeEntries = SlateEditor.nodes(editor, {
          //   match: (node) => {
          //     if (SlateElement.isElement(node)) {
          //       console.log(node);
          //       if (node.type === 'chapterExpandReadSimple') {
          //         return true;
          //       }
          //     }
          //     return false;
          //   },
          //   // universal: true,
          //   mode: 'all',
          // });
          // console.log(nodeEntries.next());
          // // 遍历匹配的节点迭代器，获取匹配的节点路径
          // for (let nodeEntry of nodeEntries) {
          //   const [node, path] = nodeEntry;
          //   if (node.random === nowRandom) {
          //     SlateTransforms.setNodes(editor, { ...node, ...props }, { at: path });
          //   }
          // }
        } else {
          const nodeEntries = SlateEditor.nodes(editor, {
            match: node => {
              // JS syntax
              if (SlateElement.isElement(node)) {
                if (node.type === 'chapterExpandRead') {
                  return true // 匹配 chapterToolTip
                }
              }
              return false
            },
            universal: true
          })
          // 遍历匹配的节点迭代器，获取匹配的节点路径
          for (let nodeEntry of nodeEntries) {
            const [node, path] = nodeEntry
            if (node.random === nowRandom) {
              SlateTransforms.setNodes(editor, props, { at: path })
            }
          }
        }
      }

      const data = await addExpandRead({
        book_id: bookId,
        chapter_id: chapterId,
        position: nowRandom,
        type: flex,
        ...other
      })
      setNowRandom(null)
      setExpandVisible(false)
      setLoadLoading(false)
      return false
    }

    let random = Math.random().toString(10).substring(2, 10)
    const data = await addExpandRead({
      book_id: bookId,
      chapter_id: chapterId,
      position: random,
      type: flex,
      ...other
    })

    if (parseInt(values.flex) === 1) {
      editor.insertNode({
        type: 'chapterExpandRead',
        flex: parseInt(values.flex),
        name: values.name,
        title: values.title,
        random: random,
        theme: values.theme,
        fontsize: values.fontSize || selectionSize,
        children: [{ text: '' }]
      })
    } else {
      editor.insertNode({
        type: 'chapterExpandReadSimple',
        flex: parseInt(values.flex),
        name: values.name,
        title: values.title,
        random: random,
        theme: values.theme,
        fontsize: values.fontSize || selectionSize,
        children: [{ text: '' }]
      })
    }

    setNowRandom(null)
    setExpandVisible(false)
    setLoadLoading(false)
  }

  return (
    <div>
      <Divider />
      <div className="editor-content-form">
        <Form layout="vertical" name="validate_other" form={form} onFinish={onFinish} initialValues={initvalues}>
          <Form.Item label="扩展类型" name="flex" rules={[{ required: true, message: '请选择扩展类型' }]}>
            <Select disabled={oldFlex > 0 ? true : false}>
              <Select.Option value={1}>独立扩展</Select.Option>
              <Select.Option value={2}>行内扩展</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="扩展名称"
            name="name"
            rules={[{ required: true, message: '请输入扩展名称' }]}
            extra="最多输入100字">
            <Input maxLength={100} placeholder="" allowClear />
          </Form.Item>
          {flexValue === 1 && (
            <Form.Item
              label="扩展标题"
              name="title"
              rules={[
                { required: flexValue === 1 ? true : false, message: '请输入扩展标题' },
                { max: 100, message: '最多输入100个字符！' }
              ]}
              extra="最多输入100字">
              <Input.TextArea maxLength={100} autoSize={{ minRows: 2, maxRows: 3 }} placeholder="" allowClear />
            </Form.Item>
          )}

          {flexValue === 1 ? (
            <Form.Item>
              <div className="justcontent-color-inline">
                <Form.Item
                  label="扩展主题色"
                  name="theme"
                  className="flex-max"
                  rules={[
                    { required: true, message: '请选择颜色' },
                    { pattern: /^#[0-9A-Fa-f]{6}$/i, message: '请输入正确的16进制色值' }
                  ]}>
                  <Input placeholder="" allowClear />
                </Form.Item>
                <Form.Item label={` `}>
                  <ColorPicker
                    disabledAlpha
                    value={themeValue}
                    defaultValue={themeValue}
                    format="hex"
                    onChange={textColorChange}
                  />
                </Form.Item>
              </div>
            </Form.Item>
          ) : (
            <Form.Item>
              <Row gutter={20}>
                <Col span={12}>
                  <Form.Item label="字号" name="fontSize">
                    <Select>
                      {fontSizeList.map((item, index) => {
                        return (
                          <Select.Option value={item.value} key={index}>
                            {item.name}
                          </Select.Option>
                        )
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <div className="justcontent-color-inline">
                    <Form.Item
                      label="扩展主题色"
                      name="theme"
                      className="flex-max"
                      rules={[
                        { required: true, message: '请选择颜色' },
                        { pattern: /^#[0-9A-Fa-f]{6}$/i, message: '请输入正确的16进制色值' }
                      ]}>
                      <Input placeholder="" allowClear />
                    </Form.Item>
                    <Form.Item label={` `}>
                      <ColorPicker
                        disabledAlpha
                        value={themeValue}
                        defaultValue={themeValue}
                        format="hex"
                        onChange={textColorChange}
                      />
                    </Form.Item>
                  </div>
                </Col>
              </Row>
            </Form.Item>
          )}
          <Form.Item label="扩展内容" name="content">
            <EditorSimple form={form} fieldName={'content'} content={content} loadLoading={loadLoading} />
          </Form.Item>
          <Form.Item className="editor-form-buttons">
            <Space>
              <Button type="default" onClick={() => setExpandVisible(false)}>
                取消
              </Button>
              <Button type="primary" loadLoading={loadLoading} htmlType="submit">
                {nowRandom ? '更新' : '插入'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default forwardRef(ExpandModal)
