<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="30%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './organization.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getOrganizationList, saveOrUpdateOrganization } from '/@/api/system/system';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'OrganizationDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();

      const isUpdate = ref(true);
      let organizationId;

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      const { t } = useI18n(); //加载国际化

      //默认传递页面数据
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        await resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        let treeData: any[] = await getOrganizationList();

        //如果是编辑操作，设置页面数据
        if (unref(isUpdate)) {
          //为表单赋值
          await setFieldsValue(data.record);
          organizationId = Reflect.get(data.record, 'id');
          // 过滤当前选中的组织，
          (function filterTransFun(treeData: any[]) {
            treeData.forEach((item, index, arr) => {
              if (item.id === organizationId) arr.splice(index, 1);
              if (item.children.length) filterTransFun(item.children);
            });
          })(treeData);
        }
        await updateSchema({
          field: 'parentId',
          componentProps: { treeData },
        });
      });

      //得到页面标题
      const getTitle = computed(() =>
        !unref(isUpdate)
          ? t('routes.common.organization.toolCreateOrganization')
          : t('routes.common.organization.toolEditOrganization')
      );

      //提交按钮
      async function handleSubmit() {
        setDrawerProps({ confirmLoading: true });
        try {
          const values = await validate();
          if (isUpdate.value) {
            Reflect.set(values, 'id', organizationId);
          }

          await saveOrUpdateOrganization(
            { ...values, parentId: values.parentId ?? null },
            isUpdate.value
          );
          closeDrawer(); //关闭侧框
          createMessage.success(`${unref(isUpdate) ? '编辑' : '新增'}成功`);
          emit('success');
        } catch {
        } finally {
          setTimeout(() => {
            setDrawerProps({ confirmLoading: false });
          }, 300);
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
