var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/workSpaceList/index.tsx
var workSpaceList_exports = {};
__export(workSpaceList_exports, {
  default: () => workSpaceList_default
});
module.exports = __toCommonJS(workSpaceList_exports);
var import_react = __toESM(require("react"));
var import_SearchWorkspaceAndBase = __toESM(require("./components/SearchWorkspaceAndBase"));
var import_Sort = __toESM(require("./components/Sort"));
var import_WorkspaceItem = __toESM(require("./components/WorkspaceItem"));
var import_materials = require("@pisell/materials");
var import_ahooks = require("ahooks");
var import_utils = require("./../../utils/index");
var import_antd = require("antd");
var import_useEngineContext = __toESM(require("./../../hooks/useEngineContext"));
var import_react2 = require("react");
var import_index = require("./index.less");
var import_server = require("./server");
var SearchBar = (props) => {
  const { title, onAddWorkspace, onSort, className, ...rest } = props;
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "search-bar-wrap", ...rest }, /* @__PURE__ */ import_react.default.createElement("div", { className: "line-1" }, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("span", { className: "title" }, title)), /* @__PURE__ */ import_react.default.createElement(import_materials.Space, { size: 24 }, /* @__PURE__ */ import_react.default.createElement(import_SearchWorkspaceAndBase.default, null), /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { type: "primary", onClick: onAddWorkspace }, "Create a workspace"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "line-2" }, /* @__PURE__ */ import_react.default.createElement(import_Sort.default, { onChange: onSort })));
};
var defaultSize = 15;
var getTenantId = () => {
  return Number(new URLSearchParams(window.location.search).get("tenant_id") || 0);
};
var WorkspacesList = (props) => {
  const { className, ...rest } = props;
  const [sort, setSort] = (0, import_react2.useState)("");
  const [refreshKey, setRefreshKey] = (0, import_react2.useState)({});
  const context = (0, import_useEngineContext.default)();
  import_utils.request.setRequest(context.appHelper.utils.request);
  const tenant_id = getTenantId();
  const scrollRef = (0, import_react2.useRef)(null);
  const {
    data = {},
    loading,
    mutate
  } = (0, import_ahooks.useRequest)(
    async (params) => {
      const newParams = params || {
        tenant_id,
        page: 1,
        size: defaultSize,
        order_by: sort
      };
      const { code, data: data2 } = await (0, import_server.getWorkspaces)({
        tenant_id,
        page: newParams.page,
        size: newParams.size,
        order_by: newParams.order_by
      });
      return {
        tenant_id,
        list: code === 200 ? data2.list || [] : [],
        page: newParams.page + 1,
        size: newParams.size,
        count: code === 200 ? data2.count || 0 : 0,
        order_by: newParams.order_by
      };
    },
    {
      defaultParams: [
        {
          page: 1,
          size: defaultSize,
          tenant_id,
          order_by: sort
        }
      ],
      ref: scrollRef,
      isNoMore: (d) => {
        return d ? d.list.length >= d.count : false;
      },
      refreshDeps: [sort, refreshKey]
    }
  );
  const { runAsync } = (0, import_ahooks.useRequest)(import_server.addWorkspace, {
    manual: true
  });
  const add = (0, import_ahooks.useRequest)(import_server.addBase, {
    manual: true
  });
  const handleAdd = async () => {
    var _a;
    const workspace = await runAsync({
      tenant_id
    });
    context.appHelper.utils.getApp().history.push(`/workspaces/${((_a = workspace == null ? void 0 : workspace.data) == null ? void 0 : _a.id) || "0"}?create=true`);
  };
  const handleSort = (val) => {
    setSort((val == null ? void 0 : val[0]) || "");
  };
  const handleAddBase = async (params) => {
    const { name, color, icon } = params;
    await add.run({
      name,
      color,
      icon,
      workspace_id: params.id,
      tenant_id: params.tenant_id
    });
    setRefreshKey({});
  };
  const handleDelete = (id) => {
    mutate((oldList) => {
      if (!oldList) return oldList;
      return {
        ...oldList,
        list: oldList.list.filter((item) => item.id !== id)
      };
    });
  };
  const handleUpdateBase = async (params) => {
    mutate((oldBase) => {
      if (!oldBase) return oldBase;
      const newList = oldBase.list.map((item) => {
        var _a;
        if (item.id === params.workspaceId) {
          return {
            ...item,
            base: (_a = item.base) == null ? void 0 : _a.map((bas) => {
              if (bas.id === params.id) {
                return {
                  ...bas,
                  ...params
                };
              }
              return bas;
            })
          };
        }
        return item;
      });
      return {
        ...oldBase,
        list: newList
      };
    });
    await (0, import_server.updateBaseDetail)({
      id: params.id,
      color: params == null ? void 0 : params.color,
      icon: params == null ? void 0 : params.icon,
      name: params == null ? void 0 : params.name
    });
  };
  const renderWorkspaceItem = (item) => /* @__PURE__ */ import_react.default.createElement(
    import_WorkspaceItem.default,
    {
      key: item.id,
      id: item.id,
      title: item.name,
      loading: false,
      describe: item.description,
      data: item.base || [],
      onRefresh: () => setRefreshKey({}),
      onDelete: () => handleDelete(item.id),
      baseCount: item.base_count,
      onUpdateBase: (params) => handleUpdateBase({
        ...params,
        workspaceId: item.id
      }),
      onAddBase: (params) => handleAddBase({
        ...item,
        ...params
      })
    }
  );
  const content = (0, import_react2.useMemo)(() => {
    var _a;
    if (loading) {
      return /* @__PURE__ */ import_react.default.createElement(import_materials.Skeleton, null);
    }
    if ((_a = data.list) == null ? void 0 : _a.length) {
      return data.list.map(renderWorkspaceItem);
    }
    return /* @__PURE__ */ import_react.default.createElement(import_antd.Empty, null);
  }, [loading, data]);
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "workspaces-wrap", ...rest }, /* @__PURE__ */ import_react.default.createElement(
    SearchBar,
    {
      title: "All Workspaces",
      onAddWorkspace: handleAdd,
      onSort: handleSort
    }
  ), /* @__PURE__ */ import_react.default.createElement("div", { className: "workspaces-list", ref: scrollRef }, content));
};
var workSpaceList_default = WorkspacesList;
