import { httpApp } from "@/plugins/axiosApp";
import { ImportResponse, ServerPageResponse, SubOrg } from "@/types";
import { responseToFile } from "@/utils/utils";
import QueryString from "qs";

/** 机构分页查询 */
export function getSubOrgList(params: {
  code?: string;
  name?: string;
  enable?: boolean;
  rootOrgId: number;
  pageNo?: number;
  pageSize?: number;
}) {
  return httpApp.post<any, ServerPageResponse<SubOrg>>(
    "/api/ess/org/page",
    params
  );
}

/** 更新机构 */
export function updateSubOrg(params: {
  code?: string;
  enable?: boolean;
  id?: number;
  name?: string;
  rootOrgId?: number;
}) {
  return httpApp.post("/api/ess/org/save", params);
}

/** 禁用、启用机构 */
export function toggleSubOrgs(enable: boolean, ids: number[]) {
  return httpApp.post(
    `/api/ess/org/${enable ? "enable" : "disable"}`,
    new URLSearchParams([["ids", ids.join(",")]])
  );
}

/** 删除机构 */
export function delOrgs(ids: number[]) {
  return httpApp.post(
    `/api/ess/org/delete`,
    new URLSearchParams([["ids", ids.join(",")]])
  );
}

/** 导入机构 */
export function importOrgs(rootOrgId: number, file: File) {
  const f = new FormData();
  f.append("rootOrgId", rootOrgId + "");
  f.append("file", file);
  return httpApp.post<any, ImportResponse>(`/api/ess/org/import`, f);
}

/** 导出机构 */
export function exportOrgs(params: {
  rootOrgId: number;
  code: string;
  name: string;
  enable: boolean;
}) {
  return httpApp
    .get(`/api/ess/org/export?` + QueryString.stringify(params), {
      responseType: "blob",
    })
    .then(function (response) {
      return responseToFile(response);
    });
}
