<template>
  <div class="c-modal-form">
    <c-modal
      :destroyOnClose="true"
      v-bind="$attrs"
      :title="title"
      :maskClosable="maskClosable"
      v-model:visible="visibleModel"
    >
      <c-dynamic-form
        ref="df"
        :form-schema="formSchema"
        :initial-values="formData"
         @keyup.enter.native="save"
      >
        <template
          v-for="(item, key, index) in $slots"
          :key="index"
          v-slot:[key]
        >
          <slot :name="key"></slot>
        </template>
      </c-dynamic-form>
      <template #footer>
        <a-button key="back" @click="() => (visibleModel = false)">{{
          $cyt("取消")
        }}</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="confirmLoading"
          @click="save"
          >{{ $cyt("保存") }}</a-button
        >
      </template>
    </c-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "c-modal-form",
});
</script>

<script setup lang="ts">
import { ref, PropType } from "vue";
import { useVModel } from "@vueuse/core";
import { FormItemSchema, FormSchema } from "../../CDynamicForm";
import CDynamicForm from "../../CDynamicForm/schema-form.vue";
const emit = defineEmits(["save"]);
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  /**
   * 点击蒙层是否允许关闭
   */
  maskClosable: {
    type: Boolean,
    default: false,
  },
  /**
   * @description 弹出框title
   */
  title: {
    type: String,
    default: "",
  },
  /**
   * @description 表单字段
   */
  fields: {
    type: Array as PropType<FormItemSchema<any>[]>,
  },
  /**
   *  @description 表单初始化数据 用于编辑页面传入 模型数据
   */
  formData: {
    type: Object,
    required: false,
  },
  formConfig: {
    type: Object as PropType<FormSchema>,
    required: false,
  },
  /**
   * @description 保存按钮loading
   */
  confirmLoading: {
    type: Boolean,
    required: false,
  },
});

const visibleModel = useVModel(props, "show");
const df = ref<InstanceType<typeof CDynamicForm>>();
// const uiData = reactive({
//   confirmLoading: false,
// });
const formSchema: FormSchema = {
  rowProps: { gutter: 25 },
  schemas: props.fields || [],
};

/**
 * @description 设置表单数据
 * @param formData
 */
const setFieldsValue = (formData: any) => {
  (df.value as any).setFieldsValue(formData);
};
/**
 * 保存保单
 */
const save = async () => {
  const formModel = await (df.value as any).validate();
  emit("save", formModel);
};

/**
 * @description 用于更新form item 数据
 */
const updateSchema = (
  data: Partial<FormItemSchema> | Partial<FormItemSchema>[]
) => {
  (df.value as any).updateSchema(data);
};
defineExpose({
  setFieldsValue,
  updateSchema,
});
</script>

<style lang="less" scoped>
.c-modal-form {
}
</style>
