import { useRoute } from 'vue-router';

import { getPostList } from '#/api/system/post/post';

/**
 * 过滤岗位数据
 * @param directoryType 目录类型
 * @param type 类型参数
 * @param allPositions 所有岗位数据
 * @returns 过滤后的岗位数据
 */
export const filterPositions = (
  directoryType: string,
  type: string,
  allPositions: any[],
) => {
  if (!Array.isArray(allPositions)) {
    return [];
  }

  // 规则1: directoryType 等于 operational, hsse_management, data_quality, financial 或 human_resources
  if (
    [
      'data_quality',
      'financial',
      'hsse_management',
      'human_resources',
      'operational',
    ].includes(directoryType)
  ) {
    return allPositions.filter((item: any) =>
      ['employee', 'management', 'region'].includes(item.type),
    );
  }

  // 规则2: directoryType 等于 visitor_feedback
  if (directoryType === 'visitor_feedback') {
    return allPositions.filter((item: any) =>
      ['headquarters', 'region'].includes(item.type),
    );
  }

  // 规则3: directoryType 等于 temporary_task, type 等于 station
  if (directoryType === 'temporary_task' && type === 'station') {
    return allPositions.filter((item: any) =>
      ['employee', 'management'].includes(item.type),
    );
  }

  // 规则4: directoryType 等于 temporary_task, type 等于 visitor
  if (directoryType === 'temporary_task' && type === 'visitor') {
    return allPositions.filter((item: any) => item.type === 'headquarters');
  }

  // 规则5: directoryType 等于 headquarters_area, type 等于 check
  if (directoryType === 'headquarters_area' && type === 'check') {
    return allPositions.filter((item: any) => item.type === 'headquarters');
  }

  // 规则6: directoryType 等于 headquarters_area, type 等于 attach
  if (directoryType === 'headquarters_area' && type === 'attach') {
    return allPositions.filter((item: any) => item.type === 'headquarters');
  }

  // 默认返回所有岗位
  return allPositions;
};

/**
 * 获取过滤后的岗位列表
 * @returns 过滤后的岗位选项
 */
export const getFilteredPositions = async () => {
  // 在运行时获取路由参数
  const route = useRoute();
  const directoryType = (route.query.directoryType as string) || '';
  const type = (route.query.type as string) || '';

  const data = await getPostList();
  const allPositions = Array.isArray(data.rows) ? data.rows : [];
  const filteredPositions = filterPositions(directoryType, type, allPositions);

  return filteredPositions.map((item: any) => ({
    label: item.postName || item.name,
    value: item.postId,
  }));
};
