<script setup lang="ts">
import type { FetchDataCallback, FetchSelectedDataCallback, PageParameters, SelectPageKey } from 'v-selectpage';
import { SelectPageList } from 'v-selectpage';
import { ref } from 'vue';

const props = withDefaults(
  defineProps<{
    load(page: number, size: number, query?: Record<string, any>): Promise<{ data: any[]; total: number }>;
    query?: Record<string, any>;
    keyProp?: string;
    labelProp?: string;
    allowCustom?: boolean; // 是否允许自定义输入
  }>(),
  {
    keyProp: 'id',
    labelProp: 'name',
    allowCustom: true,
  }
);

const emits = defineEmits<{
  update: [value: any];
  focus: [];
  blur: [];
}>();

const attrs = useAttrs() as {
  multiple?: boolean;
  debounce?: number;
};

const [modelValue] = defineModel<any, 'complex'>('value', {
  get(v: any) {
    if (!v || !v?.length) return [];
    return Array.isArray(v) ? v : [v];
  },
  set(v: SelectPageKey[]) {
    return attrs.multiple ? v : v[0];
  },
});


async function fetchData(data: PageParameters, callback: FetchDataCallback) {
  const { search: keyword, pageNumber, pageSize } = data;
  
  try {
    const { data, total } = await props.load(pageNumber, pageSize, { ...props.query, keyword });
    callback(data, total);
  } catch (e) {
    callback([], 0);
  }
}

async function fetchSelectedData(keys: SelectPageKey[], callback: FetchSelectedDataCallback) {
  if (attrs.multiple) {
    callback(
      keys.map((key) => ({
        [props.labelProp]: key,
        [props.keyProp]: key,
      }))
    );
  } else {
    try {
      const { data } = await props.load(1, 1, { keyword: keys[0] });
      callback(data);
    } catch (e) {
      callback([]);
    }
  }
}

function onSelect(items: Record<string, unknown>[]) {
  if (attrs.multiple) {
    emits('update', items);
  } else {
    emits('update', items.length > 0 ? items[0] : null);
  }
}



</script>

<template>
    <SelectPageList 
      ref="el"
      language="zh-chs"
      :debounce="attrs.debounce ?? 500"
      :multiple="attrs.multiple"
      :key-prop="props.keyProp"
      :label-prop="props.labelProp"
      v-model="modelValue"
      @fetch-data="fetchData"
      @fetch-selected-data="fetchSelectedData"
      @selection-change="onSelect"
      @visible-change="$event ? emits('focus') : emits('blur')"
    />
</template>

<style lang="scss">
.v-dropdown-trigger {
  width: 100%;

  .sp-trigger-container {
    padding: 3px 6px;
    border-radius: 6px;

    &.sp-opened,
    &:hover {
      border-color: #6bceff !important;
    }

    &.sp-opened,
    &:focus {
      border-color: #6bceff !important;
      box-shadow: 0 0 0 2px rgba(5, 205, 255, 0.06);
      border-inline-end-width: 1px;
      outline: 0;
    }
  }

  .sp-placeholder {
    color: #e0e0e0 !important;
  }
}

.enhanced-remote-select {
  position: relative;
  
  .custom-input-option {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #d9d9d9;
    border-top: none;
    border-radius: 0 0 6px 6px;
    padding: 8px 12px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #1890ff;
    font-size: 14px;
    z-index: 1000;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    
    &:hover {
      background-color: #f5f5f5;
    }
    
    .anticon {
      font-size: 12px;
    }
  }
}

// 改进下拉选项样式
:deep(.sp-dropdown) {
  .sp-option {
    &:hover {
      background-color: #f5f5f5;
    }
    
    &.sp-selected {
      background-color: #e6f7ff;
      color: #1890ff;
    }
  }
}
</style>
