<template>
  <div class="writing-container">
    <div class="header">
      <div class="left">
        <el-icon @click="back" class="pointer" style="margin-right: 12px">
          <ArrowLeftBold />
        </el-icon>
        <el-input v-if="updateTitleVisible" placeholder="请输入标题" v-model="updateTitle" style="width: 80%" />
        <span v-else >{{ pageTitle }}</span>
        <template v-if="updateTitleVisible" >
          <el-button size="small" style="margin-left: 8px;" type="primary"  @click="handleSaveTitle">保存</el-button>
          <el-button size="small" style="margin-left: 8px;" @click="updateTitleVisible = false">取消</el-button>
        </template>

        <el-icon v-else-if="pageTitle" @click="handleEditTitleOpen" style="margin-left: 8px;" class="pointer"><Edit /></el-icon>
      </div>
      <div class="right">
        <el-space :size="20">
          <ModelSelect />
          <el-button type="primary" style="width: 80px" :disabled="writingStatus !== 'applyDocs'" @click="download">下载</el-button>
          <el-button type="primary" style="width: 80px" :disabled="writingStatus !== 'applyDocs'" @click="saveDocument"
            >保存</el-button
          >
        </el-space>
      </div>
    </div>
    <div class="bottom-content">
      <div class="left-content">
        <!--左侧富文本-->
        <div class="editor" ref="editorRef" style="height: 100%">
          <div
            class="aie-container"
            :class="showEditorResult || showEditorLoading ? 'disabled-aie-container' : ''"
          >
            <div class="text-count">{{ aiEditorTextLen }}字</div>
            <div class="mask" v-if="showEditorResult || showEditorLoading"></div>
<!--            :style="{ top: docs.currentRightMenu === 1 ? editorPosY + 'px' : '50px'}"-->
            <div
              class="editor-result-status"
              :style="{ top: '50px'}"
              v-if="showEditorResult || showEditorLoading"
            >
              <EditorResult
                v-if="showEditorResult"
                :success-text="successText"
                :status="docs.currentRightMenu === 0 ? 'apply' : 'replace'"
                :showButton="!showEditorLoading"
                @apply="applyAiDocs"
                @refresh="handleRefresh"
                @delete="handleDel"
              />
              <EditorLoading ref="EditorLoadingRef" v-if="showEditorLoading" @stop="handleStop" @refresh="handleRefresh" @close="handleClose" />
            </div>
          </div>
        </div>
        <!--Ai创作-->
        <div class="steps" v-show="docs.currentRightMenu === 0" v-loading="stepPageLoading" :element-loading-text="currentStep === 1 ? '正在生成大纲信息' : currentStep === 3 ? '正在生成文档' :''">
          <AiWritingSteps
            :next-before-call-back="nextBeforeCallBack"
            @create="handleCreateWriting"
            :step-page-loading="stepPageLoading"
            :createButtonDisabled="createButtonDisabled"
          >
            <div class="step-page" v-show="currentStep === 0">
              <AiWritingScene />
            </div>
            <div class="step-page" v-show="currentStep === 1">
              <RightPageTitle title="填写基础信息" button-text="填入示例" @click="defaultText" v-if="!hiddenDefaultText.includes(currentScene)"/>
              <el-form
                :model="formData"
                ref="formDataRef"
                label-width="auto"
                style="max-width: 600px"
                label-position="top"
              >
                <FormItem
                  v-for="(v, i) in baseFormConfig"
                  :key="i"
                  v-bind="v"
                  :form-data="formData"
                />
              </el-form>
            </div>
            <div class="step-page" v-show="currentStep === 2" style="padding-bottom: 20px">
              <RightPageTitle
                title="章节目录"
                button-text="重新生成"
                @click="resetCreate"
                icon="refresh"
              />
              <Outline v-model:data="outlineData" />
            </div>
            <div class="step-page" v-show="currentStep === 3" style="padding-top: 20px">
              <el-form-item label="参考来源：" label-position="top" style="margin-bottom: 20px">
                <el-radio-group v-model="referenceSource" @change="handleChangeSource">
                  <el-radio value="01">关联知识库</el-radio>
                  <el-radio value="02">关联文档</el-radio>
                  <el-radio value="03">本地上传</el-radio>
                </el-radio-group>
              </el-form-item>
              <template v-if="referenceSource !== '03'">
                <div class="el-form-item__label" style="justify-content: start">
                  内容参考:
                </div>
                <div class="step-page-doc-item pointer" @click="handleOpenAssociation" style="background: #fff">
                  <span>关联{{ referenceSource === '02' ? '文档' : '知识库' }}</span>
                  <img src="@/assets/webapp/14.svg" alt="" class="pointer" />
                </div>
                <div class="step-page-doc">
                  <div class="step-page-doc-item" v-for="(item, i) in associationData" :key="i">
                    <span>{{ item.name }}</span>
                    <lz-svg-icon icon-class="shanchu1" class="pointer" @click="handleDeleteAssociation(i)" />
                  </div>

                </div>
                <el-input type="textarea" :rows="5" v-model="referenceContent" placeholder="请输入参考内容" />
              </template>
              <AiWritingUpload v-else v-model:value="reference" />
            </div>
          </AiWritingSteps>
        </div>
        <!--Ai润色-->
        <div class="steps" v-show="docs.currentRightMenu === 1" v-loading="polishPageLoading" :element-loading-text="polishPageLoadingText">
          <!--润色一级页面-->
          <PolishList  @create-title="createTitle" :clickBefore="handleClickBefore" />
          <!--润色二级页面-->
          <PolishSetting
            ref="PolishSettingRef"
            @polish="polish"
            @extend="extend"
            @shorten="shorten"
          />
        </div>
        <!--Ai助手-->
        <div class="steps" v-show="docs.currentRightMenu === 2">
          <AiChat />
        </div>
      </div>
      <RightMenu />
    </div>
    <DialogDataset ref="dialogDatasetRef" @submit-handle="saveAssociationData" :ids="associationDataIds" />
    <DialogDoc ref="dialogDocRef" @submit-handle="saveAssociationData" :ids="associationDataIds" />
  </div>
