<template>
  <ele-table-select
    ref="selectRef"
    :allow-clear="true"
    :placeholder="placeholder"
    v-model:value="selectedValue"
    value-key="managerId"
    label-key="nickname"
    :table-config="tableConfig"
    :overlay-style="{ width: '520px', maxWidth: '80%' }"
    :init-value="initValue"
    @select="onSelect"
    @clear="onClear"
  >
    <!-- 角色列 -->
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'manager'">
        <a-tooltip :title="`用户ID：${record.userId}`">
          <a-avatar :src="record.avatar" size="small" />
          <span style="padding-left: 4px">{{ record.nickname }}</span>
        </a-tooltip>
      </template>
      <template v-if="column.key === 'region'">
        {{record.province}} - {{record.city}} - {{record.area}}
      </template>
    </template>
    <!-- 表头工具栏 -->
    <template #toolbar>
      <ChooseSearch @search="search" />
    </template>
  </ele-table-select>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import ChooseSearch from './choose-search.vue';
  import type { EleTableSelect } from 'ele-admin-pro/es';
  import type { ProTableProps } from 'ele-admin-pro/es/ele-pro-table/types';
  import type { WhereType } from './types';
  import { pageManager, getManager } from '@/api/merchant/manager';
  import { Manager } from '@/api/merchant/manager/model';

  const props = withDefaults(
    defineProps<{
      value?: number | 0;
      placeholder?: string;
    }>(),
    {
      placeholder: '请选择区域经理'
    }
  );

  const emit = defineEmits<{
    (e: 'select', where?: Manager): void;
    (e: 'clear'): void;
  }>();

  const selectedValue = ref<number>();
  // 回显值
  const initValue = ref<Manager | null>(null);
  // 选择框实例
  const selectRef = ref<InstanceType<typeof EleTableSelect> | null>(null);

  // 表格配置
  const tableConfig = reactive<ProTableProps>({
    datasource: ({ page, limit, where, orders }) => {
      return pageManager({ ...where, ...orders, page, limit });
    },
    columns: [
      {
        title: '区域',
        key: 'region',
        dataIndex: 'region'
      },
      {
        title: '经理',
        key: 'manager',
        dataIndex: 'manager'
      }
    ],
    toolkit: ['reload', 'columns'],
    size: 'small',
    pageSize: 6,
    toolStyle: {
      padding: '0 8px'
    }
  });

  // 搜索
  const search = (where: WhereType) => {
    selectRef.value?.reload({
      where,
      page: 1
    });
  };

  const onClear = () => {
    emit('clear');
  };

  const onSelect = (item) => {
    emit('select', item);
  };

  /* 回显数据 */
  const setInitValue = () => {
    const managerId = Number(props.value);
    if (!managerId) {
      return;
    }
    getManager(managerId).then((res) => {
      if (res) {
        initValue.value = res;
      }
    });
  };

  setInitValue();

  watch(
    () => props.value,
    (value) => {
      if (value) {
        setInitValue();
      }
    }
  );
</script>
