<template>
  <BasicModal v-bind="$attrs" @@register="registerModal" :width="700" :title="getTitle" @@ok="handleSubmit">
    <BasicForm @@register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@@/components/Modal';
  import { BasicForm, useForm } from '/@@/components/Form/index';
  import { formSchema } from './data.data';
  import { add@(@Model.ClassName), update@(@Model.ClassName) } from '/@@/api/main/@(@Model.ClassName)';

  export default defineComponent({
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
@foreach (var column in Model.TableField){
if(@column.EffectType == "Upload"){
          @:if (data.record.@(@column.LowerColumnName)) {
            @:setFieldsValue({
              @:@(@column.LowerColumnName): [data.record.@(@column.LowerColumnName)Attachment],
            @:});
          @:}
}
}
        }
      });
      const getTitle = computed(() => (!unref(isUpdate) ? '新增@(@Model.BusName)' : '编辑@(@Model.BusName)'));
      async function handleSubmit() {
        try {
          var values = await validate();
@foreach (var column in Model.TableField){
if(@column.EffectType == "Upload"){
          @:if (values.@(@column.LowerColumnName)) {
            @:values = { ...values, @(@column.LowerColumnName): values.@(@column.LowerColumnName)[0].id };
          @:}
}
}
          setModalProps({ confirmLoading: true });
          if (!unref(isUpdate)) {
            await add@(@Model.ClassName)(values);
          } else {
            await update@(@Model.ClassName)(values);
          }
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
