<template>
  <div>
    <a-input-group compact>
      <a-input
        disabled
        style="width: calc(100% - 32px)"
        v-model:value="displayValue"
        :placeholder="placeholder"
      />
      <a-button @click="openEdit">
        <template #icon><BulbOutlined class="ele-text-warning" /></template>
      </a-button>
    </a-input-group>
    <!-- 选择弹窗 -->
    <select-data
      v-model:visible="showEdit"
      :data="current"
      :title="placeholder"
      :organizationId="organizationId"
      @done="onChange"
    />
  </div>
</template>

<script lang="ts" setup>
  import { BulbOutlined } from '@ant-design/icons-vue';
  import { ref, watch } from 'vue';
  import SelectData from './components/select-data.vue';
  import { User } from '@/api/system/user/model';

const props = withDefaults(
    defineProps<{
      value?: unknown;
      placeholder?: string;
      organizationId?: number;
    }>(),
    {
      placeholder: '请选择'
    }
  );

  const emit = defineEmits<{
    (e: 'update:value', value: unknown): void;
    (e: 'done', user: User): void;
    (e: 'clear'): void;
  }>();

  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 当前编辑数据
  const current = ref<User | null>(null);
  const displayValue = ref('');

  const formatDisplayValue = (value: unknown) => {
    if (value == null) {
      return '';
    }
    if (Array.isArray(value)) {
      return value.filter((v) => v != null && `${v}` !== '').join(',');
    }
    if (typeof value === 'object') {
      const record = value as any;
      return (
        record.nickname ??
        record.realName ??
        record.name ??
        record.label ??
        record.value ??
        ''
      );
    }
    return `${value}`;
  };

  watch(
    () => props.value,
    (value) => {
      displayValue.value = formatDisplayValue(value);
    },
    { immediate: true }
  );

  /* 打开编辑弹窗 */
  const openEdit = (row?: User) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  const onChange = (row?: User) => {
    if (row) {
      displayValue.value = row.nickname ?? row.realName ?? '';
      emit('update:value', displayValue.value);
      emit('done', row);
      return;
    }
    displayValue.value = '';
    emit('update:value', '');
    emit('clear');
  };
  // 查询租户列表
  // const appList = ref<App[] | undefined>([]);
</script>