</template>
<script setup lang="ts">
import router from '@/router'
import api from '@/servers/finyx/api'
import { MsgConfirm, MsgWarning } from '@/utils/message'

import { AiEditor } from 'aieditor'
import 'aieditor/dist/style.css'
import { ElMessage } from 'element-plus'
import { compact, cloneDeep, filter, isEmpty } from 'lodash-es'
import { ref, onUnmounted, onMounted, computed, nextTick } from 'vue'
// 最右侧菜单 写作 | 润色 | 助手
import RightMenu from '@/views/smart/writing/compoments/rightMenu.vue'
// 写作右侧页面 步骤条
import AiWritingSteps from '@/views/smart/writing/compoments/AiWritingSteps.vue'
// 写作右侧页面 标题
import RightPageTitle from '@/views/smart/writing/compoments/rightPageTitle.vue'
// 写作右侧页面 选择场景
import AiWritingScene from '@/views/smart/writing/compoments/AiWritingScene.vue'
// 写作右侧页面 基本信息
import FormItem from '@/views/smart/writing/compoments/formItem.vue'
// 写作右侧页面 大纲信息
import Outline from '@/views/smart/writing/compoments/outline.vue'
// 写作右侧页面 参考文档
import AiWritingUpload from '@/views/smart/writing/compoments/AiWritingUpload.vue'
// 富文本编辑器 AI生成中，超时，失败等状态
import EditorLoading from '@/views/smart/writing/compoments/editorLoading.vue'
// 富文本编辑器 流文字返回，打印机效果
import EditorResult from '@/views/smart/writing/compoments/editorResult.vue'
// 润色菜单
import PolishList from '@/views/smart/writing/compoments/polishList.vue'
// 润色配置二级页面
import PolishSetting from '@/views/smart/writing/compoments/polishSetting.vue'
// ai助手
import AiChat from '@/views/smart/writing/compoments/AiChat.vue'
// 模型选择
import ModelSelect from '@/views/smart/writing/compoments/ModelSelect.vue'

