import type { MenuOption } from '#/api/system/menu/model';
import type { MenuPermissionOption } from '#/views/system/role/config-data';

import { eachTree } from '@vben/utils';

import { difference } from 'lodash-es';

import { requestClient } from './request';
/**
 * @description:  contentType
 */
export enum ContentTypeEnum {
  // form-data  upload
  FORM_DATA = 'multipart/form-data;charset=UTF-8',
  // form-data qs
  FORM_URLENCODED = 'application/x-www-form-urlencoded;charset=UTF-8',
  // json
  JSON = 'application/json;charset=UTF-8',
}

/**
 * 通用下载接口 封装一层
 * @param url 请求地址
 * @param data  请求参数
 * @returns blob二进制
 */
export function commonExport(url: string, data: Record<string, any>) {
  return requestClient.post<Blob>(url, data, {
    data,
    headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED },
    isTransformResponse: false,
    responseType: 'blob',
  });
}
/**
 * 通用下载接口 封装一层
 * @param url 请求地址
 * @param data  请求参数
 * @returns blob二进制
 */
export function commonGetExport(url: string, data: Record<string, any>) {
  return requestClient.get<Blob>(url, {
    data,
    headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED },
    isTransformResponse: false,
    responseType: 'blob',
  });
}

/**
 * void方法 会直接修改原始数据
 * 将树结构转为 tree+permissions结构
 * @param menus 后台返回的menu
 */
export function menusWithPermissions(menus: MenuOption[]) {
  eachTree(menus, (item: MenuPermissionOption) => {
    if (item.children && item.children.length > 0) {
      /**
       * 所有为按钮的节点提取出来
       * 需要注意 这里需要过滤目录下直接是按钮的情况item.menuType !== 'M'
       * 将按钮往children添加而非加到permissions
       */
      const permissions = item.children.filter(
        (child: MenuOption) => child.menuType === 'F' && item.menuType !== 'M',
      );
      // 取差集
      const diffCollection = difference(item.children, permissions);
      // 更新后的children  即去除按钮
      item.children = diffCollection;

      // permissions作为字段添加到item
      const permissionsArr = permissions.map((permission) => {
        return {
          id: permission.id,
          label: permission.label,
          checked: false,
        };
      });
      item.permissions = permissionsArr;
    }
  });
}
