<template>
  <el-dialog
    :model-value="visible"
    title="消息类型"
    width="800px"
    :append-to-body="true"
    :destroy-on-close="true"
    @open="onOpen"
    @close="onClose"
  >
    <el-form label-position="left">
      <el-form-item>
        <el-input type="textarea" v-model="content" :rows="15" :readonly="mode === 'show'"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div>
        <el-button @click="onClose">关闭</el-button>
        <el-button @click="onDownload">下载</el-button>
        <el-button v-if="mode !== 'show'" type="primary" @click="onSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'

import * as apis from '@/apis/heai'
import { SuccessResultCode, type HeaiMessageFlag } from '@cacp/ui'
import { ElMessage } from 'element-plus'

const emits = defineEmits<{
  (e: 'on-close'): void
}>()
const props = defineProps<{
  mode: string
  visible: boolean
  appMsgId: string
  type: boolean
  flag: HeaiMessageFlag
}>()

const content = ref('')

async function onOpen() {
  const res = await apis.getRecieve(props.appMsgId, props.type, props.flag) // getSend
  content.value = res.data.content
}

function onClose() {
  emits('on-close')
}
function onDownload() {
  const blob = new Blob([content.value], { type: 'text/plain;charset=utf-8' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.href = url
  link.download = 'HeaiMessage.txt'
  link.click()
  URL.revokeObjectURL(url)
}
async function onSave() {
  const message = {
    appMsgId: props.appMsgId,
    content: content.value
  }
  const res = await apis.updateMessage(message)
  if (res.code !== SuccessResultCode) {
    ElMessage.error('保存失败，' + res.message)
    return
  }

  ElMessage.success('保存成功')
  emits('on-close')
}
</script>

<style lang="less" scoped>
.editor {
  width: 100%;
  height: 500px;
  background-color: antiquewhite;
}
</style>
