import { Button, Form, Input, Upload, Space, message } from 'antd'
import { useState, useEffect, useRef } from 'react'
const { TextArea } = Input
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { DomEditor } from '@wangeditor/editor'
import { useLocation, useNavigate } from 'react-router-dom'
import { CloseOutlined } from '@ant-design/icons'
import { addHelp, HelpInfo, editHelp, editPreview } from '../requet'
import { uploadFiles } from '@/utils/upload'

import AliOSS from 'ali-oss'
import dayjs from 'dayjs'
import { getAliOSSSTSToken } from './requet'

import './index.less'

const HelpAddEdit = () => {
  const location = useLocation()
  const navigate = useNavigate()
  const [showPhone, setShowPhone] = useState(false)
  const [form] = Form.useForm()
  // 是否修改
  const [isEdit, setIsEdit] = useState(false)
  const [initialValues, setinitialValues] = useState(JSON.parse(sessionStorage.getItem('editData')) || {})
  const [id, setId] = useState(0)

  const [loading, setLoading] = useState(false) // 定义 loading 状态和 setLoading 函数
  const [uploadProgress, setUploadProgress] = useState(0)

  const getHelpInfo = async (id) => {
    const { help_title, help_content } = await HelpInfo({ id })
    form.setFieldValue('help_title', help_title)
    form.setFieldValue('help_content', help_content)

    setHtml(help_content)
  }
  useEffect(() => {
    if (location.state && location.state.id) {
      setIsEdit(true)
      setId(location.state.id)
      getHelpInfo(location.state.id)
    }
  }, [])

  const [ossClient, setOssClient] = useState(null) // oss 操作
  const [STSToken, setSTSToken] = useState(null) // oss 过期设置

  let ossClientTemp

  const getStsAuthToken = () => {
    return new Promise(async (resolve) => {
      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)
        console.log('AliOSS', ossClientTemp)
      }
      resolve()
    })
  }

  // editor 实例
  const [editor, setEditor] = useState(null)
  // 编辑器内容
  // const [html, setHtml] = useState('');

  // 初始化 html 状态值
  const [html, setHtml] = useState(initialValues.help_content || '')

  // 模拟 ajax 请求，异步设置 html

  const toolbar = DomEditor.getToolbar(editor)

  // 当前菜单排序和分组

  // 工具栏配置
  const toolbarConfig = {
    excludeKeys: [
      'insertVideo',
      'insertImage',
      'emotion',
      // 'table',
      'codeBlock',
      'blockquote',
      'code',
      'group-more-style',
      // 'insertTable',
    ], //删除工具栏
  } // JS 语法

  const editorConfig = {
    // JS 语法
    placeholder: '请输入内容...',
    MENU_CONF: {
      // 配置默认字号
      fontSize: {
        fontSizeList: [
          { name: '初号', value: '56px' },
          { name: '小初', value: '48px' },
          { name: '一号', value: '34px' },
          { name: '小一', value: '32px' },
          { name: '二号', value: '29px' },
          { name: '小二', value: '24px' },
          { name: '三号', value: '21px' },
          { name: '小三', value: '20px' },
          { name: '四号', value: '18px' },
          { name: '小四', value: '16px' },
          { name: '五号', value: '14px' },
          { name: '小五', value: '12px' },
          { name: '六号', value: '10px' },
          { name: '小六', value: '8px' },
          { name: '七号', value: '7px' },
          { name: '八号', value: '8px' },
        ],
      },
      lineHeight: {
        lineHeightList: ['1', '1.25', '1.5', '2', '2.5', '3'],
      },
      // 配置上传图片
      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) => {
          setLoading(true)
          if (!ossClient) {
            console.error('ossClient还未初始化', ossClient)
            return false
          }
          const fileExt = file.name.substring(file.name.lastIndexOf('.'))
          const fileName = `help-${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, '题库图片')

          // const { url } = await uploadFiles({ file, file_type: 'question' });
          // insertFn(url, '题库图片');

          setLoading(false)
        },
      },

      uploadVideo: {
        timeout: 15 * 1000, // 15s
        fieldName: 'video',
        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) => {
          setLoading(true)
          if (!ossClient) {
            console.error('ossClient还未初始化', ossClient)
            return false
          }

          // const multipartOptions = {
          //   partSize: 1024 * 1024, // 分片大小
          //   progress: function (percentage, cpt) {
          //     console.log('上传进度：' + percentage * 100 + '%');
          //     // 这里可以根据 percentage 更新进度条 UI
          //     setUploadProgress(percentage * 100); // 更新上传进度状态
          //   },
          // };

          try {
            // message.success(`视频已上传:${uploadProgress}% , 玩命加载中~~`);
            message.success(`视频已上传:99% , 正玩命加载中~~`)

            const fileExt = file.name.substring(file.name.lastIndexOf('.'))
            const fileName = `help-${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.res.requestUrls[0], '题库视频');
            insertFn(result.url, '题库视频')
            setLoading(false)
          } catch (error) {
            console.error('上传视频失败：', error)
            setLoading(false)
          }
        },
      },
    },
  }

  useEffect(() => {
    getStsAuthToken()
  }, [])

  //添加、修改
  const onFinish = async (obj) => {
    let bool
    const html = editor.getHtml() // 获取最新的编辑器内容
    obj.help_content = html // 更新 help_content 字段
    if (isEdit) {
      bool = await editHelp({ ...obj, id, help_content: html })
    } else {
      bool = await addHelp({ ...obj, help_content: html })
    }
    bool && navigate(-1)
  }

  //点击预览的添加、修改
  const onFinishPre = async (obj) => {
    let bool
    const html = editor.getHtml() // 获取最新的编辑器内容
    obj.help_content = html // 更新 help_content 字段
    if (isEdit) {
      bool = await editPreview({ ...obj, id, help_content: html })
    } else {
      // bool = await addHelp({ ...obj, help_content: html });
    }
  }

  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])

  // 校验
  const vaildaterHtml = (_, value) => {
    let val = editor.getText()
    if (!val) {
      return Promise.reject('问题内容不能为空')
    } else if (val.length > 65535) {
      return Promise.reject('最大长度为65,535个字符')
    } else {
      return Promise.resolve()
    }
  }
  return (
    <div style={{ padding: 10 }}>
      {showPhone && (
        <div className="phone">
          <CloseOutlined className="close" onClick={() => setShowPhone(false)} />
          <div dangerouslySetInnerHTML={{ __html: html }} className="scrollable-div"></div>
        </div>
      )}
      <Form
        form={form}
        labelCol={{ span: 2 }}
        initialValues={initialValues}
        onFinish={onFinish}
        style={{ position: 'relative' }}>
        <Form.Item label="问题名称" name="help_title" rules={[{ required: true, message: '请输入问题名称' }]}>
          <Input autoComplete="off" placeholder="请输入问题名称" style={{ width: 'calc(100% - 180px)' }} />
        </Form.Item>
        <Button
          style={{ position: 'absolute', right: 100, top: 0 }}
          type="primary"
          onClick={async () => {
            setShowPhone(true)
            // 在这里等待帮助信息获取完成后再调用onFinish
            await new Promise((resolve) => setTimeout(resolve, 0)) // 使用微任务延时来确保setHtml完成状态更新

            const formData = form.getFieldsValue()
            formData.help_content = html // 获取并设置最新的编辑器内容
            let helpContent = editor.getHtml() // 保存当前编辑器内容

            if (isEdit) {
              const { help_content } = await HelpInfo({ id: id })
              setHtml(help_content) // 更新编辑器内容
            } else {
              setHtml('help_content') // 更新编辑器内容
            }

            await onFinishPre(formData) // 获取表单所有字段值并传入onFinish

            // 恢复编辑器内容
            setHtml(helpContent)
          }}
          ghost>
          预览
        </Button>

        <Form.Item
          name="help_content"
          label="问题内容"
          rules={[{ required: true, message: '请输入问题内容' }, { validator: vaildaterHtml }]}>
          <div style={{ border: '1px solid #ccc', zIndex: 100, width: 'calc(100% - 100px)' }}>
            {/* <div>视频上传进度：{uploadProgress}%</div> */}

            <Toolbar
              editor={editor}
              defaultConfig={toolbarConfig}
              mode="default"
              style={{ borderBottom: '1px solid #ccc' }}
            />
            {ossClient && (
              <Editor
                defaultConfig={editorConfig}
                value={html} // 使用 html 作为 value 属性的值
                onCreated={setEditor}
                onChange={(editor) => {
                  form.setFieldValue('help_content', editor.getHtml())
                }}
                config={editorConfig}
                mode="default"
                style={{ height: '500px', overflowY: 'hidden' }}
              />
            )}
          </div>
        </Form.Item>
        <Form.Item style={{ textAlign: 'center' }}>
          <Space size={20}>
            <Button
              onClick={() => {
                navigate(-1)
              }}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确认
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  )
}

export default HelpAddEdit
