<script setup lang="ts">
import { computed } from 'vue';

defineOptions({ name: 'UserPickerTrigger' });

interface Props {
  selectedUsers: Api.SystemManage.UserSimple[];
  placeholder: string;
  multiple: boolean;
  disabled: boolean;
  size: 'default' | 'small' | 'large';
}

const props = defineProps<Props>();
const emit = defineEmits<{ (e: 'open'): void }>();

const displayText = computed(() => {
  if (!props.selectedUsers.length) return '';
  if (!props.multiple) return props.selectedUsers[0]?.nickname ?? '';
  const head = props.selectedUsers
    .slice(0, 2)
    .map(u => u.nickname)
    .join('、');
  const rest = props.selectedUsers.length - 2;
  return rest > 0 ? `${head} +${rest}` : head;
});

const sizeClass = computed(() => `is-${props.size}`);

function handleClick() {
  if (props.disabled) return;
  emit('open');
}
</script>

<template>
  <div
    class="user-picker-trigger"
    :class="[sizeClass, { 'is-disabled': disabled }]"
    role="button"
    tabindex="0"
    @click="handleClick"
    @keydown.enter.prevent="handleClick"
    @keydown.space.prevent="handleClick"
  >
    <span v-if="displayText" class="user-picker-trigger__text">{{ displayText }}</span>
    <span v-else class="user-picker-trigger__placeholder">{{ placeholder }}</span>
    <span class="user-picker-trigger__suffix">
      <icon-ep:arrow-down />
    </span>
  </div>
</template>

<style scoped>
.user-picker-trigger {
  display: inline-flex;
  align-items: center;
  width: 100%;
  min-height: 32px;
  padding: 0 30px 0 11px;
  background: var(--el-fill-color-blank);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  font-size: var(--el-font-size-base);
  color: var(--el-text-color-regular);
  cursor: pointer;
  position: relative;
  box-sizing: border-box;
  transition:
    border-color 0.15s ease,
    background-color 0.15s ease;
}

.user-picker-trigger.is-small {
  min-height: 24px;
  font-size: 12px;
}

.user-picker-trigger.is-large {
  min-height: 40px;
  font-size: 14px;
}

.user-picker-trigger:hover:not(.is-disabled) {
  border-color: var(--el-border-color-hover);
}

.user-picker-trigger:focus-visible {
  outline: none;
  border-color: var(--el-color-primary);
}

.user-picker-trigger.is-disabled {
  background: var(--el-disabled-bg-color);
  color: var(--el-disabled-text-color);
  cursor: not-allowed;
  border-color: var(--el-border-color);
}

.user-picker-trigger__text {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-picker-trigger__placeholder {
  flex: 1;
  min-width: 0;
  color: var(--el-text-color-placeholder);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-picker-trigger__suffix {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  display: inline-flex;
  color: var(--el-text-color-placeholder);
  font-size: 14px;
  pointer-events: none;
}
</style>
