<template>
  <div class="editor-content">
    <div class="edit-top">
      <!--撤销-->
      <div class="edit-top-menu pointer">
        <el-tooltip content="撤销" placement="top">
          <lz-svg-icon icon-class="cx" class="pointer" @click="undo" />
        </el-tooltip>
      </div>
      <!--重做-->
      <div class="edit-top-menu pointer">
        <el-tooltip content="重做" placement="top">
          <lz-svg-icon icon-class="cz" class="pointer" @click="redo" />
        </el-tooltip>
      </div>
      <!--清除格式-->
      <div class="edit-top-menu pointer">
        <el-tooltip content="清除格式" placement="top">
          <lz-svg-icon icon-class="qcgs" class="pointer" @click="copyFormat" />
        </el-tooltip>
      </div>
      <!--正文/标题-->
      <div class="edit-top-menu pointer">
        <el-dropdown>
          <span class="el-dropdown-link">
            正文/标题
            <lz-svg-icon icon-class="dsj" />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item class="dropdown-menu-item" @click="setHeading('paragraph')">
                <SelectedSvg :show="currentHeading === null" />
                正文
              </el-dropdown-item>
              <el-dropdown-item @click="setHeading('heading', { level: 1 })">
                <SelectedSvg :show="currentHeading === 'h1'" />
                <h1>标题1</h1>
              </el-dropdown-item>
              <el-dropdown-item @click="setHeading('heading', { level: 2 })">
                <SelectedSvg :show="currentHeading === 'h2'" />
                <h2>标题2</h2>
              </el-dropdown-item>
              <el-dropdown-item @click="setHeading('heading', { level: 3 })">
                <SelectedSvg :show="currentHeading === 'h3'" />
                <h3>标题3</h3>
              </el-dropdown-item>
              <el-dropdown-item @click="setHeading('heading', { level: 4 })">
                <SelectedSvg :show="currentHeading === 'h4'" />
                <h4>标题4</h4>
              </el-dropdown-item>
              <el-dropdown-item @click="setHeading('heading', { level: 5 })">
                <SelectedSvg :show="currentHeading === 'h5'" />
                <h5>标题5</h5>
              </el-dropdown-item>
              <el-dropdown-item @click="setHeading('heading', { level: 6 })">
                <SelectedSvg :show="currentHeading === 'h6'" />
                <h6>标题6</h6>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <!--字号-->
      <div class="edit-top-menu pointer">
        <el-dropdown>
          <span class="el-dropdown-link">
            字号
            <lz-svg-icon icon-class="dsj" />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="v in ['9px', '10px', '11px', '12px', '14px', '18px', '20px', '22px', '24px', '26px', '28px', '30px', '36px', '42px', '48px', '56px', '72px']"
                :key="v"
                @click="setFontSize(v)"
              >
                <SelectedSvg :show="currentFontSize === v" />
                <el-space>
                  {{ v }}
                  <span v-show="v === '14px'">默认</span>
                </el-space>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <!--加粗-->
      <div class="edit-top-menu pointer" :class="{ 'active': boldActive }">
        <el-tooltip content="加粗" placement="top">
          <lz-svg-icon icon-class="jc" class="pointer" @click="toggleBold" />
        </el-tooltip>
      </div>
      <!--斜体-->
      <div class="edit-top-menu pointer" :class="{ 'active': italicActive }">
        <el-tooltip content="斜体" placement="top">
          <lz-svg-icon icon-class="xt" class="pointer" @click="toggleItalic" />
        </el-tooltip>
      </div>
      <!--下划线-->
      <div class="edit-top-menu pointer" :class="{ 'active': underlineActive }">
        <el-tooltip content="下划线" placement="top">
          <lz-svg-icon icon-class="xhx" class="pointer" @click="toggleUnderline" />
        </el-tooltip>
      </div>
      <!--删除线-->
      <div class="edit-top-menu pointer" :class="{ 'active': strikeActive }">
        <el-tooltip content="删除线" placement="top">
          <lz-svg-icon icon-class="scx" class="pointer" @click="toggleStrike" />
        </el-tooltip>
      </div>
      <!--字体-->
      <div class="edit-top-menu pointer">
        <el-dropdown>
          <span class="el-dropdown-link">
            字体
            <lz-svg-icon icon-class="dsj" />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="(font, i) in fontFamilyConfig"
                :key="i"
                @click="setFontFamily(font.value)"
              >
                <SelectedSvg :show="currentFontFamily === font.value" />
                <span :style="{ fontFamily: font.value }">
                  {{ font.label }}
                </span>

              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <!--对齐方式-->
      <div class="edit-top-menu pointer">
        <el-dropdown>
          <span class="el-dropdown-link">
            <lz-svg-icon icon-class="dq" class="pointer" />
            <lz-svg-icon icon-class="dsj" />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="setAlign('left')">
                <SelectedSvg :show="currentAlign === 'left'" /> 左对齐
              </el-dropdown-item>
              <el-dropdown-item @click="setAlign('right')">
                <SelectedSvg :show="currentAlign === 'right'" /> 右对齐
              </el-dropdown-item>
              <el-dropdown-item @click="setAlign('center')">
                <SelectedSvg :show="currentAlign === 'center'" />居中对齐
              </el-dropdown-item>
              <el-dropdown-item @click="setAlign('justify')">
                <SelectedSvg :show="currentAlign === 'justify'" /> 两端对齐
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <!--颜色-->
      <div class="edit-top-menu pointer">
        <el-popover placement="bottom" :width="300">
          <template #reference>
            <lz-svg-icon icon-class="ztys" class="pointer" />
          </template>
          <div class="color-panel">
            <div class="color-panel-default-button" id="defaultColor">默认</div>
            <div style="display: flex; flex-wrap: wrap; padding-top: 5px">
              <div
                v-for="(item, index) in defaultColor"
                :key="index"
                class="color-item pointer"
                :data-color="item"
                style="
                  width: 18px;
                  height: 18px;
                  margin: 1px;
                  padding: 1px;
                "
                :style="{
                  border: `1px solid ${item}`,
                  background: item
                }"
                @click="setColor(item)"
              ></div>
            </div>
            <div class="color-panel-title">标准色</div>
            <div style="display: flex; flex-wrap: wrap">
              <div
                v-for="(item, index) in standardColor"
                :key="index"
                class="color-item pointer"
                :data-color="item"
                style="
                  width: 18px;
                  height: 18px;
                  margin: 1px;
                  padding: 1px;
                "
                :style="{
                  border: `1px solid ${item}`,
                  background: item
                }"
                @click="setColor(item)"
              ></div>
            </div>
          </div>
        </el-popover>
      </div>
      <!--无序列表-->
      <div class="edit-top-menu pointer" :class="{ 'active': bulletListActive }">
        <el-tooltip content="无序列表" placement="top">
          <lz-svg-icon icon-class="wxlb" class="pointer" @click="toggleBulletList" />
        </el-tooltip>
      </div>
      <!--有序列表-->
      <div class="edit-top-menu pointer" :class="{ 'active': orderedListActive }">
        <el-tooltip content="有序列表" placement="top">
          <lz-svg-icon icon-class="yxlb" class="pointer" @click="toggleOrderedList" />
        </el-tooltip>
      </div>
      <!--减少缩进-->
      <div class="edit-top-menu pointer">
        <el-tooltip content="减少缩进" placement="top">
          <lz-svg-icon icon-class="jssj" class="pointer" @click="decreaseIndent" />
        </el-tooltip>
      </div>
      <!--增加缩进-->
      <div class="edit-top-menu pointer">
        <el-tooltip content="增加缩进" placement="top">
          <lz-svg-icon icon-class="zjsj" class="pointer" @click="increaseIndent" />
        </el-tooltip>
      </div>
    </div>
    <editor-content :editor="editor" class="edit-content" />
    <span class="count">{{ textCount }}字</span>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { Editor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import { CustomSpan, fontFamilyConfig, TextIndent, defaultColor, standardColor } from './custom-span' // 导入自定义扩展
import Underline from '@tiptap/extension-underline'
import Color from '@tiptap/extension-color'
import TextStyle from '@tiptap/extension-text-style'
import TextAlign from '@tiptap/extension-text-align'

import FontSize from '@tiptap/extension-font-size'
import FontFamily from '@tiptap/extension-font-family'
import SelectedSvg from './SelectedSvg.vue'
import { debounce } from 'lodash-es'

const editor: any = ref(null)
const formatCache = ref<any>(null)

const textCount = ref<number>(0)

const toggleBold = () => editor.value.chain().focus().toggleBold().run()
const toggleItalic = () => editor.value.chain().focus().toggleItalic().run()
const toggleUnderline = () => editor.value.chain().focus().toggleUnderline().run()
const toggleStrike = () => editor.value.chain().focus().toggleStrike().run()
const undo = () => editor.value.chain().focus().undo().run()
const redo = () => editor.value.chain().focus().redo().run()
const copyFormat = () => {
  // 获取当前选区格式
  const currentFormat = editor.value.getAttributes('textStyle')
  // 将格式存储在临时变量中
  formatCache.value = currentFormat
  ElMessage.success('格式已复制，请选择要应用格式的文本')
}

const setColor = (value: any) => {
  editor.value.chain().focus().setColor(value).run()
}


const setAlign = (alignment: string) => {
  editor.value.chain().focus().setTextAlign(alignment).run()
  currentAlign.value = alignment
}


const toggleBulletList = () => {
  editor.value.chain().focus().toggleBulletList().run()
}
const setHeading = (type: string, attributes?: any) => {
  if (type === 'paragraph') {
    editor.value.chain().focus().setParagraph().run()
  } else {
    editor.value.chain().focus().toggleHeading(attributes).run()
  }
}

const setFontSize = (size: string) => {
  editor.value.chain().focus().setFontSize(size).run()
}

const setFontFamily = (font: string) => {
  editor.value.chain().focus().setFontFamily(font).run()
}

const toggleOrderedList = () => {
  editor.value.chain().focus().toggleOrderedList().run()
}

const indentNum = ref<number>(0)

const increaseIndent = () => {
  editor.value.chain().focus().increaseIndent().run()
}
const decreaseIndent = () => {
  editor.value.chain().focus().decreaseIndent().run()
}

const currentAlign = ref('left')
// 监听编辑器选中变化
const updateCurrentAlign = () => {
  const textAlignAttrs = editor.value.getAttributes('textAlign')
  // 尝试不同方式获取对齐属性
  const align =
    textAlignAttrs.align ||
    textAlignAttrs.textAlign ||
    editor.value.getAttributes('paragraph')?.textAlign
  currentAlign.value = align || 'left'
}

const currentFontFamily = ref('SimSun, serif;')
const updateCurrentFontFamily = () => {
  const fontFamily = editor.value.getAttributes('textStyle').fontFamily
  currentFontFamily.value = fontFamily || fontFamilyConfig[0].value // 默认第一个字体
}
const currentFontSize = ref('14px')
const updateCurrentFontSize = () => {
  const fontSize = editor.value.getAttributes('textStyle').fontSize
  currentFontSize.value = fontSize || '14px' // 默认字号
}
const currentHeading: any = ref(null)
const updateCurrentHeading = () => {
  if (editor.value.isActive('heading', { level: 1 })) {
    currentHeading.value = 'h1'
  } else if (editor.value.isActive('heading', { level: 2 })) {
    currentHeading.value = 'h2'
  } else if (editor.value.isActive('heading', { level: 3 })) {
    currentHeading.value = 'h3'
  } else if (editor.value.isActive('heading', { level: 4 })) {
    currentHeading.value = 'h4'
  } else if (editor.value.isActive('heading', { level: 5 })) {
    currentHeading.value = 'h5'
  } else if (editor.value.isActive('heading', { level: 6 })) {
    currentHeading.value = 'h6'
  } else {
    currentHeading.value = null // 正文
  }
}
// 添加状态变量
const boldActive = ref(false)
const italicActive = ref(false)
const underlineActive = ref(false)
const strikeActive = ref(false)
const bulletListActive = ref(false)
const orderedListActive = ref(false)

// 更新所有活动状态的函数
const updateAllActiveStates = debounce(() => {
  if (!editor.value) return

  // 更新文本样式状态
  boldActive.value = editor.value.isActive('bold')
  italicActive.value = editor.value.isActive('italic')
  underlineActive.value = editor.value.isActive('underline')
  strikeActive.value = editor.value.isActive('strike')

  // 更新列表状态
  bulletListActive.value = editor.value.isActive('bulletList')
  orderedListActive.value = editor.value.isActive('orderedList')

  // 保持原有的更新函数
  updateCurrentAlign()
  updateCurrentFontFamily()
  updateCurrentHeading()
  updateCurrentFontSize()
}, 300)

onMounted(() => {
  // 确保编辑器容器存在
  const editorContainer = document.querySelector('.editor-content')
  if (!editorContainer) {
    console.error('Editor container not found')
    return
  }

  editor.value = new Editor({
    content: "",
    extensions: [
      StarterKit, // 包含基础格式
      CustomSpan,
      TextStyle,
      Underline,
      Color.configure({ types: ['textStyle'] }),
      TextAlign.configure({ types: ['heading', 'paragraph'] }),
      FontSize.configure({ types: ['textStyle'] }),
      FontFamily.configure({types: ['textStyle'] }),
      TextIndent
    ],
    onCreate: ({ editor }) => {
      textCount.value = editor.getText()?.length
    },
    onUpdate: ({ editor }) => {
      textCount.value = editor.getText()?.length
      updateAllActiveStates()
    },
    onSelectionUpdate: () => {
      updateAllActiveStates()
    }
  })
})

onBeforeUnmount(() => {
  editor.value?.destroy()
})

defineExpose({
  editor
})
</script>

<style scoped lang="scss">
.editor-content {
  background: #fff;
  border-radius: 16px;
  padding: 0 30px 20px;
  position: relative;
  display: flex;
  flex-direction: column;

  .edit-top {
    display: flex;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    justify-content: center;
    gap: 10px;
    align-items: center;
    flex-wrap: wrap;
    padding: 8px 0;
    user-select: none;
    &-menu {
      padding: 5px;
      border-radius: 4px;

      &:hover {
        background: #eee;
      }
      .download-menu-item {
        height: 20px;
        display: flex;
        align-items: center;
      }

    }
    .active {
      background: #eee;
    }
    .svg-icon {
      width: 16px;
      height: 16px;
    }
  }

  .edit-content {
    flex: 1;
    padding: 20px 30px;
    line-height: 1.5;
    min-height: 200px;
    overflow-y: auto;
    margin-bottom: 10px;
    /* 富文本内容样式 */
    p {
      margin: 0 0 1em 0;
    }

    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
      margin: 1em 0 0.5em 0;
      line-height: 1.2;
    }

    ul,
    ol {
      padding-left: 2em;
      margin: 0.5em 0;
    }

    /* 滚动条样式 */
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
      border-radius: 2px;
    }

    &::-webkit-scrollbar-thumb {
      background: #eee;
      border-radius: 10px;
    }
  }

  .count {
    position: absolute;
    left: 10px;
    bottom: 10px;
    color: #999999;
  }
}
</style>
<style lang="scss">
.editor-content {
  ul {
    list-style: disc;
  }
}
</style>
