<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-row />
        </a-form>
      </template>

      <template #edit>
        <BasicForm @register="registerForm" />
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { computed, defineExpose, defineProps, nextTick, reactive, ref, unref } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { saveOrUpdate } from '../AdwebEnquiry.api';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from '../AdwebEnquiry.data';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const isUpdate = ref(false);
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if (record.hasOwnProperty(key)) {
          tmpData[key] = record[key];
        }
      });
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  //提交事件
  async function submitForm() {
    confirmLoading.value = true;
    try {
      let values = await validate();

      values.siteCode = localStorage.getItem('siteCode');
      //提交表单
      let isUpdateVal = unref(isUpdate);

      await saveOrUpdate(values, isUpdateVal);
      emit('ok');
    } finally {
      confirmLoading.value = false;
      emit('ok');
    }
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