import DialogDataset from '@/views/knowledge/components/DialogDataset.vue'
import DialogDoc from '@/views/knowledge/components/DialogDoc.vue'
// 图标
import PolishSvg from '@/assets/webapp/9.svg'
import ExpansionSvg from '@/assets/webapp/10.svg'
import AbbreviationsSvg from '@/assets/webapp/11.svg'
import { useRoute } from 'vue-router'
import useStore from '@/stores'
import { formListConfig, hiddenDefaultText } from './formConfig'
import {
  createDocument,
  saveBasicInfo,
  saveOutline,
  saveDocumentItem,
  actionDocument,
  getOutline,
  getDocumentItem,
  downloadDocument,
  createPolish, // 润色、扩写
} from '@/api/writing'
import { responseToText } from '@/request/fetchWithAbort'

const { query } = useRoute()

const { docs, knowledge } = useStore()

const updateTitle = ref('')

const updateTitleVisible = ref(false);
const handleEditTitleOpen = () => {
  updateTitleVisible.value = true
  updateTitle.value = cloneDeep(pageTitle.value);
}

const handleSaveTitle = async () => {
  pageTitle.value = cloneDeep(updateTitle.value)
  await saveDocumentItem({
    content: aiEditor?.getMarkdown(),
    template_id: docs.currentScene,
    title: pageTitle.value
  })
  ElMessage.success('修改标题成功！')
  updateTitleVisible.value = false
  updateTitle.value = '';
}

// Ai 润色相关操作

const PolishSettingRef: any = ref(null)
function handelOperatePolish(data: any) {
  if(!data.content) {
    MsgWarning('内容不能为空')
    return;
  }
  if (data.preferences && data.preferences['优化方向']) {
    data.preferences['优化方向'] = data.preferences['优化方向'].join();
  }
  delayedDeleteFloatingMenu()
  data.template_id = docs.currentScene || '';
  data.document_id = docs.document_id || '';
  showEditorLoading.value = true
  stepPageLoading.value = true
  successText.value = '';
  createPolish(data)
  .then((response) => {
      responseToText(response, (status, data: any) => {
        if (status) {
          if (data.type === 'done') {
            // 流处理成功 返回成功回调
            showEditorLoading.value = false
            polishPageLoading.value = false
          } else if (data.type === 'error') {
            // 流处理失败 返回失败回调
            showEditorResult.value = false
            polishPageLoading.value = false
            EditorLoadingRef.value.updateStatus('error')
            MsgWarning(data.error)
          } else {
            showEditorResult.value = true
            successText.value += data.content
          }
        }
      })
    })
    .catch(() => {
      MsgWarning('Ai润色失败！')
      polishPageLoading.value = false
      showEditorLoading.value = false
    })
}

// 获取选中的文本内容
function getSelectorAllText(){
  // 优先使用 富文本编辑器自带的方法。
  let content: any = aiEditor ? aiEditor.getSelectedText() : ''
  if (!content) {
    content = aiEditor?.getText()
  }
  return content;
}
// AI润色-生成标题
const createTitle = () => {
  // 0: 润色 1: 扩写 2: 生成标题 3:缩写
  const data: any = {
    content: aiEditor?.getText() || '',
    template_id: docs.currentScene || '',
    action: 2,
    document_id: docs.document_id || '',
  }
  if(!data.content) {
    MsgWarning('内容不能为空')
    return;
  }
  polishPageLoading.value = true
  polishPageLoadingText.value = 'AI生成标题中'
  createPolish(data).then((response) => {
    responseToText(response, (status, data: any) => {
        if (status) {
          if (data.type === 'done') {
            // 流处理成功 返回成功回调

          } else if (data.type === 'error') {
            // 流处理失败 返回失败回调
            MsgWarning(data.error)
          } else {
            updateTitle.value = data.content
            updateTitleVisible.value = true;
          }
        }
        polishPageLoading.value = false
      })
  })
}

// Ai润色-润色
const polish = (formDataValue: any) => {
  docs.setAiLoadingText('AI正在一键润色')
  polishPageLoading.value = true
  polishPageLoadingText.value = 'AI正在一键润色'
  const content = getSelectorAllText();
  handelOperatePolish({
    content,
    action: 0, // 0: 润色 1: 扩写 2: 生成标题 3:缩写
    preferences: {
      ...formDataValue
    }
  })
}
// Ai润色-扩写
const extend = (formDataValue: any) => {
  docs.setAiLoadingText('AI正在一键扩写')
  polishPageLoading.value = true
  polishPageLoadingText.value = 'AI正在一键扩写'
  const content = getSelectorAllText();
  handelOperatePolish({
    content,
    action: 1, // 0: 润色 1: 扩写 2: 生成标题 3:缩写
    preferences: {
      ...formDataValue
    }
  })
}
// Ai润色-缩写
const shorten = (formDataValue: any) => {
  docs.setAiLoadingText('AI正在一键缩写')
  polishPageLoading.value = true
  polishPageLoadingText.value = 'AI正在一键缩写'
  const content = getSelectorAllText();
  handelOperatePolish({
    content,
    action: 3, // 0: 润色 1: 扩写 2: 生成标题 3:缩写
    preferences: {
      ...formDataValue
    }
  })
}

