<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, onMounted } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './data';
  import { useMessage } from '@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { addApplication, updateApplication } from '@/api/application/index';

  const { createMessage } = useMessage();
  defineOptions({ name: 'MenuDrawer' });

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

  const isUpdate = ref(true);

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    // baseColProps: { lg: 12, md: 24 },
    baseColProps: { span: 24 },
  });
  const rowId = ref('');

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      const { node } = data;
      if (node.pid == 0) {
        node.type = 1;
      } else {
        node.type = 2;
      }
      setFieldsValue({
        ...node,
      });
    }
    const treeData = cloneDeep(props.treeData);
    treeData.unshift({
      id: '0',
      key: '0',
      applicationName: '根节点',
    });
    updateSchema({
      field: 'pid',
      componentProps: { treeData },
    });
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增图层' : '编辑图层'));

  async function handleSubmit() {
    try {
      const values = await validate();
      values.sortNo = Number(values.sortNo);
      // TODO custom api
      delete values.type;
      // 新增菜单
      if (!unref(isUpdate)) {
        const data = await addApplication(values);
        if (data) {
          closeModal();
          emit('success');
          return createMessage.success('新增成功');
        } else {
          return createMessage.error('新增失败');
        }
      } else {
        const data = await updateApplication(values);
        if (data) {
          closeModal();
          emit('success');
          return createMessage.success('编辑成功');
        } else {
          return createMessage.error('编辑失败');
        }
      }
    } finally {
    }
  }
</script>
