<template>
  <n-form
    ref="formInst"
    v-bind="props"
    :model="formModelValue"
  >
    <n-grid v-bind="props.gridProps">
      <n-form-item-gi
        v-for="(item, field) in formOptions"
        :key="field"
        v-bind="item"
      >
        <template #label>
          <label style="display: inline-flex; align-items: center">
            <span>
              {{ item.label }}
            </span>
            <template v-if="item.remarkRender">
              <n-popover trigger="hover">
                <template #trigger>
                  <Icon
                    name="LucideCircleHelp"
                    color="#ff4a36"
                    :size="18"
                  />
                </template>
                <template #default>
                  <component :is="item.remarkRender" />
                </template>
              </n-popover>
            </template>
          </label>
        </template>
        <component
          :is="FormSupportComp[item.type](formModelValue, field, item)"
        />
      </n-form-item-gi>
    </n-grid>
  </n-form>
</template>

<script setup lang="ts" generic="T extends FormModelValue">
  import { computed, useTemplateRef } from "vue";
  import { formProProps, universalValidator } from "./FormPro";
  import type { FormModelValue, FormProInst } from "./indexface";
  import type { FormInst } from "naive-ui";
  import FormSupportComp from "./FormSupportComp";
  import { cloneDeep } from "lodash-es";
  import { Icon } from "@/components/icon";

  //表单实例
  const formRef = useTemplateRef<FormInst>("formInst");

  const props = defineProps(formProProps);

  const formModelValue = defineModel<T>("value", { default: {} });

  //初始化一些配置属性
  const formOptions = computed(() => {
    if (!props.formItemOptions) {
      return {};
    }
    return Object.fromEntries(
      Object.entries(props.formItemOptions).map(([key, value]) => {
        const item = cloneDeep(value);
        item.path = key;
        //设置默认校验规则 rule优先级更高
        item.required &&
          !item.rule &&
          (item.rule = {
            required: true,
            message: `${item.label}不能为空`,
            validator: universalValidator,
            trigger: "blur",
          });
        //初始化组件配置
        !item.componentsProps && (item.componentsProps = {});
        //设置提示词
        !item.componentsProps.placeholder &&
          (item.componentsProps.placeholder = item.type.includes("input")
            ? `请输入${item.label}`
            : `请选择${item.label}`);
        //默认可清除
        item.componentsProps?.clearable ??
          (item.componentsProps.clearable = true);
        return [key, item];
      })
    );
  });

  defineExpose<FormProInst>({
    validate: () => formRef.value!.validate(),
    restoreValidation: () => formRef.value!.restoreValidation(),
  });
</script>

<style scoped></style>
