<script setup lang="ts">
import { onMounted, ref } from "vue";
import PageHeader from '@/components/PageHeader.vue';
import type { ReportTemplateSave } from '@/types/report.types';
import ReportTemplateQueryBox from "./components/ReportTemplateQueryBox.vue"
import type { FieldType } from "./components/ReportTemplateQueryBox.vue"
import * as reportTemplateService from "@/services/reportTemplate.service"
import * as reportService from "@/services/report.service"
import { CompLog } from "@/libs/log.lib";
import SpinComponent from "@/components/SpinComponent.vue";
import { message } from "ant-design-vue";
import { routeToReportEditor } from "@/router";

const logError = CompLog.logErr("ReportTemplateListView")

// 报告模板总数
const total = ref(0);
// 报告模板列表
const templates = ref<ReportTemplateSave[]>([])
// 加载列表的状态
const loading = ref(false)
// 当前所在页数
const currentPage = ref(1)
// 查询字段
const field = ref<FieldType>('title')
// 查询关键词
const keyword = ref('')

function fetchTemplates(field?: string, keyword?: string, page?: number) {
  loading.value = true
  reportTemplateService.list(field, keyword, page).then((resp) => {
    total.value = resp.total;
    templates.value = resp.items;
    loading.value = false
  }).catch((err) => {
    loading.value = false
    logError(err)
  })
}

function onQuery(queryData: { field: string, keyword: string }) {
  fetchTemplates(queryData.field, queryData.keyword)
}

function onPaginationChange(page: number) {
  fetchTemplates(field.value, keyword.value, page)
}

function onDelete(index: number) {
  const template = templates.value[index];
  if (template.id) {
    reportTemplateService.remove(template.id).then((deleted) => {
      if (deleted) {
        fetchTemplates()
      } else {
        logError('删除报告失败：' + template.id)
      }
    })
  } else {
    message.warning("模板ID为空，无法为您删除模板 " + template.name)
  }
}

function onCreateReport(templateId: number | undefined) {
  const msgHandler = message.loading("正在使用模板创造报告...", 120)
  if (!templateId) {
    return;
  }
  reportService.create({templateId}).then((id) => {
    routeToReportEditor(id);
    msgHandler()
    message.success("创建报告成功，正在中转到编辑页面")
  }).catch((err) => {
    msgHandler()
    logError(err);
  });
}

onMounted(() => {
  fetchTemplates();
});
</script>

<template>
  <PageHeader title="报告模板管理" />
  <div class="query-box-wrap">
    <ReportTemplateQueryBox v-model:field="field" v-model:keyword="keyword" @search="onQuery" />
  </div>
  <div class="templates-wrap">
    <SpinComponent :spinning="loading">
      <a-card hoverable v-for="(item, index) in templates" :key="index" :title="item.name" class="template-item">
        <template #extra>
          <a-button type="link" @click="onCreateReport(item.id)">使用模板创建报告</a-button>
          <RouterLink :to="{ name: 'ReportTemplateEditor', params: { id: item.id }}">编辑</RouterLink>
          <a-popconfirm
            :title="'确定删模板 ' + item.name"
            ok-text="确定"
            cancel-text="取消"
            @confirm="onDelete(index)"
            placement="topRight"
          >
            <a-button type="link">删除</a-button>
          </a-popconfirm>
        </template>
        <p v-for="(metadata, j) in item.metadata" :key="j">
          {{ metadata.name }}: {{ metadata.value }}
        </p>
        <p>标签：<a-tag v-for="(tag, k) in item.tags" :key="k">{{ tag }}</a-tag></p>
        <p>创建时间：{{ item.createAt }}</p>
        <p>更新时间：{{ item.updateAt }}</p>
      </a-card>
    </SpinComponent>
  </div>
  <div class="pagination-wrap">
    <a-pagination v-model:current="currentPage" :total="total" @change="onPaginationChange" />
  </div>
</template>

<style scoped lang="scss">
.query-box-wrap {
  width: 80%;
  margin: 0 auto;
}

.templates-wrap {
  margin-top: 2em;

  .template-item {
    margin-top: 1em;

    &:first-child {
      margin-top: 0;
    }
  }

  :deep(.ant-card) {
    background-color: #f5f5f5;

    .ant-card-head-title {
      font-size: 1.2em;
    }

    .ant-card-body p {
      margin-bottom: 0.5em;
    }

    &.ant-card-bordered {
      border: 1px solid #d0d0d0;
    }
  }
}

.pagination-wrap {
  margin-top: 1em;
  text-align: right;
}
</style>