<!-- 报告模板编辑 -->
<script setup lang="ts">
import { onMounted, ref, type Ref } from "vue";
import { useRoute } from "vue-router";
import { CompLog } from "@/libs/log.lib";
import { ChapterManager } from "@/models/report.model";
import * as reportTemplateService from "@/services/reportTemplate.service"
import * as reportTemplateLogoService from "@/services/reportTemplateLogo.service"
import ReportTemplateName from "./components/ReportTemplateName.vue"
import ReportTemplateLabel from "./components/ReportTemplateTags.vue"
import RelationCompanyInput from '../report/components/report-create/RelationCompanyInput.vue';
import ReportField from "../report/components/report-create/ReportField.vue"
import type { Chapter, ChapterType, ReportMetadataItem, ReportTemplateSave } from "@/types/report.types";
import { PlusOutlined } from "@ant-design/icons-vue";
import PageHeader from '@/components/PageHeader.vue';
import DynamicMeta from '../report/components/dynamic-meta/DynamicMeta.vue';
import ChapterTypeSelect from "../report/components/ChapterTypeSelect.vue";
import LogoComponent from "../report/components/LogoComponent.vue";
import ChapterEditor from "../report/components/ChapterEditor.vue";
import { message } from "ant-design-vue";
import { useAuthStore } from "@/stores/auth.store";

const logError = CompLog.logErr("ReportTemplateEditorView")

// 当前路由
const route = useRoute()
// 权限store
const authStore = useAuthStore()

const reportTemplate = ref<ReportTemplateSave | null>(null);

// 报告元数据
const metadata: Ref<ReportMetadataItem[]> = ref([]);
// 章节类型选择器可见状态
const chapterTypeSelectVisible = ref(false);
// 章节管理对象
const chapterManager = new ChapterManager();
// 正在保存状态
const saveLoading = ref(false);
// logo url
const logoUrl = ref<string | undefined>(undefined)

function fetchReportTemplate(id: number) {
  reportTemplateService.get(id).then((data) => {
    reportTemplate.value = data;
    chapterManager.setChapters(reportTemplate.value.chapters)
    // 设置Logo信息
    if (reportTemplate.value.id && authStore.token) {
      logoUrl.value = reportTemplateLogoService.link(reportTemplate.value.id, authStore.token)
    }
  }).catch(logError)
}

function onMetaChange(data: ReportMetadataItem[]) {
  console.log('metadata', data)
  metadata.value = data;
  if (reportTemplate.value) {
    reportTemplate.value.metadata = metadata.value;
  }
}

function onChapterTypeSelected(types: ChapterType[]) {
  chapterManager.addChapters(types);
}

function onChapterChange(index: number, data: Chapter) {
  chapterManager.setChapter(index, data);
}

function onChapterMoveUp(index: number) {
  chapterManager.moveUp(index)
}

function onChapterMoveDown(index: number) {
  chapterManager.moveDown(index)
}

function onChapterRemove(index: number) {
  chapterManager.remove(index)
}

function onSave() {
  if (reportTemplate.value) {
    saveLoading.value = true
    reportTemplateService.save(reportTemplate.value).then(() => {
      message.success("保存成功")
      saveLoading.value = false
    }).catch((err) => {
      logError(err)
      saveLoading.value = false
    });
  }
}

function onCompanyChange(companyId: number) {
  if (reportTemplate.value) {
    reportTemplate.value.companyId = companyId;
  }
}

/**
 * Logo组件上传处理函数
 * @param file 图片文件
 */
function onLogoChange(file: File) {
  if (!reportTemplate.value) {
    return;
  }
  const formData = new FormData();
  formData.append("file", file)
  formData.append("templateId", reportTemplate.value.id.toString())

  reportTemplateLogoService.upload(formData).then((resp) => {
    if (resp && reportTemplate.value && authStore.token) {
      reportTemplate.value.logoPath = resp;
      logoUrl.value = reportTemplateLogoService.link(reportTemplate.value.id, authStore.token)
      onSave()
    }
  }).catch(logError)
}

function onLogoDelete() {
  if (!reportTemplate.value || !reportTemplate.value.logoPath) {
    return;
  }
  reportTemplateLogoService.remove(reportTemplate.value.id).then((resp) => {
    if (resp) {
      if (reportTemplate.value) {
        reportTemplate.value.logoPath = ''
      }
      logoUrl.value = undefined
    }
  })
}

onMounted(() => {
  const id = parseInt(route.params.id as string)
  if (id) {
    fetchReportTemplate(id)
  }
})
</script>

<template>
  <PageHeader title="报告模板编辑" />
  <a-row :gutter="24" v-if="reportTemplate">
    <a-col :span="12">
      <a-space class="metadata-wrap" direction="vertical">
        <ReportTemplateName v-model="reportTemplate.name" />
        <ReportTemplateLabel v-model="reportTemplate.tags" />
        <RelationCompanyInput v-model:id="reportTemplate.companyId" @change="onCompanyChange" ref="relationCompanyEl" />
        <ReportField name="项目名称" v-model="reportTemplate.reportName" />
        <DynamicMeta v-model:data="reportTemplate.metadata" @change="onMetaChange" />
      </a-space>
    </a-col>
    <a-col :span="12">
      <LogoComponent @change="onLogoChange" @delete="onLogoDelete" :url="logoUrl" />
    </a-col>
  </a-row>
  <a-divider />
  <div class="chapter-wrap" v-if="reportTemplate">
    <ChapterEditor
      v-for="(item, index) in chapterManager.getChapters()"
      :title="''"
      :key="index"
      :data="item"
      :contentEditorVisible="false"
      @change="onChapterChange(index, $event)"
      @move-up="onChapterMoveUp(index)"
      @move-down="onChapterMoveDown(index)"
      @remove="onChapterRemove(index)"
    />
  </div>
  <div class="add-chapter-wrap">
    <a-button @click="() => chapterTypeSelectVisible = true">
      <plus-outlined />
      添加章节
    </a-button>
  </div>
  <div class="bottom-button-group">
    <a-space>
      <a-button type="primary" @click="onSave" :loading="saveLoading">保存</a-button>
    </a-space>
  </div>
  <ChapterTypeSelect @ok="onChapterTypeSelected" v-model:visible="chapterTypeSelectVisible" />
</template>

<style scoped lang="scss">
.metadata-wrap {
  width: 100%;
}

.add-chapter-wrap {
  margin-top: 3em;
}

.bottom-button-group {
  margin-top: 5em;
}
</style>