<template>
  <ele-table-select
    ref="selectRef"
    :allow-clear="true"
    :placeholder="placeholder"
    v-model:value="selectedValue"
    value-key="customerId"
    label-key="customerName"
    :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 === 'progress'">
        <div v-for="(d, i) in progressDict" :key="i">
          <span v-if="d.value === record.progress">{{ d.label }}</span>
        </div>
      </template>
    </template>
    <!-- 表头工具栏 -->
    <template #toolbar>
      <Search @search="search" />
    </template>
  </ele-table-select>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import Search from './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 { pageCustomer, getCustomer } from '@/api/oa/customer';
  import { getDictionaryOptions } from '@/utils/common';
  import type { Customer } from '@/api/oa/customer/model';

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

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

  const selectedValue = ref<number>();
  // 获取字典数据
  const progressDict = getDictionaryOptions('customerFollowStatus');
  // 回显值
  const initValue = ref<Customer | null>(null);
  // 选择框实例
  const selectRef = ref<InstanceType<typeof EleTableSelect> | null>(null);

  // 表格配置
  const tableConfig = reactive<ProTableProps>({
    datasource: ({ page, limit, where, orders }) => {
      return pageCustomer({ ...where, ...orders, page, limit });
    },
    columns: [
      {
        title: '客户名称',
        dataIndex: 'customerName',
        showSorterTooltip: false
      }
      // {
      //   title: '状态',
      //   dataIndex: 'progress',
      //   key: 'progress'
      // }
    ],
    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 customerId = Number(props.value);
    if (!customerId) {
      return;
    }
    getCustomer(customerId).then((res) => {
      if (res) {
        initValue.value = res;
      }
    });
  };

  setInitValue();

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