import React, { useState, useEffect, forwardRef, useImperativeHandle, useRef } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { Modal, Row, Col, Divider, Upload, Input, Space, Button, Form, Spin, message, ColorPicker } from 'antd'
import { CloseOutlined } from '@ant-design/icons'
import { setPracticeRandom } from '@/store/modules/editor'
import { DomEditor, SlateEditor, SlateTransforms, SlateElement } from '@wangeditor/editor'

import ListTopic from './components/list'
import CustomerTopic from './components/customer'
import InsertTopic from './components/insert'
import iconPractice from '@/assets/images/icon_practice.png'
import iconClose from '@/assets/images/icon_chapter_close.png'
import { getChapterTopic } from '../utils/request'
import { bookNameList } from './request'

import '../utils/iconfont'
import './index.less'

const PracticeSettingModal = forwardRef((props, ref) => {
  const { editor, chapterId, bookId, closePanel } = props
  const dispatch = useDispatch()
  const { practiceRandom, practiceTitle, practiceTheme } = useSelector(state => state.editor)
  const [themeValue, setThemeValue] = useState(practiceTheme)

  const listRef = useRef()
  const customerTopicRef = useRef()

  const [customerType, setCustomerType] = useState('')
  const [practiceTitleVisible, setPracticeTitleVisible] = useState(false) // 是否显示可编辑
  const [practiceTitleValue, setPracticeTitleValue] = useState(practiceTitle) // input 标题
  const [practiceStatus, setPracticeStatus] = useState(false) // 手动还是自动

  // 右边勾选的列表
  const [chooseList, setChooseList] = useState([])
  // 线上的题库
  const [onlineList, setOnloneList] = useState([])
  // 左边插入的列表
  const [insertList, setInsertList] = useState([])
  const [bookNameIdData, setbookNameIdData] = useState([])
  const getbookNameList = async () => {
    const res = await bookNameList({})
    setbookNameIdData(res)
  }
  useEffect(() => {
    getbookNameList()
  }, [])

  const textColorChange = value => {
    const hex = typeof value === 'string' ? value : value?.toHexString()
    setThemeValue(hex)
  }
  // 获取
  const getTopicList = async () => {
    const data = await getChapterTopic({
      position: practiceRandom,
      book_id: bookId,
      chapter_id: chapterId
    })

    if (data && data.length > 0) {
      let dataSource = []
      data.forEach((item, index) => {
        dataSource.push({ ...item, choose_id: item.question_id })
      })
      setOnloneList(dataSource)

      if (insertList.length === 0) {
        setInsertList(dataSource)
      } else {
        const tempChoose = [...insertList]
        const ids = tempChoose.map(item => parseInt(item.choose_id))
        dataSource.forEach(item => {
          if (!ids.includes(parseInt(item.choose_id))) {
            tempChoose.push(item)
          }
        })
        setInsertList(tempChoose)
      }
      if (chooseList.length === 0) {
        setChooseList(dataSource)
      } else {
        const tempChoose = [...chooseList]
        const ids = tempChoose.map(item => parseInt(item.choose_id))
        dataSource.forEach(item => {
          if (!ids.includes(parseInt(item.choose_id))) {
            tempChoose.push(item)
          }
        })
        setChooseList(tempChoose)
      }
    }
  }
  useEffect(() => {
    if (bookId && chapterId && practiceRandom) {
      getTopicList()
    }
  }, [bookId, chapterId, practiceRandom])

  // 设置标题
  const changePracticeTitle = () => {
    setPracticeTitleValue(practiceTitle)
    setPracticeTitleVisible(true)
  }
  const submitPracticeTitle = () => {
    editor.restoreSelection()

    const nodeEntries = SlateEditor.nodes(editor, {
      match: node => {
        // JS syntax
        if (SlateElement.isElement(node)) {
          if (node.type === 'chapterPractice') {
            return true // 匹配 chapterHeader
          }
        }
        return false
      },
      universal: true
    })

    if (nodeEntries) {
      for (let nodeEntry of nodeEntries) {
        const [node, path] = nodeEntry
        // console.log('选中了 chapterHeader 节点', node);
        // console.log('节点 path 是', path);
        if (node.practiceNum === practiceRandom) {
          SlateTransforms.setNodes(editor, { ...node, title: practiceTitleValue, theme: themeValue }, { at: path })
          dispatch(setPracticeRandom({ practiceNum: node.practiceNum, practiceTitle: practiceTitleValue }))
          setPracticeTitleVisible(false)
          return false
        }
      }
    }
    return
  }

  // 添加题目到左边
  const addTopicList = () => {
    if (chooseList.length === 0) {
      message.error('您还没有勾选题目！')
      return
    }

    const tempChoose = [...insertList]
    const ids = tempChoose.map(item => parseInt(item.choose_id))
    chooseList.forEach(item => {
      if (!ids.includes(parseInt(item.choose_id))) {
        tempChoose.push(item)
      }
    })
    setInsertList(tempChoose)
  }

  const getTopList = () => {
    listRef.current.setPage(1)
    listRef.current.getTopicTypeList()
  }

  return (
    <div>
      <Row gutter="20" className="practice-topic-row">
        <Col span={12} className="common practice-left">
          <div className="practice-header">
            <div className="practice-l-img">
              {/* <img src={iconPractice} alt='' /> */}
              <svg className="svg-icon" aria-hidden="true">
                <use xlinkHref="#icon-writing"></use>
              </svg>
            </div>
            <div className="practice-l-title">
              {!practiceTitleVisible && (
                <h2 onClick={changePracticeTitle} className="title">
                  <ColorPicker value={themeValue} defaultValue={themeValue} size="small" disabled />
                  <span className="titles">{practiceTitle}</span>
                  <span className="click">（可点击编辑）</span>
                </h2>
              )}
              {practiceTitleVisible && (
                <div style={{ marginTop: 2 }}>
                  <Space>
                    <Input value={practiceTitleValue} onChange={e => setPracticeTitleValue(e.target.value)} />
                    <div style={{ marginTop: 2 }}>
                      <ColorPicker
                        disabledAlpha
                        value={themeValue}
                        defaultValue={themeValue}
                        format="hex"
                        onChange={textColorChange}
                        showText
                      />
                    </div>
                    <Button type="primary" onClick={submitPracticeTitle}>
                      确定
                    </Button>
                    <Button type="default" onClick={() => setPracticeTitleVisible(false)}>
                      取消
                    </Button>
                  </Space>
                </div>
              )}
            </div>
          </div>
          <div className="practice-topic-list">
            <InsertTopic
              insertList={insertList}
              setInsertList={setInsertList}
              chooseList={chooseList}
              setChooseList={setChooseList}
              practiceRandom={practiceRandom}
              chapterId={chapterId}
              bookId={bookId}
              closePanel={closePanel}
            />
          </div>
        </Col>
        <Col span={12} className="common practice-right">
          <div className="practice-header right">
            <div style={{ marginTop: 5 }}>
              <Button type="default" onClick={() => setPracticeStatus(!practiceStatus)}>
                {practiceStatus ? '自动添加' : '手动添加'}
              </Button>
            </div>
            <Button type="link" icon={<CloseOutlined style={{ color: '#b83956' }} />} onClick={closePanel}></Button>
          </div>
          <div className="practice-topic-list">
            {practiceStatus ? (
              <CustomerTopic
                ref={customerTopicRef}
                setPracticeStatus={setPracticeStatus}
                getTopList={getTopList}
                bookNameIdData={bookNameIdData}
                bookId={bookId}
                setCustomerType={setCustomerType}
              />
            ) : (
              <ListTopic
                ref={listRef}
                chooseList={chooseList}
                setChooseList={setChooseList}
                addTopicList={addTopicList}
                practiceStatus={practiceStatus}
                bookNameIdData={bookNameIdData}
                bookId={bookId}
                customerType={customerType}
              />
            )}
          </div>
        </Col>
      </Row>
    </div>
  )
})

export default PracticeSettingModal
