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/productExtension/fields/SelectResourcesTable/index.tsx
var SelectResourcesTable_exports = {};
__export(SelectResourcesTable_exports, {
  default: () => SelectResourcesTable_default
});
module.exports = __toCommonJS(SelectResourcesTable_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_server = require("./server");
var import_index = require("./index.less");
var sortArrayByOrder = (arr1, arr2, reverse) => {
  return (arr1 || []).sort((a, b) => {
    let _a = arr2.findIndex((item) => item.form_id === a.form_id);
    let _b = arr2.findIndex((item) => item.form_id === b.form_id);
    return reverse ? _b - _a : _a - _b;
  });
};
var SelectResourcesTable = ({ value, onChange }) => {
  const Dom = window.BaseMaterials.Table;
  const [data, setData] = (0, import_react.useState)([]);
  const _getData = async () => {
    let _getFormTypes = (0, import_server.getFormTypes)(
      { type: "manual", num: 500, skip: 1, status: "published" },
      { useCache: true }
    );
    let _getAllResource = (0, import_server.getAllResource)(
      { num: 500, skip: 1 },
      { useCache: true }
    );
    const [forms, resources] = await Promise.all([
      _getFormTypes,
      _getAllResource
    ]);
    let defaultResourceId = getDefaultResourceId();
    let _data = (forms || []).reduce((arr, item) => {
      const currentResource = (resources || []).filter(
        (relation) => relation.form_id === item.id
      );
      if (currentResource.length > 0) {
        if (defaultResourceId && currentResource.some((d) => d.id == defaultResourceId)) {
          _onChange([defaultResourceId], item.id);
          removeDefaultResourceId();
          defaultResourceId = void 0;
        }
        arr.push({
          label: item.title,
          key: item.id,
          value: item.id,
          options: currentResource,
          // 统一字段,方便后面处理
          ...item,
          form_id: item.id
        });
      }
      return arr;
    }, []);
    setData(_data);
  };
  const getDefaultResourceId = () => {
    let serviceParams = sessionStorage.getItem(
      "pisell2.eventBooking.serviceParams"
    );
    if (serviceParams) {
      serviceParams = JSON.parse(serviceParams);
    }
    let resource_id = serviceParams == null ? void 0 : serviceParams.resource_id;
    if (resource_id) {
      resource_id = Number(resource_id);
    }
    return resource_id;
  };
  const removeDefaultResourceId = () => {
    sessionStorage.setItem("pisell2.eventBooking.serviceParams", "");
  };
  const _dataSource = (0, import_react.useMemo)(() => {
    if (value) {
      let sortOrder = {};
      let arr1Copy = data.slice();
      value.forEach((item, index) => {
        sortOrder[item.form_id] = index;
      });
      arr1Copy.sort((a, b) => {
        if (sortOrder[a.form_id] !== void 0 && sortOrder[b.form_id] !== void 0) {
          return sortOrder[a.form_id] - sortOrder[b.form_id];
        }
        if (sortOrder[a.form_id] !== void 0) {
          return -1;
        }
        if (sortOrder[b.form_id] !== void 0) {
          return 1;
        }
        return 0;
      });
      return arr1Copy;
    }
    return data;
  }, [data, value]);
  const _onChange = (val, form_id) => {
    let _value = JSON.parse(JSON.stringify(value || []));
    let cur = _value.find((d) => d.form_id === form_id);
    if (cur) {
      cur.form_record_ids = val;
    } else {
      _value.push({ form_id, form_record_ids: val });
    }
    onChange == null ? void 0 : onChange(_value);
  };
  console.log("value", value);
  const columns = (0, import_react.useMemo)(() => {
    return [
      {
        title: import_utils.locales.getText("pisell2.text.product-extension.resource-type"),
        dataIndex: "title",
        value,
        data,
        width: 100
      },
      // {
      // 	title: locales.getText("pisell2.text.product-extension.open"),
      // 	dataIndex: "open",
      // 	width: 80,
      // 	render: (text: any, record: any, index: number) => {
      // 		let cur = value?.find((d: any) => d.form_id === record.form_id);
      // 		let bol = !!(cur?.form_record_ids || []).length;
      // 		return (
      // 			<Switch
      // 				disabled={!bol}
      // 				checked={bol}
      // 				onChange={(e) => {
      // 					_onChange([], record.id);
      // 				}}
      // 			/>
      // 		);
      // 	},
      // },
      {
        title: import_utils.locales.getText("pisell2.text.product-extension.options"),
        dataIndex: "form_id",
        render: (form_id, record, index) => {
          let cur = value == null ? void 0 : value.find((d) => d.form_id === form_id);
          return /* @__PURE__ */ import_react.default.createElement(
            import_antd.Select,
            {
              style: { width: "100%" },
              mode: "multiple",
              value: (cur == null ? void 0 : cur.form_record_ids) || [],
              options: record.options,
              popupMatchSelectWidth: false,
              fieldNames: { label: "title", value: "id" },
              onChange: (val) => {
                _onChange(val, form_id);
              }
            }
          );
        }
      }
    ];
  }, [value, _dataSource]);
  const sortChange = (detail) => {
    if (value && value.length) {
      onChange == null ? void 0 : onChange(sortArrayByOrder(value, detail.dataSource));
    }
  };
  (0, import_react.useEffect)(() => {
    _getData();
  }, []);
  return /* @__PURE__ */ import_react.default.createElement(
    Dom,
    {
      className: "",
      dragSort: true,
      onSortChange: sortChange,
      rowKey: "form_id",
      columns,
      dataSource: _dataSource,
      pagination: false,
      virtual: false,
      scroll: { x: "auto" }
    }
  );
};
var SelectResourcesTable_default = SelectResourcesTable;