// 写作 相关代码
const stepPageLoading = ref(false)
const polishPageLoading: any = ref(false)
const polishPageLoadingText: any = ref('')
// 写作 右侧当前步骤节点
const currentStep = computed(() => {
  return docs.currentAiWritingStep
})

const createButtonDisabled = computed(() => {
  if (isEmpty(initValue.value)) {
    return false;
  }
  return JSON.stringify(initValue.value.basic_info) === JSON.stringify(formData.value) && JSON.stringify(initValue.value.outline) === JSON.stringify(outlineData.value) && reference.value.material?.id === initValue.value.reference[0] && reference.value.data?.id === initValue.value.reference[1] && initValue.value.scene === docs.currentScene && initValue.value.referenceSource === referenceSource.value && JSON.stringify(initValue.value.associationData) === JSON.stringify(associationData.value)
})
const pageTitle: any = ref('')
const writingStatus: any = ref('loading')
// 写作 当前场景
const currentScene: any = computed(() => docs.currentScene)
// 写作 基础信息
const formDataRef: any = ref(null)
// 写作 基础信息表单
const formData: any = ref({})
// 写作 基础信息表单配置
// @ts-ignore
const baseFormConfig: any = computed(() => formListConfig[currentScene.value])
const nextBeforeCallBack = async () => {
  if (currentStep.value === 0) {
    if (!currentScene.value) {
      MsgWarning('请先选择场景模板！')
      return false
    }
    if (!docs.document_id) {
      const documentData = await createDocument({
        template_type: docs.currentSceneType,
        template_id: docs.currentScene
      })
      docs.setDocumentId(documentData.data.id)
    }
    return true
  }
  if (currentStep.value === 1) {
    try {
      if (JSON.stringify(formData.value) !== JSON.stringify(initValue.value.basic_info)) {
        stepPageLoading.value = true
        await formDataRef.value.validate()
        await saveBasicInfo(formData.value)

        const outline = await getOutline()
        if (outline.data && outline.data.id) {
          docs.setOutlineId(outline.data.id)
          outlineData.value = outline.data?.outline
          pageTitle.value = outline.data.title
        }
        stepPageLoading.value = false
      }
      return true
    } catch (e) {
      stepPageLoading.value = false
      return false
    }
  }
  if (currentStep.value === 2) {
    if (outlineData.value.length === 0) {
      MsgWarning('请先添加章节信息！')
      return false
    }
    try {
      if (JSON.stringify(outlineData.value) !== JSON.stringify(initValue.value.outline)) {
        stepPageLoading.value = true
        await saveOutline({
          action: 0,
          outline: outlineData.value
        })
        stepPageLoading.value = false
      }
      return true
    } catch (e) {
      console.log(e)
      return false
    }
  }
}

// 大纲章节信息
const outlineData = ref([])
// 重置章节信息
const resetCreate = async () => {
  try {
    stepPageLoading.value = true
    const outline = await getOutline()
    docs.setOutlineId(outline.data.id)
    pageTitle.value = outline.data.title
    outlineData.value = outline.data?.outline
    stepPageLoading.value = false
  } catch (e) {
    stepPageLoading.value = false
    console.log(e)
  }
}
// 基础信息填写默认示例
const defaultText = () => {
  baseFormConfig.value.forEach((item: any) => {
    formData.value[item.field] = item.defaultText
  })
}

const referenceSource = ref<any>('01') // 01 关联知识库 02 关联文档 03 本地上传
const referenceContent = ref<string>('')
const referenceDetail = ref<any>({})
// 参考文献资料
const reference: any = ref({
  // 参考
  material: {},
  // 数据
  data: {}
})

