/**
 * 富文本编辑器相关功能
 */
export function useRichTextEditor() {
  // Quill富文本编辑器配置
  const editorOptions = {
    theme: 'snow',
    placeholder: '请输入课程描述...',
    modules: {
      toolbar: [
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
        ['link', 'image'],
        ['clean']
      ]
    }
  }
  
  // 处理编辑器内容更新
  const handleContentUpdate = (content, courseForm) => {
    courseForm.description = content
  }
  
  // 处理富文本中的base64图片上传到OSS
  const processDescriptionImages = async (description, uploadImageToOss) => {
    if (!description) return description
    
    const base64Regex = /<img[^>]+src="data:image\/([^;]+);base64,([^"]+)"[^>]*>/g
    let processedDescription = description
    const uploadPromises = []
    
    let match
    while ((match = base64Regex.exec(description)) !== null) {
      const [fullMatch, imageType, base64Data] = match
      
      // 将base64转换为File对象
      const byteCharacters = atob(base64Data)
      const byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      const byteArray = new Uint8Array(byteNumbers)
      const blob = new Blob([byteArray], { type: `image/${imageType}` })
      const file = new File([blob], `description_image_${Date.now()}.${imageType}`, { type: `image/${imageType}` })
      
      // 创建上传Promise
      const uploadPromise = uploadImageToOss(file).then(ossUrl => {
        // 替换原来的base64图片为OSS链接
        processedDescription = processedDescription.replace(fullMatch, fullMatch.replace(`data:image/${imageType};base64,${base64Data}`, ossUrl))
      })
      
      uploadPromises.push(uploadPromise)
    }
    
    // 等待所有图片上传完成
    await Promise.all(uploadPromises)
    return processedDescription
  }
  
  return {
    editorOptions,
    handleContentUpdate,
    processDescriptionImages
  }
}
