<script setup lang="ts">
import RolePicker from './RolePicker.vue'
import { useCustomFieldValue } from '@vant/use'

const props = withDefaults(
  defineProps<{
    placeholder?: string
    multiple?: boolean
    disabled?: boolean
  }>(),
  {
    multiple: false,
    disabled: false,
    placeholder: '请选择角色'
  }
)
const value = defineModel<string | string[] | undefined>({ required: true })
useCustomFieldValue(() => value.value)
const rolePickerRef = ref<InstanceType<typeof RolePicker>>()
const valueArr = computed<string[]>(() => {
  if (!value.value) return []
  return Array.isArray(value.value) ? value.value : [value.value]
})
const onClose = (roleId: string) => {
  if (!value.value) return
  if (props.multiple && Array.isArray(value.value)) {
    value.value.splice(value.value.indexOf(roleId), 1)
  } else {
    value.value = undefined
  }
}
const openRolePicker = () => {
  rolePickerRef.value?.openPopup()
}
</script>

<template>
  <div class="flex-items-center flex-wrap gap7px" v-bind="$attrs">
    <slot>
      <van-button icon="plus" size="mini" class="role-but" @click="openRolePicker" />
    </slot>
    <RoleTag v-for="item in valueArr" :key="item" :roleId="item" closable @close="onClose(item)" />
    <span v-show="!value || value.length === 0" class="placeholder">
      {{ placeholder }}
    </span>
    <RolePicker ref="rolePickerRef" :multiple="multiple" v-bind="$attrs" v-model="value" />
  </div>
</template>

<style scoped lang="less">
.role-but {
  border-style: dashed;
}
.placeholder {
  color: var(--van-text-color);
  font-size: var(--van-font-size-md);
}
</style>
