import { requestHeaders } from 'helpers/login';

export function getApiUrl() {
  return window.location.origin.replace('3000', '8000');
}

export function trimString(str = '') {
  // 将多种分隔符替换成\n
  str = str.replace(/[\s,;]+/g, '\n');
  // 去掉开头和结尾的\n
  str = str.replace(/^\s+|\s+$/g, '');

  return str;
}

export async function findMany<T>(resource: string, params: Record<string, any>) {
  const url = `${getApiUrl()}/${resource}/findMany`;
  const res = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      ...requestHeaders(),
    },
    // credentials: 'include',
    body: JSON.stringify(params),
  });
  const data = await res.json();
  return data.data as T[];
}

export function getUrlParams(search = window.location.search) {
  const hashes = search.slice(search.indexOf('?') + 1).split('&');
  return hashes.reduce((acc, hash) => {
    const [key, val] = hash.split('=');
    if (val) acc[key] = decodeURIComponent(val);
    return acc;
  }, {} as Record<string, string>);
}

export interface Option {
  value: string | number;
  label: string;
  children?: Option[];
}
export function transformTaskType(originalData: Record<string, string>): Option[] {
  const result = new Map();

  for (const [key, value] of Object.entries(originalData)) {
    const parts = key.split("/");
    const platform = parts[0];
    const attribute = parts[1];

    if (!result.has(platform)) {
      result.set(platform, {
        value: platform,
        label: platform,
        children: [],
      });
    }

    result.get(platform).children.push({
      value: attribute,
      label: `${attribute}(spider_type:${value})`,
    });
  }

  return Array.from(result.values());
}
