<template>
  <div>
    <SelectPost :selectedIds="selectedIds" :multiple="true" @change="submit">
      <slot></slot>
      <a-button type="primary" v-if="!hasSlot">{{ t('添加岗位') }}</a-button>
    </SelectPost>
  </div>
</template>

<script setup lang="ts">
  import { computed, useSlots } from 'vue';
  import { getPostMulti } from '/@/api/system/post';
  import { SelectPost } from '/@/components/SelectOrganizational/index';
  import { MemberType } from '/@/enums/workflowEnum';
  import { MemberConfig } from '/@/model/workflow/memberSetting';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const emits = defineEmits(['change']);
  const props = withDefaults(
    defineProps<{
      memberList: Array<MemberConfig>;
    }>(),
    {
      memberList: () => {
        return [];
      },
    },
  );

  const hasSlot = computed(() => {
    return !!useSlots().default;
  });
  let selectedIds = computed(() => {
    if (props.memberList && props.memberList.length > 0) {
      return props.memberList
        .filter((ele: MemberConfig) => {
          return ele.memberType === MemberType.POST;
        })
        .map((ele: MemberConfig) => {
          return ele.id;
        });
    } else {
      return [];
    }
  });

  async function submit(ids: Array<string>) {
    let list: Array<MemberConfig> = [];
    if (props.memberList && props.memberList.length > 0) {
      props.memberList.forEach((ele) => {
        if (ele.memberType != MemberType.POST) list.push(ele);
      });
    }
    try {
      let postRes = await getPostMulti(ids.join(','));
      if (postRes.length > 0) {
        postRes.forEach((ele) => {
          list.push({
            name: ele.name,
            id: ele.id,
            memberType: MemberType.POST,
          });
        });
      }
    } catch (error) {
      ids.forEach((id) => {
        if (id)
          list.push({
            name: id,
            id: id,
            memberType: MemberType.POST,
          });
      });
    }
    emits('change', list);
  }
</script>