const dialogDocRef = ref<any>(null)
const dialogDatasetRef = ref<any>(null)

const handleChangeSource = () => {
  // 01 关联知识库 02 关联文档 03 本地上传
  if (referenceSource.value !== '03') {
    associationData.value = []
  } else {
    reference.value = {
      material: {},
      data: {},
    }
  }
}

const handleOpenAssociation = () => {
  // 01 关联知识库 02 关联文档 03 本地上传
  if (referenceSource.value === '01') {
    dialogDatasetRef.value?.open();
  } else if (referenceSource.value === '02') {
    knowledge.setCategory({ id: '', name: ''})
    dialogDocRef.value?.open();
  }
}
const associationData = ref<any>([])

const associationDataIds = computed(() => associationData.value.map((v: any) => v.id))
const saveAssociationData = (ids: any, data: any) => {
  associationData.value = data;
}
const handleDeleteAssociation = (i: number) => {
  associationData.value.splice(i, 1)
}

const saveReference = async () => {
  // 01 关联知识库 02 关联文档 03 本地上传
  if (referenceSource.value !== '03') {
    try {
      const model: any = {
        id: docs.document_id,
        referenceSource: referenceSource.value,
        context: referenceContent.value,
      }
      // 01 关联知识库 02 关联文档 03 本地上传
      if (referenceSource.value === '01') {
        model.knowledgeResultVOS = associationData.value.map((v: any) => ({ id: v.id, name: v.name }))
      } else if (referenceSource.value === '02') {
        model.documentResultVOS = associationData.value.map((v: any) => ({ id: v.id, name: v.name }))
      } else if (referenceSource.value === '03') {
        model.formatDocumentId = reference.value.material?.id
        model.contentDocumentId = reference.value.data?.id
      }
      if (referenceDetail.value?.id) {
        await api.zhinengxiezuo.update13(model)
      } else {
        await api.zhinengxiezuo.save13(model)
      }
    } catch (e) {
      return e;
    }
  }
}

// 编辑器
let aiEditor: AiEditor | null = null
const editorRef: any = ref()
const showEditorLoading: any = ref(false)
const showEditorResult: any = ref(false)
const successText: any = ref('')
const editorPosY: any = ref(0)
const aiEditorTextLen: any = ref(0)
const EditorLoadingRef: any = ref(null)

// 开始生成
const handleCreateWriting = () => {
  stepPageLoading.value = true
  showEditorLoading.value = true
  writingStatus.value = 'createLoading'
  successText.value = '';
  docs.setAiLoadingText('AI正在生成文章')
  initValue.value.scene = cloneDeep(docs.currentScene);
  initValue.value.basic_info = cloneDeep(formData.value);
  initValue.value.outline = cloneDeep(outlineData.value);
  initValue.value.reference = cloneDeep(compact([reference.value.material?.id, reference.value.data?.id]))
  initValue.value.referenceSource = cloneDeep(referenceSource.value)
  initValue.value.associationData = cloneDeep(associationData.value)
  saveReference();
  actionDocument({ action: 0 })
    .then((response) => {
      showEditorResult.value = true
      responseToText(response, (status, data, fullResult) => {
        if (status) {
          if (data.type === 'done') {
            // 流处理成功 返回成功回调
            showEditorLoading.value = false
            stepPageLoading.value = false
          } else if (data.type === 'error') {
            // 流处理失败 返回失败回调
            stepPageLoading.value = false
            showEditorResult.value = false
            EditorLoadingRef.value.updateStatus('error')
            MsgWarning(data.error)
          } else {
            successText.value += data.content
          }
        }
      })
    })
    .catch(() => {
      MsgWarning('创建失败！')
      stepPageLoading.value = false
      showEditorLoading.value = false
    })
}

// 替换原文或者采纳
const applyAiDocs = () => {
  if (docs.currentRightMenu === 0) {
    aiEditor?.focus()?.setMarkdownContent(successText.value)
    actionDocument({ action: 3 })
    writingStatus.value = 'applyDocs'
  }
  if (docs.currentRightMenu === 1) {
    if (!aiEditor?.getSelectedText()) {
      aiEditor?.focus()?.setMarkdownContent(successText.value)
    } else {
      aiEditor?.focus()?.insertMarkdown(successText.value)
    }
  }
  showEditorResult.value = false
  stepPageLoading.value = false
}

