import { useState, useEffect, forwardRef, useImperativeHandle } from 'react'
import { Form, Space, Input, Select, Button, Row, Col, Checkbox } from 'antd'
import { MinusOutlined, PlusOutlined } from '@ant-design/icons'

import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { DomEditor } from '@wangeditor/editor'

import { questionAdd, questionAddType, questionEdit } from '@/pages/books/question-bank/request'
import QuestionEditr from '@/pages/books/question-bank/questionEditr'
import './index.less'
import dayjs from 'dayjs'
import AliOSS from 'ali-oss'
import { getAliOSSSTSToken } from '@/pages/setting/help/addedit/requet'

const CustomerTopic = (props, ref) => {
  const { topicData, isadd, init, getTypeList, typeDate, setShowModal, bookIdList, typeId } = props
  // oss
  const [ossClient, setOssClient] = useState(null) // oss 操作
  const [STSToken, setSTSToken] = useState(null) // oss 过期设置
  let ossClientTemp
  const getStsAuthToken = async () => {
    const data = await getAliOSSSTSToken()
    if (data) {
      window.sessionStorage.setItem('sts', JSON.stringify(data))
      setSTSToken(data)
      ossClientTemp = await new AliOSS({
        accessKeyId: data.AccessKeyId,
        accessKeySecret: data.AccessKeySecret,
        stsToken: data.SecurityToken,
        endpoint: data.endpoint,
        bucket: 'zxts-book-file',

        timeout: 180000,
        refreshSTSToken: async () => {
          const info = await getAliOSSSTSToken()
          return {
            AccessKeyId: info.AccessKeyId,
            AccessKeySecret: info.AccessKeySecret,
            SecurityToken: info.SecurityToken
          }
        },
        refreshSTSTokenInterval: 14 * 60 * 1000
      })
      setOssClient(ossClientTemp)
    }
  }

  useEffect(() => {
    ;(async () => {
      await getStsAuthToken()
    })()
  }, [])

  useImperativeHandle(ref, () => {
    return {}
  })

  const [form] = Form.useForm()
  const questionType = Form.useWatch('question_style', form)
  // 题干名称的编辑器实例
  const [titlesEditor, setTitlesEditor] = useState(null)
  const [quesList, setQuesList] = useState([])
  const [initialValues, setInitialValues] = useState({
    titles: '',
    type_id: null,
    question_style: '',
    analysis: '',
    answers: '',
    question_list: [],
    book_id: ''
  })

  const [selectedTypeId, setSelectedTypeId] = useState([])

  useEffect(() => {
    const getTypeNameById = id => {
      const selectedType = props.typeDate.find(item => item.id === id)
      return selectedType ? selectedType.typename : ''
    }

    const matchedTypename = getTypeNameById(typeId)
    setSelectedTypeId(matchedTypename)
  }, [props.typeDate, typeId])

  useEffect(() => {
    let obj = {
      titles: '',
      type_id: null,
      question_style: '',
      analysis: '',
      answers: '',
      question_list: [],
      book_id: ''
    }
    if (!isadd && Object.entries(topicData)) {
      obj = {
        ...topicData
      }
      setQuestionStyle(obj.question_style)
      if (topicData.question_style === 4 || topicData.question_style === 5) {
        setedierVal(topicData.answers)

        setQuesList([])
      } else {
        if (topicData.question_list && topicData.question_list.length) {
          try {
            obj.question_list = JSON.parse(topicData.question_list)
            setQuesList(JSON.parse(topicData.question_list))
          } catch (e) {
            obj.question_list = []
            setQuesList([])
          }
        } else {
          obj.question_list = []
          setQuesList([])
        }
      }
      setInitialValues({ ...obj })
      form.setFieldsValue({ ...obj })
    } else {
      setInitialValues(obj)
      form.setFieldsValue({ ...obj })
    }
  }, [topicData, isadd])

  // 显示不同类型的选项函数
  const [edierVal, setedierVal] = useState('')
  // 是否显示选项
  const [showAddClass, setShowAddClass] = useState(false)
  const [addClassVal, setAddClassVal] = useState('') // 添加分类
  const [questionStyle, setQuestionStyle] = useState('')

  // 分类
  const sureFn = async () => {
    const bool = await questionAddType({ typename: addClassVal })
    if (bool) {
      await getTypeList()
      form.setFieldsValue({ type_id: bool.type_id })
      setInitialValues({ ...initialValues, type_id: [bool.type_id] })
      setAddClassVal('')
      setShowAddClass(false)
    }
  }

  // 工具栏配置
  const toolbarConfig = {}
  toolbarConfig.toolbarKeys = ['uploadImage']
  // 编辑器配置
  const editorConfig = {
    // JS 语法
    placeholder: '请输入内容...',
    hoverbarKeys: {
      text: {
        menuKeys: []
      }
    },
    MENU_CONF: {
      // 配置默认字号
      // 配置上传图片
      uploadImage: {
        timeout: 5 * 1000, // 5s

        fieldName: 'image',
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: 'Bearer ' + localStorage.getItem('token')
        },
        maxFileSize: 10 * 1024 * 1024, // 10M

        base64LimitSize: 5 * 1024, // 5kb 以下插入 base64
        customUpload: async (file, insertFn) => {
          if (!ossClient) {
            console.error('ossClient还未初始化', ossClient)
            return false
          }
          const fileExt = file.name.substring(file.name.lastIndexOf('.'))
          const fileName = `ad-${dayjs().valueOf()}-${Math.random().toString(36).substring(2)}${fileExt}`
          const filePath = `${dayjs().format('YYYY/MM/DD')}/${fileName}`
          const result = await ossClient.put(filePath, file)

          console.log('result', result)
          insertFn(result.url, '题库图片')
        }
      }
    },
    customPaste: (editor, event) => {
      // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
      const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
      // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

      // 异步
      setTimeout(() => {
        editor.insertText(text)
      }, 500)

      // 阻止默认的粘贴行为
      event.preventDefault()
      return false
    }
  }

  // 及时销毁 editor ，重要！
  useEffect(() => {
    if (titlesEditor !== null) {
      const toolbar = DomEditor.getToolbar(titlesEditor)
    }

    return () => {
      if (titlesEditor === null) return
      titlesEditor.destroy()
      setTitlesEditor(null)
    }
  }, [titlesEditor])

  const submitForm = async obj => {
    let ilen = 0
    let obj2 = { ...obj }
    if ([1, 2, 3].includes(parseInt(obj.question_style))) {
      obj.question_list.forEach((item, index) => {
        if (item.correct && item.correct === true) {
          ilen++
        }
      })

      if ([1, 3].includes(parseInt(obj.question_style))) {
        if (ilen > 1 || ilen === 0) {
          form.setFields([
            {
              name: ['question_list', obj.question_list.length - 1, 'correct'],
              errors: [`${parseInt(obj.question_style) === 3 ? '判断题' : '单选题'}有且仅有一个正确答案！`]
            }
          ])
          return false
        } else {
          form.setFields([{ name: ['question_list', obj.question_list.length - 1, 'correct'], errors: [''] }])
        }
      } else {
        if (ilen <= 1) {
          form.setFields([
            {
              name: ['question_list', obj.question_list.length - 1, 'correct'],
              errors: ['多选题需要2个及以上正确答案！']
            }
          ])
          return false
        } else {
          form.setFields([{ name: ['question_list', obj.question_list.length - 1, 'correct'], errors: [''] }])
        }
      }

      obj2['question_list'] = JSON.stringify(quesList)
    } else {
      obj2['answers'] = edierVal
    }

    setShowAddClass(true)
    let bool = null
    if (isadd) {
      bool = await questionAdd({
        ...obj2
      })
    } else {
      bool = await questionEdit({
        ...obj2,
        id: topicData.id
      })
    }

    setShowAddClass(false)
    if (!bool) return
    setShowModal(false)
    init()
  }
  // 校验
  const vaildaterHtml = (_, value) => {
    if (value === '<p><br></p>') {
      return Promise.reject('问题内容不能为空')
    } else if (!value.trim()) {
      return Promise.reject(new Error('请输入正确的内容'))
    } else {
      return Promise.resolve()
    }
  }

  return (
    <div className="practice_customer">
      <Form
        form={form}
        initialValues={initialValues}
        onFinish={submitForm}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 19 }}>
        <Form.Item name="book_id" label="书籍名称" rules={[{ required: true, message: '请选择书籍名称' }]}>
          <Select
            style={{ width: 260 }}
            placeholder="请选择书籍名称"
            showSearch //下拉框出现搜素,并可以输入
            optionFilterProp="children" // 使搜索匹配子节点的文本内容
          >
            {bookIdList &&
              bookIdList.length &&
              bookIdList.map((item, index) => (
                <Select.Option key={index} value={item.book_id} data={item}>
                  {item.name}
                </Select.Option>
              ))}
          </Select>
        </Form.Item>
        <Form.Item name="question_style" label="题目类型" rules={[{ required: true, message: '请选择题目类型' }]}>
          <Select
            onChange={ev => {
              setQuestionStyle(ev)
            }}
            style={{ width: 260 }}
            placeholder="请选择题目类型">
            <Select.Option value={1}>单选题</Select.Option>
            <Select.Option value={2}>多选题</Select.Option>
            <Select.Option value={3}>判断题</Select.Option>
            <Select.Option value={4}>填空题</Select.Option>
            <Select.Option value={5}>简答题</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="题目分类" name="type_id" rules={[{ required: true, message: '请选择题目分类' }]}>
          {!showAddClass ? (
            <>
              <Select
                onChange={ev => {
                  form.setFieldValue('type_id', ev)

                  setSelectedTypeId(ev)
                }}
                style={{ width: 220 }}
                placeholder="请选择题目分类"
                value={selectedTypeId}>
                {typeDate &&
                  typeDate.length &&
                  typeDate.map(item => (
                    <Select.Option key={item.id} value={item.id}>
                      {item.typename}
                    </Select.Option>
                  ))}
              </Select>
              <Button
                onClick={() => {
                  setShowAddClass(true)
                  form.setFieldsValue({ type_id: '' })
                }}
                type="link"
                style={{ textDecoration: 'underline', color: '#1672EC' }}>
                添加分类
              </Button>
            </>
          ) : (
            <>
              <Input
                style={{ width: 200 }}
                value={addClassVal}
                onChange={e => setAddClassVal(e.target.value)}
                autoComplete="off"
                placeholder="请输入题目分类"></Input>
              <Space>
                <Button onClick={sureFn} type="link" style={{ textDecoration: 'underline', color: '#1672EC' }}>
                  添加
                </Button>
                <Button
                  type="link"
                  onClick={() => setShowAddClass(false)}
                  style={{ textDecoration: 'underline', color: '#AA1941', marginLeft: -30 }}>
                  取消
                </Button>
              </Space>
            </>
          )}
        </Form.Item>
        <Form.Item
          name="titles"
          label="题干名称"
          rules={[
            { required: true, message: '请输入题干名称' },
            { validator: vaildaterHtml, validateTrigger: 'onChange' }
          ]}
          extra={questionType === 4 ? '请在需要填空的位置使用2个或以上的下划线进行区分！' : ''}>
          <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
            <Toolbar
              editor={titlesEditor}
              defaultConfig={toolbarConfig}
              mode="default"
              style={{ borderBottom: '1px solid #ccc' }}
            />
            {ossClient && (
              <Editor
                defaultConfig={editorConfig}
                value={initialValues.titles}
                onCreated={setTitlesEditor}
                onChange={editor => {
                  form.setFieldValue('titles', editor.getHtml())
                }}
                config={{
                  uploadImgServer: 'your_upload_server_address'
                }}
                mode="default"
                style={{ height: '200px', overflowY: 'hidden' }}
              />
            )}
          </div>
        </Form.Item>
        <Form.Item name="analysis" label="题目解析">
          <Input.TextArea
            placeholder="请输入题目解析"
            autoSize={{
              minRows: 5,
              maxRows: 8
            }}
            name="analysis"
          />
        </Form.Item>

        {(questionStyle === 1 || questionStyle === 2 || questionStyle === 3) && (
          <Form.List name="question_list">
            {(fields, { add, remove }) => (
              <Form.Item label="题目选项">
                {fields.map(({ key, name, ...restField }, index) => (
                  <Row gutter={4} key={key}>
                    <Col span={14} className="form_inside-out">
                      <Form.Item className="inside-it">
                        <QuestionEditr
                          editorValue={quesList && quesList[index] && quesList[index].option}
                          quesList={quesList}
                          setQuesList={setQuesList}
                          index={index}
                          form={form}
                        />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'option']}
                        rules={[
                          { required: true, message: '请输入内容' },
                          {
                            validator: (_, value) => {
                              if (value !== '') {
                                if (value === '<p><br></p>') {
                                  return Promise.reject(new Error('请输入正确的内容'))
                                } else {
                                  return Promise.resolve()
                                }
                              } else {
                                return Promise.reject(new Error(''))
                              }
                            }
                          }
                        ]}
                        className="form_inside-out-none">
                        <Input.TextArea />
                      </Form.Item>
                    </Col>
                    {/* 加和减 */}
                    <Col span={7}>
                      <Form.Item
                        {...restField}
                        name={[name, 'correct']}
                        valuePropName="checked"
                        initialValue={restField.correct || false}>
                        <Checkbox
                          onChange={e => {
                            if (quesList.length) {
                              let temp = JSON.parse(JSON.stringify(quesList))
                              if (questionStyle === 1 || questionStyle === 3) {
                                if (e.target.checked) {
                                  temp.forEach(item => {
                                    item.correct = false
                                  })
                                }
                              }

                              temp[index].correct = e.target.checked
                              setQuesList(temp)
                              form.setFieldValue('question_list', temp)
                            }
                          }}>
                          正确答案
                        </Checkbox>
                      </Form.Item>
                    </Col>
                    <Col span={3}>
                      <Button
                        onClick={async () => {
                          let temp = JSON.parse(JSON.stringify(quesList))
                          temp.splice(index, 1)
                          setQuesList(temp)

                          await remove(name)
                        }}
                        icon={<MinusOutlined />}></Button>
                    </Col>
                  </Row>
                ))}
                {quesList.length < 2 && questionStyle === 3 && (
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={async () => {
                        let tempQuestion = JSON.parse(JSON.stringify(quesList))
                        tempQuestion.push({ option: '', correct: false })
                        setQuesList(tempQuestion)

                        await add()
                      }}
                      icon={<PlusOutlined />}></Button>
                  </Form.Item>
                )}
                {[1, 2].includes(questionStyle) && (
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={async () => {
                        let tempQuestion = JSON.parse(JSON.stringify(quesList))
                        tempQuestion.push({ option: '', correct: false })
                        setQuesList(tempQuestion)

                        await add()
                      }}
                      icon={<PlusOutlined />}></Button>
                  </Form.Item>
                )}
              </Form.Item>
            )}
          </Form.List>
        )}
        {(questionStyle === 5 || questionStyle === 4) && (
          <Form.Item name="answers" label="正确答案">
            <QuestionEditr editorValue={edierVal} setedierVal={setedierVal} form={form} name="answers" />
          </Form.Item>
        )}
        <Form.Item wrapperCol={{ offset: 11, span: 16 }}>
          <Space size={20}>
            <Button onClick={() => setShowModal(false)}>取消</Button>
            <Button type="primary" disabled={showAddClass} htmlType="submit">
              提交
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  )
}

export default forwardRef(CustomerTopic)
