<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑单页"
    width="900px"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入标题"
          maxlength="100"
        />
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <div v-if="showEditor" class="editor-container">
          <Toolbar
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
            class="editor-toolbar"
          />
          <Editor
            :defaultConfig="editorConfig"
            :mode="mode"
            class="editor-content"
            @onCreated="handleCreated"
          />
        </div>
        <div v-else class="editor-loading">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载编辑器中...</span>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, shallowRef, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'
import '@wangeditor/editor/dist/css/style.css'
import { uploadFile } from '@/api/upload'
import {
  updateDanye,
  type DanyeDetailResponse,
  type DanyeUpdateRequest
} from '@/api/business/danye'

const props = defineProps<{
  modelValue: boolean
  danye: DanyeDetailResponse | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 编辑器实例
const editorRef = shallowRef<IDomEditor>()
const showEditor = ref(false)
const mode = 'default'

// 工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: [
    'group-video', // 排除视频上传
    'fullScreen'   // 排除全屏（弹窗内不适合）
  ]
}

// 编辑器配置
const editorConfig: Partial<IEditorConfig> = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      maxFileSize: 20 * 1024 * 1024, // 20MB
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'],
      // 使用自定义上传，复用 ImageUpload 组件的上传逻辑
      async customUpload(file: File, insertFn: (url: string, alt?: string, href?: string) => void) {
        try {
          const res = await uploadFile(file)
          if (res.code === 0 && res.data?.url) {
            insertFn(res.data.url, file.name, '')
          } else {
            ElMessage.error(res.message || '图片上传失败')
          }
        } catch (error: any) {
          console.error('图片上传错误:', file.name, error)
          ElMessage.error(`图片 ${file.name} 上传失败`)
        }
      }
    },
    // 颜色配置
    color: {
      colors: [
        '#000000', '#262626', '#595959', '#8c8c8c', '#bfbfbf', '#d9d9d9', '#e9e9e9', '#f5f5f5', '#fafafa', '#ffffff',
        '#f5222d', '#fa541c', '#fa8c16', '#fadb14', '#52c41a', '#13c2c2', '#1890ff', '#2f54eb', '#722ed1', '#eb2f96'
      ]
    },
    // 字体大小配置
    fontSize: {
      fontSizeList: ['12px', '14px', '16px', '18px', '20px', '24px', '28px', '32px', '36px']
    }
  }
}

// 表单引用
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
const formData = reactive({
  title: '',
  content: ''
})

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { max: 100, message: '标题不能超过100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ]
}

// 清理 HTML 内容，修复可能导致编辑器解析错误的格式问题
const cleanHtmlContent = (html: string): string => {
  if (!html) return '<p></p>'
  
  // 修复以分号开头的 style 属性（如 style=";font-family:宋体"）
  let cleaned = html.replace(/style=";/g, 'style="')
  
  // 移除空的 style 属性
  cleaned = cleaned.replace(/style=""/g, '')
  
  // 修复连续的分号
  cleaned = cleaned.replace(/;;+/g, ';')
  
  // 移除 style 属性开头的分号
  cleaned = cleaned.replace(/style=";\s*/g, 'style="')
  
  // 移除可能导致问题的特殊字符
  cleaned = cleaned.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '')
  
  return cleaned || '<p></p>'
}

// 编辑器创建完成
const handleCreated = (editor: IDomEditor) => {
  console.log('[DanyeFormDialog] handleCreated called')
  editorRef.value = editor
  
  // 延迟设置内容，确保编辑器完全初始化
  nextTick(() => {
    setTimeout(() => {
      if (editor && !editor.isDestroyed && formData.content) {
        try {
          const cleanedContent = cleanHtmlContent(formData.content)
          console.log('[DanyeFormDialog] Setting cleaned content')
          editor.setHtml(cleanedContent)
        } catch (e) {
          console.error('[DanyeFormDialog] Error setting content:', e)
          // 如果设置失败，尝试设置为空
          try {
            editor.setHtml('<p></p>')
          } catch (e2) {
            console.error('[DanyeFormDialog] Error setting empty content:', e2)
          }
        }
      }
    }, 100)
  })
}

// 监听弹窗打开，初始化数据
watch(() => props.modelValue, (visible) => {
  console.log('[DanyeFormDialog] modelValue changed:', visible)
  if (visible && props.danye) {
    formData.title = props.danye.title
    formData.content = props.danye.content || ''
    // 延迟显示编辑器，确保弹窗已渲染
    nextTick(() => {
      showEditor.value = true
    })
  }
})

// 监听 dialogVisible 变化
watch(dialogVisible, (visible) => {
  console.log('[DanyeFormDialog] dialogVisible changed:', visible)
  if (!visible) {
    showEditor.value = false
  }
})

// 组件销毁时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor && !editor.isDestroyed) {
    editor.destroy()
  }
})

// 重置表单
const resetForm = () => {
  formData.title = ''
  formData.content = ''
  showEditor.value = false
  formRef.value?.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  // 先销毁编辑器实例
  if (editorRef.value && !editorRef.value.isDestroyed) {
    editorRef.value.destroy()
    editorRef.value = undefined
  }
  showEditor.value = false
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value || !props.danye) return

  try {
    await formRef.value.validate()
  } catch {
    return
  }

  // 从编辑器获取最新内容
  if (editorRef.value && !editorRef.value.isDestroyed) {
    formData.content = editorRef.value.getHtml()
  }

  submitLoading.value = true
  try {
    const submitData: DanyeUpdateRequest = {
      title: formData.title,
      content: formData.content
    }

    await updateDanye(props.danye.id, submitData)
    ElMessage.success('保存成功')
    emit('success')
    handleClose()
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped>
.page-container {
  padding: 0;
}

.editor-container {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  z-index: 100;
}

.editor-toolbar {
  border-bottom: 1px solid #dcdfe6;
}

.editor-content {
  height: 400px;
  overflow-y: auto;
}

.editor-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 400px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #909399;
  gap: 8px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 确保编辑器下拉菜单在弹窗之上 */
:deep(.w-e-bar-item) {
  z-index: 10001 !important;
}

:deep(.w-e-modal) {
  z-index: 10002 !important;
}

:deep(.w-e-drop-panel) {
  z-index: 10002 !important;
}
</style>
