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/webPosLogin/WebPosLogin.tsx
var WebPosLogin_exports = {};
__export(WebPosLogin_exports, {
  default: () => WebPosLogin_default
});
module.exports = __toCommonJS(WebPosLogin_exports);
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_react = __toESM(require("react"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_responsive = require("../../responsive");
var import_utils2 = require("../../utils");
var import_WebPosLoginCpt = __toESM(require("./WebPosLoginCpt"));
var import_service = require("./service");
var useSearchParams = () => {
  return new URLSearchParams(window.location.search);
};
var WebPosLogin = (props) => {
  var _a, _b, _c, _d, _e, _f;
  const context = (0, import_useEngineContext.default)();
  const {
    getApp = () => ({}),
    reloadAfterLogin,
    pisellos
  } = (_a = context.appHelper) == null ? void 0 : _a.utils;
  const { mediaConfig, isIotLogin } = (_b = context.appHelper) == null ? void 0 : _b.constants;
  const {
    backgroundImage,
    step: propsStep = "login",
    loginSlot,
    config,
    variant
  } = props;
  const [storeList, setStoreList] = (0, import_react.useState)(() => {
    var _a2;
    const app = getApp();
    const storeList2 = (_a2 = app == null ? void 0 : app.storage) == null ? void 0 : _a2.getStorage("storeList");
    if (!storeList2) {
      return [];
    }
    return JSON.parse(storeList2);
  });
  console.log("loginSlot", loginSlot);
  const urlStep = useSearchParams().get("step");
  const [step, setStep] = (0, import_react.useState)(() => {
    if (urlStep && urlStep !== "undefined") {
      return urlStep;
    }
    return props.step || "login";
  });
  const [userInfo, setUserInfo] = (0, import_react.useState)(() => {
    var _a2;
    const app = getApp();
    const userInfo2 = ((_a2 = app == null ? void 0 : app.storage) == null ? void 0 : _a2.getStorage("userInfo")) || "{}";
    const userInfoObj = JSON.parse(userInfo2);
    return {
      name: (userInfoObj == null ? void 0 : userInfoObj.name) || "",
      avatar: (userInfoObj == null ? void 0 : userInfoObj.avatar) || ""
    };
  });
  const [selectedStore, setSelectedStore] = (0, import_react.useState)(() => {
    var _a2;
    const app = getApp();
    const selectedStore2 = ((_a2 = app == null ? void 0 : app.storage) == null ? void 0 : _a2.getStorage("selectedStore")) || "{}";
    return JSON.parse(selectedStore2);
  });
  const [deviceList, setDeviceList] = (0, import_react.useState)(() => {
    var _a2;
    const app = getApp();
    const deviceList2 = ((_a2 = app == null ? void 0 : app.storage) == null ? void 0 : _a2.getStorage("deviceList")) || "[]";
    return JSON.parse(deviceList2);
  });
  const [lastUsedStoreId, setLastUsedStoreId] = (0, import_react.useState)(() => {
    var _a2, _b2;
    const app = getApp();
    const lastUsedStore = ((_a2 = app == null ? void 0 : app.storage) == null ? void 0 : _a2.getStorage("selectedStore")) || "{}";
    const lastUsedStoreId2 = ((_b2 = JSON.parse(lastUsedStore)) == null ? void 0 : _b2.id) || 0;
    return parseInt(lastUsedStoreId2);
  });
  const [lastUsedDeviceId, setLastUsedDeviceId] = (0, import_react.useState)(() => {
    var _a2, _b2;
    const app = getApp();
    const lastUsedDevice = ((_a2 = app == null ? void 0 : app.storage) == null ? void 0 : _a2.getStorage("lastUsedDevice")) || "{}";
    const lastUsedDeviceId2 = ((_b2 = JSON.parse(lastUsedDevice)) == null ? void 0 : _b2.id) || 0;
    return parseInt(lastUsedDeviceId2);
  });
  const [isShowGoBack, setIsShowGoBack] = (0, import_react.useState)(true);
  import_utils2.request.setRequest(context.appHelper.utils.request);
  const onLoginSuccess = async (res) => {
    var _a2, _b2, _c2, _d2, _e2;
    const app = getApp();
    if (!res) {
      return;
    }
    (_a2 = app == null ? void 0 : app.getPlugin("token")) == null ? void 0 : _a2.set(res == null ? void 0 : res.authorization);
    (_b2 = app == null ? void 0 : app.storage) == null ? void 0 : _b2.setStorage(
      "account",
      JSON.stringify({ ...res == null ? void 0 : res.account, ...res })
    );
    setUserInfo({
      name: ((_c2 = res == null ? void 0 : res.account) == null ? void 0 : _c2.name) || "",
      avatar: ((_d2 = res == null ? void 0 : res.account) == null ? void 0 : _d2.avatar) || ""
    });
    const tenant = await (0, import_service.getTenant)();
    (_e2 = app == null ? void 0 : app.storage) == null ? void 0 : _e2.setStorage("storeList", JSON.stringify(tenant || {}));
    const lastUsedStore = tenant == null ? void 0 : tenant.find((item) => item.id == lastUsedStoreId);
    if ((tenant == null ? void 0 : tenant.length) === 1) {
      await handleStoreSelect(tenant[0], false);
    } else if (lastUsedStore) {
      await handleStoreSelect(lastUsedStore, false);
    } else {
      setStep("store");
    }
    setStoreList(tenant);
  };
  const onBack = () => {
    if (step === "store") {
      setStep("login");
    } else if (step === "device") {
      setStep("store");
    }
  };
  const handleStoreSelect = async (shopInfo, isShowGoBack2 = true) => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
    const app = getApp();
    if (lastUsedStoreId !== shopInfo.id) {
      await ((_b2 = (_a2 = pisellos.server) == null ? void 0 : _a2.clearAllIndexDB) == null ? void 0 : _b2.call(_a2));
      if (pisellos.server) {
        pisellos.server = null;
      }
    }
    if (isIotLogin) {
      if (lastUsedStoreId !== shopInfo.id) {
        (_c2 = app == null ? void 0 : app.storage) == null ? void 0 : _c2.removeStorage("iotDevice");
      }
    }
    app.storage.setStorage("tenant_domain", (_d2 = shopInfo == null ? void 0 : shopInfo.tenant) == null ? void 0 : _d2.default_domain);
    app.storage.setStorage("selectedStore", JSON.stringify(shopInfo));
    setLastUsedStoreId(shopInfo.id);
    setSelectedStore(shopInfo);
    (_e2 = app == null ? void 0 : app.logger) == null ? void 0 : _e2.addLog({
      type: "info",
      title: "选择店铺页-点击店铺",
      metadata: shopInfo || {}
    });
    try {
      const res = await (0, import_service.getTenantDetail)();
      if (!res) {
        return;
      }
      if (!((_f2 = res == null ? void 0 : res.mypisell_data) == null ? void 0 : _f2.account_token)) {
        (0, import_materials.PisellToast)({
          content: import_utils.locales.getText("webpos-login-store-data-missing")
        });
        return;
      }
      (_h = app == null ? void 0 : app.getPlugin("token")) == null ? void 0 : _h.set((_g = res == null ? void 0 : res.mypisell_data) == null ? void 0 : _g.account_token, "pisellV1Token");
      if (res.nocobase_tenant_token) {
        (_i = app == null ? void 0 : app.getPlugin("token")) == null ? void 0 : _i.set(res.nocobase_tenant_token, "nocobaseToken");
      }
      if (isIotLogin) {
        const _iotDeviceNumber = (_k = JSON.parse(
          ((_j = app == null ? void 0 : app.storage) == null ? void 0 : _j.getStorage("iotDevice")) || "{}"
        )) == null ? void 0 : _k.number;
        if (_iotDeviceNumber) {
          const _pageSource = (_l = useSearchParams()) == null ? void 0 : _l.get("pageSource");
          console.log(_pageSource, "pageSource");
          if (_pageSource !== "pinLoginStore") {
            (_m = app == null ? void 0 : app.storage) == null ? void 0 : _m.setStorage("isLogin", true);
            reloadAfterLogin == null ? void 0 : reloadAfterLogin();
          } else {
            (_o = (_n = app == null ? void 0 : app.history) == null ? void 0 : _n.instance) == null ? void 0 : _o.replace("/");
          }
          return;
        }
        setStep("device");
      } else {
        await getDeviceListFunction();
      }
      setIsShowGoBack(isShowGoBack2);
      (_p = app == null ? void 0 : app.logger) == null ? void 0 : _p.addLog({
        type: "info",
        title: "选择店铺页-选择店铺成功",
        metadata: res || {}
      });
    } catch (err) {
      (_q = app == null ? void 0 : app.logger) == null ? void 0 : _q.addLog({
        type: "error",
        title: "登录页-选择店铺失败",
        metadata: err || {}
      });
    }
  };
  const getDeviceListFunction = async () => {
    var _a2, _b2, _c2;
    if (isIotLogin) {
      return;
    }
    const app = getApp();
    const localeType = ((_a2 = localStorage == null ? void 0 : localStorage.getItem) == null ? void 0 : _a2.call(localStorage, "pisell_app_channel")) || "";
    const type = !localeType || localeType === "pos" ? "terminal" : localeType;
    const res = await (0, import_service.getDeviceList)({
      type,
      with: ["client"]
    });
    if (!res) {
      return;
    }
    if ((res == null ? void 0 : res.length) > 0) {
      app == null ? void 0 : app.storage.setStorage("deviceList", JSON.stringify(res || []));
      setDeviceList(res);
      setStep("device");
      (_b2 = app == null ? void 0 : app.logger) == null ? void 0 : _b2.addLog({
        type: "info",
        title: "选择店铺页-获取设备列表成功-有云端设备",
        metadata: res || {}
      });
    } else {
      app.storage.setStorage("isLogin", true);
      reloadAfterLogin == null ? void 0 : reloadAfterLogin();
      (_c2 = app == null ? void 0 : app.logger) == null ? void 0 : _c2.addLog({
        type: "info",
        title: "选择店铺页-获取设备列表成功-没有云端设备",
        metadata: res || {}
      });
    }
  };
  const handleDissociateDevice = async () => {
    var _a2, _b2, _c2, _d2, _e2;
    const app = getApp();
    const boundCloudDevice = JSON.parse(
      ((_a2 = app == null ? void 0 : app.storage) == null ? void 0 : _a2.getStorage("boundCloudDevice")) || "{}"
    );
    if ((boundCloudDevice == null ? void 0 : boundCloudDevice.number) && ((_b2 = boundCloudDevice == null ? void 0 : boundCloudDevice.client) == null ? void 0 : _b2.number)) {
      const res = await (0, import_service.dissociateDevice)({
        number: (_c2 = boundCloudDevice == null ? void 0 : boundCloudDevice.client) == null ? void 0 : _c2.number,
        dissociateDeviceNumber: boundCloudDevice == null ? void 0 : boundCloudDevice.number
      });
      if (!res) {
        (_d2 = app == null ? void 0 : app.logger) == null ? void 0 : _d2.addLog({
          type: "error",
          title: "选择设备页-解除设备绑定失败"
        });
        return false;
      } else {
        (_e2 = app == null ? void 0 : app.logger) == null ? void 0 : _e2.addLog({
          type: "info",
          title: "选择设备页-解除设备绑定成功",
          metadata: res || {}
        });
        return true;
      }
    }
    return true;
  };
  const handleDeviceSelect = async (device) => {
    var _a2, _b2, _c2, _d2, _e2;
    const app = getApp();
    app.storage.setStorage("lastUsedDevice", JSON.stringify(device));
    setLastUsedDeviceId(device.id);
    const deviceNumber = device == null ? void 0 : device.number;
    const language = ((_a2 = app == null ? void 0 : app.locales) == null ? void 0 : _a2.getLocale()) || "en";
    let _device = null;
    try {
      const _deviceOrigin = await app.plugins.get("device").getDeviceInfo({ language });
      _device = (_deviceOrigin == null ? void 0 : _deviceOrigin.data) || null;
      app == null ? void 0 : app.storage.setStorage("localDevice", JSON.stringify(_device || {}));
    } catch (error) {
      (_b2 = app == null ? void 0 : app.logger) == null ? void 0 : _b2.addLog({
        type: "error",
        title: "选择设备页-获取本机设备信息获取失败"
      });
    }
    if (!_device) {
      (_c2 = app == null ? void 0 : app.logger) == null ? void 0 : _c2.addLog({
        type: "error",
        title: "选择设备页-绑定设备失败-本机设备信息获取失败"
      });
      return;
    } else {
      (_d2 = app == null ? void 0 : app.logger) == null ? void 0 : _d2.addLog({
        type: "info",
        title: "选择设备页-绑定设备-本机设备信息获取成功",
        metadata: _device || {}
      });
    }
    const dissociateRes = await handleDissociateDevice();
    if (!dissociateRes) {
      return;
    }
    const res = await (0, import_service.selectDevice)({
      deviceNumber,
      ..._device || {}
    });
    if (!res) {
      return;
    }
    app.storage.setStorage("loginStatus", "success");
    app.storage.setStorage("isLogin", true);
    reloadAfterLogin == null ? void 0 : reloadAfterLogin();
    app == null ? void 0 : app.storage.setStorage("boundCloudDevice", JSON.stringify(res || {}));
    app.pubsub.publish("dataManager", {
      type: "get",
      key: "DEVICE_NUMBER",
      metadata: { msg: "webpo主动推送" }
    });
    (_e2 = app == null ? void 0 : app.logger) == null ? void 0 : _e2.addLog({
      type: "info",
      title: "选择设备页-绑定设备成功",
      metadata: res || {}
    });
  };
  const handleChangeAccount = () => {
    var _a2, _b2, _c2;
    setStep("login");
    const app = getApp();
    (_a2 = app == null ? void 0 : app.getPlugin("token")) == null ? void 0 : _a2.remove();
    (_b2 = app == null ? void 0 : app.getPlugin("token")) == null ? void 0 : _b2.remove("pisellV1Token");
    (_c2 = app == null ? void 0 : app.getPlugin("token")) == null ? void 0 : _c2.remove("nocobaseToken");
  };
  const handleChangeStore = () => {
    setStep("store");
  };
  const handleIotDeviceLinked = () => {
    var _a2;
    const app = getApp();
    (_a2 = app == null ? void 0 : app.storage) == null ? void 0 : _a2.setStorage("isLogin", true);
    reloadAfterLogin == null ? void 0 : reloadAfterLogin();
  };
  const handleIotBack = () => {
    var _a2, _b2, _c2, _d2;
    const app = getApp();
    const _pageSource = (_a2 = useSearchParams()) == null ? void 0 : _a2.get("pageSource");
    console.log(_pageSource, "pageSource");
    if (_pageSource === "pinLoginDevice") {
      (_d2 = (_c2 = (_b2 = app == null ? void 0 : app.history) == null ? void 0 : _b2.instance) == null ? void 0 : _c2.goBack) == null ? void 0 : _d2.call(_c2);
    } else {
      setStep("store");
    }
  };
  return /* @__PURE__ */ import_react.default.createElement(
    import_WebPosLoginCpt.default,
    {
      loginConfig: config,
      backgroundImage: backgroundImage || ((_d = (_c = mediaConfig.loginBgMediaConfig) == null ? void 0 : _c[0]) == null ? void 0 : _d.url),
      brandConfig: mediaConfig.loginMediaConfig,
      step,
      showBackButton: isShowGoBack,
      storeList,
      deviceList,
      userInfo,
      selectedStore,
      lastUsedStoreId,
      lastUsedDeviceId,
      locale: ((_f = (_e = context == null ? void 0 : context.engine) == null ? void 0 : _e.props) == null ? void 0 : _f.locale) || "en",
      loading: false,
      loginSlot,
      variant,
      onStoreSelect: handleStoreSelect,
      onDeviceSelect: handleDeviceSelect,
      onChangeAccount: handleChangeAccount,
      onChangeStore: handleChangeStore,
      onBack,
      onLoginSuccess,
      onIotDeviceLinked: handleIotDeviceLinked,
      onIotBack: handleIotBack
    }
  );
};
WebPosLogin.displayName = "WebPosLogin";
var WebPosLogin_default = (0, import_responsive.withResponsive)(WebPosLogin);