const handleClose = () => {
  successText.value = '';
  polishPageLoadingText.value = '';
  showEditorResult.value = false
  showEditorLoading.value = false
  stepPageLoading.value = false;
  polishPageLoading.value = false;
}
const handleStop = () => {
  try {
    handleClose();
    // @ts-ignore
    window._controller?.abort()
  } catch (e) {
    console.log(e)
  }
}
// AI创作刷新
const handleRefresh = () => {
  stepPageLoading.value = true
  showEditorLoading.value = true
  writingStatus.value = 'RefreshLoading'
  successText.value = '';
  if (docs.currentRightMenu === 0) {
    docs.setAiLoadingText('AI正在重新生成文章')
    actionDocument({ action: 1 })
    .then((response) => {
      showEditorResult.value = true
      responseToText(response, (status, data, fullResult) => {
        if (status) {
          if (data.type === 'done') {
            // 流处理成功 返回成功回调
            showEditorLoading.value = false
            stepPageLoading.value = false
          } else if (data.type === 'error') {
            // 流处理失败 返回失败回调
            stepPageLoading.value = false
            showEditorResult.value = false
            EditorLoadingRef.value.updateStatus('error')
            MsgWarning(data.error)
          } else {
            successText.value = fullResult
          }
        }
      })
    })
    .catch(() => {
      MsgWarning('创建失败！')
      stepPageLoading.value = false
      showEditorLoading.value = false
    })
  }
  if (docs.currentRightMenu === 1) {
    docs.setAiLoadingText('AI正在重新一键润色')
    PolishSettingRef.value?.createPolish();
  }
}
/**
 * AI创作删除
 */
const handleDel = () => {
  if (docs.currentRightMenu === 0) {
    actionDocument({ action: 2 })
  }
  stepPageLoading.value = false
  showEditorLoading.value = false
  successText.value = '';
  showEditorResult.value = false;
}

function selectionChange() {
  // 当出现加载中或者结果，不记录鼠标位置
  if (showEditorResult.value || showEditorLoading.value) return
  const res: any = getBestSelectionPosition()
  if (res) {
    editorPosY.value = res.top + res.height - 50
  }
}

function getBestSelectionPosition() {
  const selection: any = window.getSelection()
  if (!selection.rangeCount) return null
  const range = selection.getRangeAt(0)
  const rects = Array.from(range.getClientRects())
  if (rects.length) {
    return rects[rects.length - 1]
  }
  return null
}

const initValue: any = ref({})
const isEdit = computed(() => query?.id)
const getDetail = async () => {
  if (!isEdit.value) return false
  try {
    stepPageLoading.value = true
    const result: any = await api.zhinengxiezuo.getDetail13({ id: <number>query?.id })
    referenceDetail.value = result;
    referenceSource.value = result.referenceSource || '01';
    referenceContent.value = result.context || '';
    if (result.referenceSource === '01') {
      associationData.value = result.knowledgeResultVOS || []
    } else if (result.referenceSource === '02') {
      associationData.value = result.documentResultVOS || []
    } else if (result.referenceSource === '03') {

    }
    const data = await getDocumentItem(<string>query?.id)
    docs.setCurrentSceneType(data.data.official_document_type)
    docs.setCurrentScene(data.data.template_id)
    docs.setDocumentId(<string>query?.id)
    pageTitle.value = data.data.title;
    formData.value = data.data.basic_info
    outlineData.value = data.data.outline
    initValue.value = cloneDeep({
      scene: data.data.template_id,
      basic_info: data.data.basic_info,
      outline: data.data.outline,
      reference: (data.data.reference || []).map((v: any) => v.id),
      referenceSource: referenceSource.value
    })
    if (!isEmpty(data.data.reference)) {
      reference.value.material = filter(data.data.reference, (v: any) => v.file_type === 0)[0]
      reference.value.data = filter(data.data.reference, (v: any) => v.file_type === 1)[0]
      initValue.value.reference = cloneDeep([reference.value.material?.id, reference.value.data?.id])
    }
    if (!isEmpty(associationData.value)) {
      initValue.value.associationData = cloneDeep(associationData.value)
    }

    if (data.data.content) {
      aiEditor?.setMarkdownContent(data.data.content)
      writingStatus.value = 'applyDocs'
    }
    docs.setCurrentAiWritingStep(3)
    stepPageLoading.value = false
  } catch (e) {
    stepPageLoading.value = false
    console.log(e)
  }
}
// 下载文件
const download = async () => {
  try {
    const content = aiEditor?.getMarkdown().replace(/\\./g,'.')
    await saveDocumentItem({
      content,
      template_id: docs.currentScene,
      title: pageTitle.value
    })
    const res = await downloadDocument();
    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });

    const downloadLink = document.createElement('a');
    downloadLink.href = window.URL.createObjectURL(blob);
    downloadLink.download = `${pageTitle.value || initValue.value.basic_info['标题']}.docx`;

    document.body.appendChild(downloadLink);

    // 触发下载
    downloadLink.click();

    // 移除链接
    document.body.removeChild(downloadLink);

    // 释放URL对象
    window.URL.revokeObjectURL(downloadLink.href);
  } catch (error) {
    console.error('下载文件时发生错误:', error);
    MsgWarning('文件下载失败，请稍后重试！');
  }
}
// 保存文件
const saveDocument = async () => {
  const content = aiEditor?.getMarkdown().replace(/\\./g,'.')
  await saveDocumentItem({
    content,
    template_id: docs.currentScene,
    title: pageTitle.value
  })
  ElMessage.success('保存成功！')
  await getDetail()
}

