import { useState, useEffect, forwardRef } from 'react'
import { Divider, Input, Space, Button, Form, message, Select, Cascader, ColorPicker, Row, Col } from 'antd'
import { SlateTransforms, SlateEditor, SlateElement } from '@wangeditor/editor'
import './index.less'
import { fontSizeList } from '../utils/setting'
import { findTreeElementByKey } from '@/utils/common'

const LinkModal = (props, ref) => {
  const { editor, setLinkVisible, setLinkInfo, linkInfo, gData, selectionSize = 18 } = props

  const [form] = Form.useForm()
  const linktype = Form.useWatch('linktype', form)
  const [loading, setLoading] = useState(false)
  const [themeValue, setThemeValue] = useState('#ab1941')
  const [initvalues, setInitValue] = useState({
    linktype: 1,
    title: '',
    link: '',
    theme: '#ab1941',
    fontSize: selectionSize || 18
  })
  const [nowRandom, setNowRandom] = useState(null)

  const linkChange = value => {
    if (value === 2) {
      form.setFieldsValue({ chapters: [] })
    }
  }

  useEffect(() => {
    if (editor.getSelectionText()) {
      setInitValue({ ...initvalues, title: editor.getSelectionText() })
      form.setFieldsValue({ title: editor.getSelectionText() })
    }
  }, [])

  useEffect(() => {
    if (Object.entries(linkInfo).length > 0) {
      let chapters = []
      try {
        chapters = linkInfo.chapters.split(',').map(item => parseInt(item))
      } catch (e) {
        chapters = []
      }

      let obj = { ...linkInfo, linktype: parseInt(linkInfo.linktype), chapters, fontSize: parseInt(linkInfo.fontsize) }
      setInitValue(obj)
      setThemeValue(linkInfo.theme)
      form.setFieldsValue(obj)
      setNowRandom(linkInfo.random)
      // setFontsize(linkInfo.fontsize);
      setLinkInfo({})
    }
  }, [linkInfo])

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

  const onFinish = async values => {
    editor.restoreSelection()

    let child = {}
    if (values.linktype === 2) {
      const last = values.chapters[values.chapters.length - 1]
      child = findTreeElementByKey(gData, 'key', last)
      if (child.children && child.children.length) {
        form.setFields([{ chapters: { errors: ['请选择正确的子节！'] } }])
        return false
      }
    }

    setLoading(true)
    const { link } = values
    let newLink = ''
    if (link) {
      if (!/^https*:\/\//.test(link)) {
        newLink = `http://${link}`
      } else {
        newLink = link
      }
    }

    if (nowRandom) {
      const props = {
        ...values,
        link: newLink,
        random: nowRandom,
        title: parseInt(values.linktype) === 1 ? values.title : child.title,
        chapters: values.chapters instanceof Array ? values.chapters.join(',') : '',
        fontsize: values.fontSize
      }
      const nodeEntries = SlateEditor.nodes(editor, {
        match: node => {
          // JS syntax
          if (SlateElement.isElement(node)) {
            if (node.type === 'chapterLink') {
              return true
            }
          }
          return false
        },
        universal: true
      })
      // 遍历匹配的节点迭代器，获取匹配的节点路径
      if (nodeEntries === null) {
        console.log('当前未选中的 chapterLink')
      } else {
        for (let nodeEntry of nodeEntries) {
          const [node, path] = nodeEntry
          console.log('linkedit', node)
          if (node.random === nowRandom) {
            SlateTransforms.setNodes(editor, props, { at: path })
          }
        }
      }
      message.success('更新成功!')
      setLinkVisible(false)
      setNowRandom(null)
      setLoading(false)
      return false
    }

    let random = Math.random().toString(10).substring(2, 10)
    editor.insertNode({
      type: 'chapterLink',
      title: parseInt(values.linktype) === 1 ? values.title : child.title,
      linktype: parseInt(values.linktype),
      link: newLink,
      theme: values.theme,
      chapters: values.chapters instanceof Array ? values.chapters.join(',') : '',
      random,
      fontsize: values.fontSize,
      children: [{ text: '' }]
    })
    message.success('添加成功!')
    setNowRandom(null)
    setLinkVisible(false)
    setLoading(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="linktype" rules={[{ required: true, message: '请选择链接类型' }]}>
            <Select onChange={linkChange}>
              <Select.Option value={1}>普通链接</Select.Option>
              <Select.Option value={2}>章节链接</Select.Option>
            </Select>
          </Form.Item>
          {linktype === 1 && (
            <>
              <Form.Item
                label="链接标题"
                name="title"
                rules={[{ required: true, message: '请输入链接标题' }]}
                extra="最多输入100字">
                <Input maxLength={100} placeholder="" allowClear />
              </Form.Item>
              <Form.Item
                label="链接"
                name="link"
                rules={[
                  { required: true, message: '请输入链接地址' },
                  { pattern: /^https*:\/\//gi, message: '链接地址需要http(s)://开头' }
                ]}>
                <Input placeholder="" allowClear />
              </Form.Item>
            </>
          )}

          {linktype === 2 && (
            <>
              <Form.Item label="子节" name="chapters" rules={[{ required: true, message: '请选择子节' }]}>
                <Cascader
                  options={gData}
                  fieldNames={{ label: 'title', value: 'key', children: 'children' }}
                  placeholder="请选择子节"
                  allowClear
                />
              </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 className="editor-form-buttons">
            <Space>
              <Button type="primary" loading={loading} htmlType="submit">
                {nowRandom ? '更新' : '插入'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default forwardRef(LinkModal)
