index.vue 2.72 KB
<script lang="ts" setup>
  import { ApiTreeSelect } from '/@/components/Form';
  import { Button } from 'ant-design-vue';
  import { getOrganizationList } from '/@/api/system/system';
  import { computed, ref, unref } from 'vue';
  import OrganizationDrawer from '/@/views/system/organization/OrganizationDrawer.vue';
  import { useDrawer } from '/@/components/Drawer';
  import { OrganizationListItem } from '/@/api/system/model/systemModel';
  import { useRole } from '/@/hooks/business/useRole';

  const [registerDrawer, { openDrawer }] = useDrawer();
  const { isCustomerUser } = useRole();

  const props = withDefaults(
    defineProps<{
      value?: string | string[];
      apiTreeSelectProps?: Recordable;
      showCreate?: boolean;
      disabled?: boolean;
    }>(),
    {
      showCreate: true,
      disabled: false,
    }
  );

  const needReload = ref(true);

  const emit = defineEmits(['change', 'optionsChange']);

  const handleOpenCreate = () => {
    openDrawer(true, { isUpdate: false });
  };

  const timespan = ref(Date.now());

  const orgList = ref<Recordable[]>([]);

  const getBindProps = computed<Recordable>(() => {
    const { value, apiTreeSelectProps = {}, disabled } = props;
    const { params = {} } = apiTreeSelectProps;
    return {
      replaceFields: { children: 'children', key: 'id', title: 'name', value: 'id' },
      getPopupContainer: () => document.body,
      placeholder: '请选择所属组织',
      maxLength: 250,
      disabled,
      ...apiTreeSelectProps,
      value,
      dropdownStyle: { maxHeight: '300px' },
      api: async (params: OrganizationListItem) => {
        try {
          if (!unref(needReload)) return unref(orgList);
          const result = ((await getOrganizationList(params)) as unknown as Recordable[]) || [];
          orgList.value = result;
          needReload.value = false;
          return result;
        } catch (error) {
          return unref(orgList);
        }
      },
      params: {
        ...params,
        _t: unref(timespan),
      },
      onChange: (...args: any[]) => {
        emit('change', ...args);
      },
      onOptionsChange: (...args: any[]) => emit('optionsChange', ...args),
    };
  });

  const getShowCreate = computed(() => {
    const { showCreate } = props;
    return unref(isCustomerUser) ? false : showCreate;
  });

  const handleReload = () => {
    needReload.value = true;
    timespan.value = Date.now();
  };
</script>

<template>
  <section class="flex">
    <ApiTreeSelect v-bind="getBindProps" />
    <Button v-if="getShowCreate" type="link" @click="handleOpenCreate" :disabled="disabled"
      >新增组织</Button
    >
    <OrganizationDrawer v-if="getShowCreate" @register="registerDrawer" @success="handleReload" />
  </section>
</template>