import { useState, useEffect, forwardRef } from 'react'
import { Divider, Input, Space, Button, Form, ColorPicker, Tabs, Select, Row, Col } from 'antd'
import './index.less'
import { addGallery } from '../utils/request'
import { SlateEditor, SlateTransforms, SlateElement } from '@wangeditor/editor'

import { findNodeWithParent, fontSizeList } from '../utils/setting'
import GalleryFormItem from './galleryItem'

const randomOne = Math.random().toString(16).substring(2, 10)
const GalleryModal = (props, ref) => {
  const {
    editor,
    galleryInfo,
    bookId,
    chapterId,
    setGalleryVisible,
    setGalleryInfo,
    selectionSize = 18,
    isOnline = false
  } = props

  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const flexValue = Form.useWatch('flex', form)
  const contentValue = Form.useWatch('content', form)

  const [oldFlex, setOldFlex] = useState(null)
  const [picList, setPicList] = useState([])
  const [themeValue, setThemeValue] = useState('#ab1941')
  const [fontsize, setFontsize] = useState(selectionSize)
  const [initValues, setInitValues] = useState({
    galleryTitle: '',
    flex: 1,
    theme: '#ab1941',
    fontSize: selectionSize || 18
  })

  // 监听图片改变
  useEffect(() => {
    const newGalleryList = []
    // eslint-disable-next-line guard-for-in
    for (let key in contentValue) {
      newGalleryList.push({ ...contentValue[key], key: key })
    }
    setPicList(newGalleryList)
    form.setFieldsValue({ gallery: newGalleryList })
  }, [contentValue])

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

  // tabs
  const initialItems = [
    {
      label: '图 1',
      children: (
        <GalleryFormItem
          form={form}
          galleryInfo={galleryInfo}
          activeKey={randomOne}
          setPicList={setPicList}
          isOnline={isOnline}
        />
      ),
      key: randomOne,
      forceRender: true
    }
  ]
  const [activeKey, setActiveKey] = useState(initialItems[0].key)
  const [items, setItems] = useState(initialItems)

  const onChange = newActiveKey => {
    setActiveKey(newActiveKey)
  }
  const add = () => {
    let newPanes = [...items]
    let index = newPanes.length
    if (index >= 10) return
    const random = Math.random().toString(16).substring(2, 10)
    const newActiveKey = `${random}`
    newPanes.push({
      label: `图 ${index + 1}`,
      children: (
        <GalleryFormItem
          form={form}
          galleryInfo={galleryInfo}
          activeKey={newActiveKey}
          setPicList={setPicList}
          isOnline={isOnline}
        />
      ),
      key: newActiveKey,
      forceRender: true
    })

    newPanes.forEach((item, index) => {
      item.label = `图 ${index + 1}`
    })
    setItems(newPanes)
    setActiveKey(newActiveKey)
  }
  const remove = async targetKey => {
    const tempGallery = picList.filter(item => item.key !== targetKey)
    await setPicList(tempGallery)
    console.log(tempGallery)
    form.setFieldsValue({ gallery: tempGallery })

    let newActiveKey = activeKey
    let lastIndex = -1
    items.forEach((item, i) => {
      if (item.key === targetKey) {
        lastIndex = i - 1
      }
    })
    let newPanes = items.filter(item => item.key !== targetKey)
    if (newPanes.length && newActiveKey === targetKey) {
      if (lastIndex >= 0) {
        newActiveKey = newPanes[lastIndex].key
      } else {
        newActiveKey = newPanes[0].key
      }
    }
    newPanes.forEach((item, index) => {
      item.label = `图 ${index + 1}`
    })

    setItems(newPanes)
    setActiveKey(newActiveKey)
  }
  const onEdit = (targetKey, action) => {
    if (action === 'add') {
      add()
    } else {
      remove(targetKey)
    }
  }

  const [nowRandom, setNowRandom] = useState(null)

  useEffect(() => {
    if (galleryInfo && Object.entries(galleryInfo).length > 0) {
      const { galleryList, random, flex, title, theme = '', fontsize } = galleryInfo

      let galleryArr = []
      try {
        galleryArr = JSON.parse(decodeURI(galleryList))
        if (galleryArr && !(galleryArr instanceof Array)) {
          galleryArr = [{ url: '', title: '', desc: '', key: randomOne }]
        }
      } catch (err) {
        galleryArr = [{ url: '', title: '', desc: '', key: randomOne }]
      }

      setInitValues({
        galleryTitle: title,
        flex: parseInt(flex),
        theme: theme,
        gallery: galleryArr,
        fontSize: fontsize
      })
      form.setFieldsValue({
        galleryTitle: title,
        flex: parseInt(flex),
        theme: theme,
        gallery: galleryArr,
        fontSize: fontsize
      })
      setPicList(galleryArr)
      setThemeValue(theme)
      setOldFlex(parseInt(flex))
      setFontsize(fontsize)

      let newPanel = []
      let activeKey = ''
      galleryArr.forEach((item, index) => {
        const newActiveKey = `${item.key}`
        if (index === 0) {
          activeKey = item.key
        }
        let obj = {
          label: `图 ${index + 1}`,
          children: (
            <GalleryFormItem
              galleryInfo={{ ...galleryInfo, galleryList: encodeURI(JSON.stringify(galleryArr)) }}
              form={form}
              setPicList={setPicList}
              activeKey={newActiveKey}
              isOnline={isOnline}
            />
          ),
          key: newActiveKey,
          forceRender: true
        }
        newPanel.push(obj)
      })
      setItems(newPanel)
      setActiveKey(activeKey)

      setNowRandom(random)
      setGalleryInfo({})
    }
  }, [galleryInfo])

  const onFinish = async values => {
    editor.restoreSelection()
    // setLoading(true);
    const { galleryTitle, flex, gallery, fontSize, theme = '' } = values
    console.log(values)

    if (parseInt(flex) !== 2) {
      // 删除空白的p标签
      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)
        }
      }
    }

    if (nowRandom) {
      let props = {
        title: galleryTitle,
        flex: flex,
        galleryList: encodeURI(JSON.stringify(gallery)),
        random: nowRandom,
        theme,
        fontsize: fontSize || fontsize
      }
      await addGallery({
        book_id: bookId,
        chapter_id: chapterId,
        title: galleryTitle,
        content: JSON.stringify(gallery),
        position: nowRandom
      })

      if (flex === 2) {
        const aPath = findNodeWithParent(editor.children, 'chapterGalleryInline', 'random', nowRandom)
        SlateTransforms.setNodes(editor, props, { at: aPath.reverse() })
      } else {
        const aPath = findNodeWithParent(editor.children, 'chapterGallery', 'random', nowRandom)
        SlateTransforms.setNodes(editor, props, { at: aPath.reverse() })
      }

      form.resetFields()
      setGalleryVisible(false)
      setOldFlex(null)

      setLoading(false)
      return false
    }

    let random = Math.random().toString(10).substring(2, 10)
    await addGallery({
      book_id: bookId,
      chapter_id: chapterId,
      title: galleryTitle,
      content: JSON.stringify(gallery),
      position: random
    })
    if (parseInt(flex) === 2) {
      editor.insertNode({
        type: 'chapterGalleryInline',
        title: galleryTitle,
        galleryList: encodeURI(JSON.stringify(gallery)),
        random: random,
        theme,
        flex: flex,
        fontsize: fontSize,
        children: [{ text: '' }]
      })
    } else {
      editor.insertNode({
        type: 'chapterGallery',
        title: galleryTitle,
        galleryList: encodeURI(JSON.stringify(gallery)),
        random: random,
        theme,
        flex: flex,
        fontsize: fontSize,
        children: [{ text: '' }]
      })
    }

    form.resetFields()
    setOldFlex(null)
    setGalleryVisible(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="flex" rules={[{ required: true, message: '请选择展示模式' }]}>
            <Select>
              <Select.Option disabled={oldFlex && oldFlex === 2} value={1}>
                两图并列画廊
              </Select.Option>
              <Select.Option disabled={oldFlex && oldFlex !== 2} value={2}>
                图文内画廊
              </Select.Option>
              <Select.Option disabled={oldFlex && oldFlex === 2} value={3}>
                单张图居中画廊
              </Select.Option>
              <Select.Option disabled={oldFlex && oldFlex === 2} value={4}>
                全部显示画廊
              </Select.Option>
            </Select>
          </Form.Item>
          {flexValue === 2 && (
            <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: parseInt(flexValue) === 2 ? true : false,
                          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>
          )}

          {flexValue !== 2 && (
            <Form.Item
              label="画廊标题"
              name="galleryTitle"
              rules={[{ required: true, message: '请输入画廊标题' }]}
              extra="最多输入100字">
              <Input maxLength={100} placeholder="" allowClear />
            </Form.Item>
          )}
          <Form.Item label="图片" name="gallery" rules={[{ required: true, message: '请上传画廊图片' }]}>
            <Tabs type="editable-card" onChange={onChange} activeKey={activeKey} onEdit={onEdit} items={items}></Tabs>
          </Form.Item>
          <Form.Item className="editor-form-buttons">
            <Space>
              <Button type="default" onClick={() => setGalleryVisible(false)}>
                取消
              </Button>
              <Button type="primary" loading={loading} htmlType="submit">
                {nowRandom ? '更新' : '插入'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default forwardRef(GalleryModal)
