<!-- 章节编辑器 -->

<script setup lang="ts">
import { ref, watch, type PropType } from 'vue';
import { EditOutlined, DownOutlined } from '@ant-design/icons-vue';
import { marked } from "marked";
import type { Chapter } from '@/types/report.types';
import ContentEditor from "../components/ContentEditor.vue";
import ReferenceDraw from "../components/reference/ReferenceDraw.vue";
import AIContentDraw from "../components/reference/AIContentDraw.vue";
import * as aiService from "@/services/ai.service"
import { message } from 'ant-design-vue';

const props = defineProps({
  title: {
    type: String,
    required: true,
  },
  reportKeywords: {
    type: String,
    required: false,
  },
  data: {
    type: Object as PropType<Chapter>,
    required: true
  },
  contentEditorVisible: {
    type: Boolean,
    required: false,
    default: true,
  }
});

const titleEditor = ref<HTMLInputElement | null>(null);

const titleEditing = ref(false);

const keywordsInChapter = ref('')

const keywordsEditor = ref<HTMLInputElement | null>(null);

const keywordsEditing = ref(false);

const repetitiveWarning = ref(false);

const fullTitle = ref('');
// 参考文献抽屉组件ref
const referenceDraw = ref<InstanceType<typeof ReferenceDraw> | null>(null);
// 内容编辑器组件ref
const contentEditor = ref<InstanceType<typeof ContentEditor> | null>(null)
// AI内容展示组件ref
const aiContentDraw = ref<InstanceType<typeof ReferenceDraw> | null>(null);

const emits = defineEmits<{
  (e: "update:data", data: Chapter): void;
  (e: "change", data: Chapter): void;
  (e: "moveUp"): void;
  (e: "moveDown"): void;
  (e: "remove"): void;
  (e: "sectionRecordUse", sectionId: number): void;
}>();

const visible = ref<boolean>(false);

const handleOk = () => {
  emits("remove");
  visible.value = false;
};

watch(
  () => titleEditor.value,
  (el: HTMLInputElement | null) => {
    el?.focus();
  }
);

function onEditTitle() {
  fullTitle.value = props.data.title;
  titleEditing.value = true;
}

function onEditKeywords() {
  keywordsInChapter.value = props.data.keywords.join(",");
  keywordsEditing.value = true;
}

function onTitleChange() {
  titleEditing.value = false;
  emits("change", { ...props.data, title: fullTitle.value })
}

function onKeywordsChange() {
  keywordsEditing.value = false;
  emits("change", { ...props.data, keywords: keywordsInChapter.value.split(",") })
}

function onTitleChangeCancel() {
  fullTitle.value = props.data.title;
  titleEditing.value = false;
}

function onKeywordsChangeCancel() {
  keywordsInChapter.value = props.data.keywords.join(",");
  keywordsEditing.value = false;
}

function onContentChange(value: string) {
  emits("change", { ...props.data, content: value });
}

function onMenuClick(e: { key: string }) {
  switch (e.key) {
    case "UP":
      emits("moveUp");
      break;
    case "DOWN":
      emits("moveDown");
      break;
    case "REMOVE":
      visible.value = true;
      break;
  }
}

function searchReference() {
  referenceDraw.value?.show();
}

function onInsert(text: string) {
  contentEditor.value?.insert(text)
}

function onReferenceDrawClose() {
  contentEditor.value?.focus()
}

function onSectionRecordUse(sectionId: number) {
  emits("sectionRecordUse", sectionId)
}

function notifyRepetitiveWarning(data: boolean) {
  repetitiveWarning.value = data;
}

function test1() {
  const loadingHandler = message.loading({ content: 'AI正在撰写章节内容，请稍等……', duration: 0 })
  aiService.generate(props.title, props.reportKeywords || '', props.data.title).then((resp) => {
    onContentChange(marked.parse(resp))
    if (loadingHandler) {
      loadingHandler()
    }
  }).catch((err) => {
    console.log('err', err)
    if (loadingHandler) {
      loadingHandler()
    }
  })
}

defineExpose({
  notifyRepetitiveWarning
})
</script>

<template>
  <div class="chapter-item">
    <a-row type="flex" justify="space-between">
      <a-col>
        <a-space>
          <a-input v-if="titleEditing" v-model:value="fullTitle" @blur="onTitleChange" @pressEnter="onTitleChange"
            @keyup.esc="onTitleChangeCancel" ref="titleEditor" class="title-editor" />
          <h1 v-else>
            <span>{{ data.fullTitle }}</span>
          </h1>
          <a-button type="text" @click="onEditTitle" class="edit-btn"><edit-outlined /></a-button>
        </a-space>
      </a-col>
      <a-col flex="1">
        <!-- 关键词编辑 -->
        <a-space class="keywords-wrap">
          <h1>
            <span>章节关键词：</span><span v-if="!keywordsEditing">{{ data.keywords.join(', ') }}</span>
          </h1>
          <a-input v-if="keywordsEditing" v-model:value="keywordsInChapter" @blur="onKeywordsChange"
            @pressEnter="onKeywordsChange" @keyup.esc="onKeywordsChangeCancel" ref="keywordsEditor"
            class="keywords-editor" />
          <a-button type="text" @click="onEditKeywords" class="edit-btn"><edit-outlined /></a-button>
        </a-space>
      </a-col>
      <a-col>
        <a-dropdown>
          <template #overlay>
            <a-menu @click="onMenuClick">
              <a-menu-item key="UP">上移</a-menu-item>
              <a-menu-item key="DOWN">下移</a-menu-item>
              <a-menu-item key="REMOVE">删除</a-menu-item>
            </a-menu>
          </template>
          <a-button type="link" size="small">
            操作
            <DownOutlined />
          </a-button>
        </a-dropdown>
      </a-col>
    </a-row>
    <p v-if="contentEditorVisible" :class="{ 'repetitiveWarning': repetitiveWarning }">
      <ContentEditor :data="data.content || ''" @change="onContentChange" ref="contentEditor" />
    </p>
    <div class="chapter-button-group" v-if="contentEditorVisible">
      <a-space>
        <a-button @click="test1">AI生成</a-button>
        <a-button @click="searchReference">匹配文献</a-button>
      </a-space>
    </div>
  </div>
  <ReferenceDraw :report-name="title" :reportKeywords="reportKeywords || ''" :chapter-keywords="data.keywords || []"
    ref="referenceDraw" @insert="onInsert" @close="onReferenceDrawClose" @recordUse="onSectionRecordUse" />
  <AIContentDraw content="''" ref="aiContentDraw" />
  <!--删除章节 start -->
  <a-modal v-model:visible="visible" title="删除章节" @ok="handleOk">
    <p>确认删除章节</p>
  </a-modal>
  <!-- end -->
</template>

<style scoped lang="scss">
.chapter-item {
  margin-top: 2em;

  .title-editor {
    width: 400px;
  }

  .keywords-wrap {
    font-size: 0.9em;
    display: flex;
    align-items: baseline;
    margin-left: 2em;
  }

  .keywords-editor {
    width: 400px;
  }

  .edit-btn {
    margin-left: 0.5em;
  }

  .chapter-button-group {
    text-align: right;
  }

  .repetitiveWarning {
    border: 1px solid red;
    border-radius: 8px;
  }
}
</style>