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/plus/walletEditor/WalletEditor.tsx
var WalletEditor_exports = {};
__export(WalletEditor_exports, {
  default: () => WalletEditor_default
});
module.exports = __toCommonJS(WalletEditor_exports);
var import_react = __toESM(require("react"));
var import_utils = require("@pisell/utils");
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_ImageUpload = __toESM(require("./components/ImageUpload"));
var import_JsonEditor = __toESM(require("./components/JsonEditor"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_locales = __toESM(require("./locales"));
var import_sortableWalletPassTypes = __toESM(require("./components/sortableWalletPassTypes"));
var import_ValidityPeriodSelector = __toESM(require("./components/ValidityPeriodSelector"));
var import_relationProduct = __toESM(require("./components/relationProduct"));
var import_WalletEditor = require("./WalletEditor.less");
var import_useComponents = __toESM(require("../../hooks/useComponents"));
var WalletEditor = (0, import_react.forwardRef)(
  (props, ref) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
    const { value, onChange, disabled = false, className, style } = props;
    const context = (0, import_useEngineContext.default)();
    import_utils.locales.init(
      import_locales.default,
      ((_b = (_a = context.appHelper.utils) == null ? void 0 : _a.storage) == null ? void 0 : _b.get("umi_locale")) || "en"
    );
    const amountSymbol = ((_d = (_c = context.appHelper.utils).getData) == null ? void 0 : _d.call(_c, "shop_symbol")) || "";
    const store = ((_h = (_g = (_f = (_e = context.appHelper.utils).getStore) == null ? void 0 : _f.call(_e)) == null ? void 0 : _g.getState) == null ? void 0 : _h.call(_g)) || {};
    const shopName = ((_j = (_i = store.global) == null ? void 0 : _i.shopDetail) == null ? void 0 : _j.name) || "";
    const [sendConfigVisible, setSendConfigVisible] = (0, import_react.useState)(true);
    const [previewVisible, setPreviewVisible] = (0, import_react.useState)(false);
    const [form] = import_antd.Form.useForm();
    const isControlled = value !== void 0;
    const [HolderSelector] = (0, import_useComponents.default)({
      components: ["HolderSelector"]
    });
    const holderSelectorRef = (0, import_react.useRef)(null);
    const defaultValue = (0, import_react.useMemo)(
      () => ({
        status: "enable",
        valid_for: {
          unit: "1",
          unit_type: "year",
          type: "normal"
        },
        metadata: {
          holder: {
            type: "customer"
          },
          showcaseWalletPassNew: import_sortableWalletPassTypes.DEFAULT_WALLET_PASS_TYPES_CONFIG.map(
            (item) => ({
              ...item,
              display: 1
            })
          ),
          coverImage: "",
          send_config: { type: "register" }
        }
      }),
      []
    );
    const currentValue = (0, import_react.useMemo)(() => {
      return { ...defaultValue, ...value };
    }, [value, defaultValue]);
    (0, import_react.useImperativeHandle)(
      ref,
      () => ({
        form,
        setInitialValues: (values) => {
          form.setFieldsValue({ ...defaultValue, ...values });
        },
        getValues: () => {
          var _a2;
          const formValues = form.getFieldsValue();
          const processedValues = {
            ...formValues,
            metadata: {
              ...formValues.metadata,
              showcaseWalletPass: convertShowcaseWalletPass(
                (_a2 = formValues.metadata) == null ? void 0 : _a2.showcaseWalletPassNew
              )
            }
          };
          return processedValues;
        }
      }),
      [form, defaultValue]
    );
    (0, import_react.useEffect)(() => {
      if (isControlled && currentValue) {
        form.setFieldsValue(currentValue);
      }
    }, [currentValue, form, isControlled]);
    const convertShowcaseWalletPass = (showcaseWalletPassNew) => {
      if (!showcaseWalletPassNew) return [];
      return showcaseWalletPassNew.filter((item) => item.display === 1).map((item) => item.type);
    };
    const toggleSendConfig = (0, import_react.useCallback)(() => {
      setSendConfigVisible((prev) => !prev);
    }, []);
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: `wallet-editor ${className || ""}`, style }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form,
      {
        size: "large",
        form,
        layout: "vertical",
        initialValues: isControlled ? currentValue : { ...defaultValue },
        onValuesChange: (...args) => {
          var _a2;
          (_a2 = props.onValuesChange) == null ? void 0 : _a2.call(props, ...args);
        },
        onFinish: (values) => {
          var _a2;
          if (onChange) {
            const processedValues = {
              ...values,
              metadata: {
                ...values.metadata,
                showcaseWalletPass: convertShowcaseWalletPass(
                  (_a2 = values.metadata) == null ? void 0 : _a2.showcaseWalletPassNew
                )
              }
            };
            onChange(processedValues);
          }
        },
        disabled
      },
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          style: {
            padding: "20px 20px 0px 20px",
            borderRadius: 10,
            marginTop: 24,
            border: "1px solid var(--Gray-300,#d0d5dd)"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.Form.Item,
          {
            label: import_utils.locales.getText("walletName"),
            name: "name",
            rules: [
              {
                validator: async (_, value2) => {
                  const msg = import_utils.locales.getText("pleaseInputWalletName");
                  if (value2 == null || typeof value2 !== "object") {
                    return Promise.reject(new Error(msg));
                  }
                  const keys = Object.keys(value2);
                  if (keys.length === 0) {
                    return Promise.reject(new Error(msg));
                  }
                  const hasNonEmpty = keys.some((k) => {
                    const v = value2[k];
                    return typeof v === "string" && v.trim() !== "";
                  });
                  return hasNonEmpty ? Promise.resolve() : Promise.reject(new Error(msg));
                }
              }
            ]
          },
          /* @__PURE__ */ import_react.default.createElement(import_materials.Translation, null)
        ),
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.Form.Item,
          {
            label: import_utils.locales.getText("validityPeriod"),
            name: "valid_for"
          },
          /* @__PURE__ */ import_react.default.createElement(import_ValidityPeriodSelector.default, null)
        ),
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.Form.Item,
          {
            label: import_utils.locales.getText("linkedPasses"),
            name: "relation_id",
            initialValue: []
          },
          /* @__PURE__ */ import_react.default.createElement(import_relationProduct.default, null)
        ),
        HolderSelector && /* @__PURE__ */ import_react.default.createElement(
          import_antd.Form.Item,
          {
            label: import_utils.locales.getText("pisell2.wallet-editor.holder"),
            name: ["metadata", "holder"],
            initialValue: {
              type: "customer"
            },
            rules: [
              {
                validator: async (_, value2) => {
                  var _a2, _b2, _c2;
                  if ((value2 == null ? void 0 : value2.type) === "custom") {
                    if (!((_a2 = value2 == null ? void 0 : value2.custom) == null ? void 0 : _a2.custom_id)) {
                      return Promise.reject(
                        new Error(
                          import_utils.locales.getText(
                            "pisell2.wallet-editor.holder.required"
                          )
                        )
                      );
                    }
                    const options = ((_c2 = (_b2 = holderSelectorRef.current) == null ? void 0 : _b2.getOptions) == null ? void 0 : _c2.call(_b2)) || [];
                    if (!(options == null ? void 0 : options.find(
                      (item) => {
                        var _a3;
                        return item.value === ((_a3 = value2 == null ? void 0 : value2.custom) == null ? void 0 : _a3.custom_id);
                      }
                    ))) {
                      return Promise.reject(
                        new Error(
                          import_utils.locales.getText(
                            "pisell2.wallet-editor.holder.invalid"
                          )
                        )
                      );
                    }
                  }
                  return Promise.resolve();
                }
              }
            ]
          },
          /* @__PURE__ */ import_react.default.createElement(HolderSelector, { ref: holderSelectorRef })
        ),
        /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { label: import_utils.locales.getText("sort"), name: "sort" }, /* @__PURE__ */ import_react.default.createElement(import_antd.InputNumber, { style: { width: "100%" } })),
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.Form.Item,
          {
            label: import_utils.locales.getText("status"),
            name: "status",
            initialValue: "enable"
          },
          /* @__PURE__ */ import_react.default.createElement(import_antd.Radio.Group, null, /* @__PURE__ */ import_react.default.createElement(import_antd.Radio, { value: "enable" }, import_utils.locales.getText("enable")), /* @__PURE__ */ import_react.default.createElement(import_antd.Radio, { value: "disable" }, import_utils.locales.getText("disable")))
        ),
        /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { label: import_utils.locales.getText("distributionConditions") }, /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            style: {
              color: "#8c5cff",
              cursor: "pointer",
              height: 40,
              display: "flex",
              alignItems: "center",
              border: "none",
              background: "transparent",
              padding: 0
            },
            onClick: toggleSendConfig
          },
          import_utils.locales.getText("advancedSettings"),
          " ",
          /* @__PURE__ */ import_react.default.createElement(
            import_materials.Icon,
            {
              type: "pisell2-chevron-down",
              size: 18,
              style: {
                transform: sendConfigVisible ? "rotate(0deg)" : "rotate(180deg)"
              }
            }
          )
        ), /* @__PURE__ */ import_react.default.createElement(
          import_antd.Form.Item,
          {
            noStyle: true,
            name: ["metadata", "send_config"],
            initialValue: {
              type: "register"
            }
          },
          /* @__PURE__ */ import_react.default.createElement(
            import_JsonEditor.default,
            {
              placeholder: import_utils.locales.getText("enterJSONConfig"),
              rows: 4,
              disabled,
              style: { display: sendConfigVisible ? "block" : "none" }
            }
          )
        ))
      ),
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          style: {
            padding: "20px 20px 0px 20px",
            borderRadius: 10,
            margin: "24px 0",
            border: "1px solid var(--Gray-300,#d0d5dd)"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            style: {
              marginBottom: "8px",
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center"
            }
          },
          /* @__PURE__ */ import_react.default.createElement("span", { style: { fontWeight: "bold", fontSize: 16 } }, import_utils.locales.getText("displaySettings")),
          /* @__PURE__ */ import_react.default.createElement(
            "span",
            {
              style: { color: "#8c5cff", cursor: "pointer" },
              onClick: () => setPreviewVisible(true)
            },
            import_utils.locales.getText("viewPreview")
          )
        ),
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.Form.Item,
          {
            label: "",
            name: ["metadata", "showcaseWalletPassNew"],
            initialValue: import_sortableWalletPassTypes.DEFAULT_WALLET_PASS_TYPES_CONFIG.map((item) => ({
              ...item,
              display: 1
            }))
          },
          /* @__PURE__ */ import_react.default.createElement(import_sortableWalletPassTypes.default, null)
        ),
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.Form.Item,
          {
            label: import_utils.locales.getText("icon"),
            name: ["metadata", "icon"]
          },
          /* @__PURE__ */ import_react.default.createElement(import_ImageUpload.default, null)
        ),
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.Form.Item,
          {
            label: import_utils.locales.getText("coverImage"),
            name: ["metadata", "coverImage"]
          },
          /* @__PURE__ */ import_react.default.createElement(import_ImageUpload.default, null)
        )
      )
    )), /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellModal,
      {
        open: previewVisible,
        onCancel: () => setPreviewVisible(false),
        title: import_utils.locales.getText("preview"),
        width: "auto",
        footer: false,
        header: false,
        className: "pisell-wallet-editor_preview-modal"
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.WalletCard,
        {
          mode: "dark",
          shopName,
          cardStyle: "normal",
          codeType: "qrCode",
          symbol: amountSymbol,
          items: form.getFieldValue(["metadata", "showcaseWalletPassNew"]),
          customBackgroundImage: form.getFieldValue([
            "metadata",
            "coverImage"
          ]),
          iconImg: form.getFieldValue(["metadata", "icon"]),
          style: {
            minWidth: 368
          }
        }
      )
    ));
  }
);
var WalletEditor_default = WalletEditor;
