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

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

<script lang="ts" setup>
  import { computed, defineExpose, defineProps, nextTick, ref, unref } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { saveOrUpdate } from '../AdwebTheme.api';
  import { BasicForm, useForm } from '@/components/Form';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { formSchema } from '@/views/adweb/theme/AdwebTheme.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 { createMessage } = useMessage();
  const isUpdate = ref(false);
  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 [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) {
    Object.keys(record).length === 0 ? (isUpdate.value = false) : (isUpdate.value = true);

    nextTick(() => {
      resetFields();
      setFieldsValue({
        ...record,
      });
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      let values = await validate();

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

      confirmLoading.value = true;
      let results = await saveOrUpdate(values, isUpdateVal);

      if (results.code === 200) {
        emit('ok');
        createMessage.success('模板添加成功');
      } else {
        createMessage.error(results.message);
      }

      emit('ok');
    } finally {
      confirmLoading.value = false;
    }
  }

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

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