<template>
  <div class="modals">
    <BasicDrawer
      v-bind="$attrs"
      destroyOnClose
      @register="registerDrawer"
      :title="getTitle"
      @ok="handleSubmit"
      :width="780"
      :showFooter="true"
    >
      <div class="!pl-8 !pt-4">
        <BasicForm @register="registerForm" />
      </div>
    </BasicDrawer>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { dataFormSchema } from './data';

  import { articleAdd, articleById, articleEdit } from '/@/api/biz/mission/articleApi';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  const emit = defineEmits(['success', 'register']);

  const getTitle = computed(() => (!unref(isUpdate) ? '新增宣教' : '编辑宣教'));
  const isUpdate = ref(false);
  const rowId = ref();

  const { createMessage } = useMessage();
  const [registerForm, { resetFields, validate, setFieldsValue }] = useForm({
    layout: 'vertical',
    showResetButton: true,
    labelWidth: 100,
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
    baseColProps: {
      span: 12,
    },
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async data => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      const resData = await articleById(data.record.id);
      console.log('resData::::', resData);
      await setFieldsValue({
        ...resData,
      });
    }
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      !unref(isUpdate)
        ? await articleAdd({ ...values })
        : await articleEdit({ ...values, id: rowId.value });
      !unref(isUpdate) ? createMessage.success('新增成功！') : createMessage.success('编辑成功！');
      closeDrawer();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
