<template>
  <ele-table-select
    ref="selectRef"
    :allow-clear="true"
    :placeholder="placeholder"
    v-model:value="selectedValue"
    value-key="projectId"
    label-key="projectName"
    :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 projectStatus" :key="i">
          <span v-if="d.value === record.progress">{{ d.label }}</span>
        </div>
      </template>
    </template>
    <!-- 表头工具栏 -->
    <template #toolbar>
      <ProjectSearch @search="search" />
    </template>
  </ele-table-select>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import ProjectSearch from './project-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 { pageProject, getProject } from '@/api/oa/project';
  import type { Project } from '@/api/oa/project/model';
  import { getDictionaryOptions } from '@/utils/common';

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

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

  const selectedValue = ref<number>();
  // 回显值
  const initValue = ref<Project | null>(null);
  // 选择框实例
  const selectRef = ref<InstanceType<typeof EleTableSelect> | null>(null);
  // 获取字典数据
  const projectStatus = getDictionaryOptions('projectStatus');
  // 表格配置
  const tableConfig = reactive<ProTableProps>({
    datasource: ({ page, limit, where, orders }) => {
      return pageProject({ ...where, ...orders, page, limit });
    },
    columns: [
      {
        title: '项目名称',
        dataIndex: 'projectName',
        showSorterTooltip: false
      },
      {
        title: '项目进度',
        dataIndex: 'progress',
        showSorterTooltip: false
      }
    ],
    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 projectId = Number(props.value);
    if (!projectId) {
      return;
    }
    getProject(projectId).then((res) => {
      if (res) {
        initValue.value = res;
      }
    });
  };

  setInitValue();

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