<script setup lang="ts">
import { onMounted, reactive, ref } from "vue"
import type { ReportTemplateModal } from "../reportComponent.types";
import * as reportTemplateService from "@/services/reportTemplate.service"
import { CompLog } from "@/libs/log.lib";
import { message, type FormInstance, type SelectProps } from "ant-design-vue";

const logError = CompLog.logErr("TemplateSaveModal")

// 弹窗组件显示状态
const visible = ref(false)
// 确定按钮加载状态
const saving = ref(false);
// 标签值列表
const tagsOptions = ref<SelectProps['options']>([]);
// 表单ref
const templateSaveModalRef = ref<FormInstance>();
// 模板名称输入框ref
const templateNameElem = ref<HTMLInputElement | null>(null)

const emits = defineEmits<{
  (e: "ok", data: ReportTemplateModal): void
}>();

const formState = reactive<ReportTemplateModal>({
  templateName: '',
  tags: [],
});

function onTagsChange() {
  formState.tags = formState.tags.map((item) => item.trim())
}

async function onOk() {
  const templateName = (formState.templateName || '').trim()
  formState.templateName = templateName
  templateSaveModalRef.value?.validateFields()
  if (templateName == '') {
    templateNameElem.value?.focus()
    message.warning("请填写模板名称！")
    return
  }
  saving.value = true;
  emits("ok", formState);
}

onMounted(() => {
  reportTemplateService.tags().then((tags) => {
    tagsOptions.value = tags.map((tag) => ({ value: tag }))
  }).catch(logError)
});

function hide() {
  visible.value = false
  saving.value = false
}

function complete() {
  visible.value = false
  saving.value = false
}

defineExpose({
  show: () => visible.value = true,
  hide,
  complete,
})
</script>

<template>
  <a-modal v-model:visible="visible" title="另存为模板" @ok="onOk">
    <a-form
      :model="formState"
      name="templateSaveModal"
      ref="templateSaveModalRef"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 19 }"
      autocomplete="off"
      :ok-button-props="{ loading: saving }"
    >
      <a-form-item
        label="模板名称"
        name="templateName"
        :rules="[{ required: true, message: '请输入模板名称！' }]"
      >
        <a-input v-model:value="formState.templateName" ref="templateNameElem" />
      </a-form-item>

      <a-form-item
        label="标签"
        name="tags"
        :rules="[{ required: false, message: '请填写模板标签', type: 'array' }]"
      >
        <a-select
          v-model:value="formState.tags"
          mode="tags"
          :token-separators="[',', '，', ' ']"
          @change="onTagsChange"
          :options="tagsOptions"
          placeholder="模板标签，输入逗号、空格或者回车自动分割"
        ></a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