// 延时删除浮动菜单
const delayedDeleteFloatingMenu = () => {
  setTimeout(()=> {
    // @ts-ignore
    if (document.querySelector('.aie-container').lastChild.getAttribute('data-tippy-root') !== null) {
      // @ts-ignore
      document.querySelector('.aie-container').lastChild.remove()
    }
  }, 100)
}


onMounted(() => {
  document.addEventListener('selectionchange', selectionChange)
  aiEditor = new AiEditor({
    element: editorRef.value as Element,
    placeholder: '在左侧使用AI生成文章或直接输入文字',
    toolbarKeys: [
      'undo',
      'redo',
      'eraser',
      'heading',
      'font-size',
      'bold',
      'italic',
      'strike',
      'underline',
      'font-family',
      'font-color',
      'align',
      'bullet-list',
      'ordered-list',
      'indent-decrease',
      'indent-increase'
    ],
    content: '',
    draggable: false,
    textSelectionBubbleMenu: {
      enable: true,
      items: [
        {
          id: 'PolishSvg',
          title: '',
          icon:
            '<div class="editor-menu-icon" style="user-select: none;"> <img src="' +
            PolishSvg +
            '" alt=""> <span>AI润色</span> </div>',
          onClick(e) {
            docs.setCurrentRightMenu(1)
            docs.setCurrentPolish(1)
          }
        },
        {
          id: 'ExpansionSvg',
          title: '',
          icon:
            '<div class="editor-menu-icon"> <img src="' +
            ExpansionSvg +
            '" alt=""> <span>AI扩写</span> </div>',
          onClick() {
            docs.setCurrentRightMenu(1)
            docs.setCurrentPolish(2)
          }
        },
        {
          id: 'AbbreviationsSvg',
          title: '',
          icon:
            '<div class="editor-menu-icon"> <img src="' +
            AbbreviationsSvg +
            '" alt=""> <span>AI缩写</span> </div>',
          onClick() {
            docs.setCurrentRightMenu(1)
            docs.setCurrentPolish(3)
          }
        }
      ]
    },
    onChange: (aiEditor) => {
      aiEditorTextLen.value = aiEditor.getText()?.length
    }
  })
  getDetail()
})

function back() {
  // 编辑时徐判断是否有修改
  if (isEdit.value) {
    const result = {
      scene: docs.currentScene,
      basic_info: formData.value,
      outline: outlineData.value,
      reference: compact([reference.value.material?.id, reference.value.data?.id]),
      referenceSource: referenceSource.value,
      associationData: associationData.value,
    }
    if (JSON.stringify(result) !== JSON.stringify(initValue.value)) {
      return MsgConfirm('提示', '已修改的内容未保存，是否确定退出？').then(() => {
        router.go(-1)
      })
    }
  } else if (!!docs.currentScene || !isEmpty(formData.value) || !isEmpty(outlineData.value) || !isEmpty(reference.value.material) || !isEmpty(reference.value.data)) {
    return MsgConfirm('提示', '已修改的内容未保存，是否确定退出？').then(() => {
      router.go(-1)
    })
  }
  router.go(-1)
}

