<script setup lang="ts">
import Editor from '@tinymce/tinymce-vue'
import md5 from 'blueimp-md5'
import { getSignature, uploadFile } from '@/api/base'
import { ArrowDown } from '@element-plus/icons-vue'
import { useAI } from '@/composables/useAI'
import { ElMessage } from 'element-plus'

const props = defineProps({
  height: { type: Number, default: 400 },
  hasAI: { type: Boolean, default: false },
})

const ImageUploadHandler = (blobInfo: any) =>
  new Promise((resolve, reject) => {
    const file = blobInfo.blob()
    getSignature()
      .then((response: any) => {
        const prefix = 'upload/admin/'
        const key = prefix + md5(file.name + new Date().getTime()) + file.name.substr(file.name.lastIndexOf('.'))
        const { accessid, policy, signature, host } = response
        const params = {
          key,
          host,
          OSSAccessKeyId: accessid,
          policy,
          signature,
          success_action_status: '200',
          file,
          url: `${host}/${key}`,
        }
        uploadFile(params)
          .then((res: any) => {
            resolve(res.url)
          })
          .catch(() => {
            reject('上传失败')
          })
      })
      .catch(() => {
        reject('获取Signature失败')
      })
  })

const editorRef = ref()

const init = {
  language: 'zh-Hans',
  height: props.height,
  menubar: false,
  statusbar: false,
  plugins: 'table charmap fullscreen lists link code preview quickbars',
  toolbar:
    'undo redo | fontsizeselect lineheight bold italic underline strikethrough forecolor backcolor | link quickimage image media table | align hangingindent indent outdent numlist bullist | charmap  blockquote hr fullscreen | code preview',
  // font_formats:
  //   '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Times New Roman',
  fontsize_formats: '8px 10px 12px 14px 15px 16px 17px 18px 20px 24px',
  lineheight_formats: '0.5 1 1.2 1.5 2',
  images_upload_handler: ImageUploadHandler,
  automatic_uploads: true,
  quickbars_insert_toolbar: false,
  // style_formats: [{ title: '悬挂缩进', block: 'p', styles: { textIndent: '-2em', paddingLeft: '2em' } }],
  content_style: 'img {max-width:100%;}',
  setup: (editor: any) => {
    editorRef.value = editor
  },
}

const aiDialogVisible = ref(false)
const form = reactive({
  function: '润色',
  tone: '口语化',
})

const { post, isLoading } = useAI()

const handleAI = async () => {
  const text = editorRef.value.getContent({ format: 'text' })

  if (!text.trim()) {
    ElMessage.warning('请先输入一些内容')
    return
  }

  // 根据功能生成对应的prompt
  const functionMap: any = {
    改写: `改写以上内容`,
    扩写: `扩写以上内容`,
    缩写: `缩写以上内容`,
    润色: `润色以上内容`,
  }

  const toneMap: any = {
    更正式: '请帮我使用正式、专业的语言风格',
    更活泼: '请帮我使用活泼、生动的语言风格',
    党政风: '请帮我使用党政机关公文风格',
    口语化: '请帮我使用口语化、通俗易懂的表达方式',
  }

  const prompt = `${text}\n\n${toneMap[form.tone]}${
    functionMap[form.function]
  }\n请仅返回优化后的内容，不要添加任何解释或前缀。/no_think`

  await post(
    { prompt },
    {
      onUpdate: (content) => {
        editorRef.value.setContent(content)
      },
    }
  )
}
</script>

<template>
  <div class="app-editor" style="width: 100%">
    <editor :init="init" v-bind="$attrs" style="width: 100%" />
    <div class="app-editor-ai" v-if="hasAI">
      <el-button-group size="small">
        <el-button type="primary" @click="handleAI" :loading="isLoading">AI{{ form.function }}</el-button>
        <el-button type="primary" :icon="ArrowDown" @click="aiDialogVisible = true"></el-button>
      </el-button-group>
    </div>
    <el-dialog title="AI" v-model="aiDialogVisible" width="500px">
      <el-form label-position="top">
        <el-form-item label="您需要AI辅助的功能是：">
          <el-radio-group v-model="form.function">
            <el-radio-button label="改写" value="改写" />
            <el-radio-button label="扩写" value="扩写" />
            <el-radio-button label="缩写" value="缩写" />
            <el-radio-button label="润色" value="润色" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="您需要的文本语气是：">
          <el-radio-group v-model="form.tone">
            <el-radio-button label="更正式" value="更正式" />
            <el-radio-button label="更活泼" value="更活泼" />
            <el-radio-button label="党政风" value="党政风" />
            <el-radio-button label="口语化" value="口语化" />
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.tox-tinymce-aux {
  z-index: 3000 !important;
}
.app-editor-ai {
  text-align: right;
  margin-top: 10px;
}
</style>
