import { type AccountFormState, type PeopleModel, transformAccount } from '@/model';
import type { UserModel } from '@/model/system.model';
import request from '@/request/alova';
import router from '@/router';
import { roleMethod } from './system.api';

export interface Menu {
  label: string;
  title: string;
  key: string;
  children?: Menu[];
}

export interface AccountModel {
  token: string;
  local: PeopleModel;
  menus?: Menu[];
  permission: string[];
  user?: UserModel;
}

export function loginMethod(data: AccountFormState) {
  return request.Post<string, { access_token: string }>(`/auth/token`, data, {
    transform(data, headers) {
      return `Bearer ${data.access_token}`;
    },
  });
}

export function accountMethod(token: string) {
  return request.Get<AccountModel>(`/system/user/getInfo`, {
    headers: { Authorization: token },
    transform(data: any, headers) {
      return {
        token,
        local: transformAccount(data.user),
        permission: Array.isArray(data.permissions) ? data.permissions : [],
        user: data.user,
      };
    },
    meta: { unconvert: true },
  });
}

export function getMenusMethod(account: AccountModel) {
  const routes = new Set(router.getRoutes().map((route) => route.path));
  const transformMenus = (data: any[], prefix?: string) => {
    const menus: Menu[] = [];
    if (!Array.isArray(data)) return menus;
    for (const menu of data) {
      const path = [prefix, menu?.path].filter((v) => v != null).join('/');
      const title = menu?.meta?.title ?? path;
      const children = transformMenus(menu.children, path === '/' ? '' : path);
      if (children.length > 1) {
        menus.push({ key: path, title, label: title, children });
      } else if (children.length === 1) {
        if (path === '/') {
          menus.push(children[0]);
        } else {
          menus.push({ key: path, title, label: title, children });
        }
      } else if (routes.has(path)) {
        menus.push({ key: path, title, label: title });
      }
    }
    return menus;
  };

  return request.Get<AccountModel, any[]>(`/system/menu/getRouters`, {
    headers: { Authorization: account.token },
    transform(data) {
      // data[5].children.push(
      //   {
      //     path: 'shipment',
      //     meta: { title: '发货' },
      //   },
      //   {
      //     path: 'revenueSharing',
      //     meta: { title: '分账' },
      //   },
      // );
      //   console.log(data, 'push之后的data', transformMenus(data));
      return { ...account, menus: transformMenus(data) };
    },
  });
}