const handleClickBefore = () => {
  if (showEditorLoading.value || !aiEditor?.getText()) {
    MsgWarning('请先创作或输入文章，再体验AI工具！')
    return true;
  }
  return false
}

onUnmounted(() => {
  aiEditor && aiEditor.destroy()
})
</script>
<style scoped lang="scss">
.writing-container {
  width: 100%;
  height: 100vh;
  background: #f4f8ff;

  .header {
    height: 60px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    border-radius: 24px 24px 0 0;
    padding-left: 32px;
    padding-right: 28px;

    .left {
      font-size: 18px;
      font-weight: bold;
      width: 70%;
      align-items: center;
      display: flex;
    }
  }

  .bottom-content {
    padding-top: 20px;
    padding-bottom: 20px;
    padding-left: 20px;
    height: calc(100vh - 100px);
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    .left-content {
      flex: 1;
      border-radius: 24px;
      display: flex;

      .editor {
        width: 70%;

        .aie-container {
          border-radius: 20px;
          position: relative;

          .text-count {
            width: calc(100% - 20px);
            height: 50px;
            line-height: 50px;
            background: #fff;
            position: absolute;
            left: 10px;
            bottom: 0;
            font-weight: 400;
            font-size: 14px;
            color: #999999;
            z-index: 100;
          }

          .editor-result-status {
            position: absolute;
            z-index: 1000;
            width: calc(100% - 120px);
            left: 55px;
            background: #fff;
          }

          .mask {
            position: absolute;
            width: 100%;
            height: 100%;
            z-index: 100;
          }
        }
      }

      .steps {
        width: 30%;
        border-right: 2px solid #eaeef5;
        box-sizing: border-box;

        .step-page {
          overflow-x: hidden;
          &-doc {
            max-height: 200px;
            overflow-y: auto;
            &-item {
              padding: 6px 12px;
              border: 1px solid rgba(0,0,0,0.1);
              border-radius: 4px;
              margin-bottom: 4px;
              font-weight: 400;
              font-size: 12px;
              color: #333333;
              line-height: 20px;
              display: flex;
              justify-content: space-between;
              align-items: center;
            }
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.writing-container {
  //.el-loading-mask {
  //  background: transparent;
  //}

  .pointer {
    cursor: pointer;
  }

  .el-step__icon {
    background: #fff !important;
  }

  .el-step__title {
    font-weight: 400;
    font-size: 12px;
    line-height: 18px;
    margin-top: 5px;
  }

  .el-step__head.is-wait .el-step__icon-inner,
  .el-step__title.is-wait {
    color: var(--el-color-primary) !important;
  }

  .el-step.is-horizontal .el-step__line {
    height: 5px !important;
    top: 10px !important;
    background: #fff !important;
  }

  .el-step__icon.is-text {
    border-color: transparent;
  }

  .el-step__line-inner {
    border-width: 4px !important;
  }

  .el-step__head.is-finish .el-step__line-inner {
    width: 100% !important;
  }

  .el-step__head.is-finish .el-step__icon.is-text {
    color: #ffffff;
    border-color: var(--el-color-primary) !important;
    background: var(--el-color-primary) !important;
  }

  .el-upload {
    width: 100% !important;
  }

  .el-step__title.is-process {
    color: #3067ef !important;
  }

  .editor {
    .disabled-aie-container {
      aie-header {
        .aie-menu-item {
          svg {
            fill: #ccc !important;
          }

          #text {
            color: #ccc !important;
          }
        }
      }
    }

    aie-header {
      border-radius: 20px;

      div {
        justify-content: center !important;
      }
    }

    .aie-content {
      padding: 20px 60px;
      height: calc(100% - 50px) !important;

      p {
        line-height: 36px;
      }
      ul {
        list-style: square;
      }
    }

    aie-footer {
      display: none !important;
    }

    .editor-menu-icon {
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        width: 20px;
        height: 20px;
        margin-right: 6px;
      }
    }
  }
}
</style>
