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

<script setup lang="ts">
  import { computed, useSlots } from 'vue';
  import { getRoleMulti } from '/@/api/system/role';
  import { SelectRole } 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.ROLE;
        })
        .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.ROLE) list.push(ele);
      });
    }
    try {
      let roleRes = await getRoleMulti(ids.join(','));
      if (roleRes.length > 0) {
        roleRes.forEach((ele) => {
          list.push({
            name: ele.name,
            id: ele.id,
            memberType: MemberType.ROLE,
          });
        });
      }
    } catch (error) {
      ids.forEach((id) => {
        if (id)
          list.push({
            name: id,
            id: id,
            memberType: MemberType.ROLE,
          });
      });
    }

    emits('change', list);
  }
</script>
