var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/modules/AccountList/index.ts
var AccountList_exports = {};
__export(AccountList_exports, {
  AccountListModule: () => AccountListModule
});
module.exports = __toCommonJS(AccountList_exports);
var import_lodash_es = require("lodash-es");
var import_Account = require("../Account");
var import_BaseModule = require("../BaseModule");
var import_types = require("./types");
var import_utils = require("./utils");
var AccountListModule = class extends import_BaseModule.BaseModule {
  constructor(name, version) {
    super(name, version);
    this.defaultName = "accountList";
    this.defaultVersion = "1.0.0";
    this.store = {
      accountList: [],
      // 账号的纯数据列表
      accounts: [],
      // 账号的 module 列表
      isLoading: false,
      error: null
    };
    this.openCache = false;
  }
  async initialize(core, options) {
    var _a, _b, _c;
    this.core = core;
    this.store = options == null ? void 0 : options.store;
    this.request = this.core.getPlugin("request");
    if (Array.isArray((_a = options == null ? void 0 : options.initialState) == null ? void 0 : _a.accountList)) {
      const recordList = (0, import_lodash_es.cloneDeep)(options.initialState.accountList || []);
      this.store.accounts = [];
      recordList.forEach((account) => {
        this.addAccount(account);
      });
    } else {
      this.store.accounts = [];
      this.store.accountList = [];
    }
    if ((_b = options == null ? void 0 : options.otherParams) == null ? void 0 : _b.cacheId) {
      this.openCache = options.otherParams.openCache;
      this.cacheId = options.otherParams.cacheId;
    }
    if ((_c = options == null ? void 0 : options.otherParams) == null ? void 0 : _c.fatherModule) {
      this.fatherModule = options.otherParams.fatherModule;
    }
  }
  /**
   * 创建账号并添加到列表中
   * @param account 账号信息
   * @param needEmit 是否需要触发事件
   * @param type 添加类型
   */
  async createAccountAndAdd(account, needEmit = true, type) {
    const tempAccountModule = this.store.accounts.find(
      (a) => a.getId() === account.id
    );
    if (tempAccountModule) {
      return tempAccountModule;
    }
    const newAccountList = [...this.store.accountList || []];
    if (type === "unshift") {
      newAccountList.unshift(account);
    } else {
      newAccountList.push(account);
    }
    this.store.accountList = newAccountList;
    const accountModule = new import_Account.AccountModule(`account_${account.id}`);
    this.core.registerModule(accountModule);
    accountModule.setAccountInfo(account);
    if (type === "unshift") {
      this.store.accounts = [accountModule, ...this.store.accounts || []];
    } else {
      this.store.accounts = [...this.store.accounts || [], accountModule];
    }
    if (needEmit) {
      await this.core.effects.emit(
        import_types.AccountListHooks.OnAccountListUpdate,
        this.store
      );
    }
    return accountModule;
  }
  async addAccount(account) {
    let currentAccountModule;
    try {
      this.store.isLoading = true;
      this.store.error = null;
      if (this.store.accounts.some((a) => a.getId() === account.id)) {
        currentAccountModule = this.store.accounts.find(
          (n) => n.getId() === account.id
        );
        throw new Error(`Account with id ${account.id} already exists`);
      }
      this.store.accountList.push(account);
      const accountModule = new import_Account.AccountModule(`account_${account.id}`);
      this.core.registerModule(accountModule);
      accountModule.setAccountInfo(account);
      this.store.accounts = [...this.store.accounts || [], accountModule];
      if (this.store.accounts.length === 1) {
        this.setActiveAccount(accountModule.getId());
      }
      currentAccountModule = accountModule;
      await this.core.effects.emit(
        import_types.AccountListHooks.OnAccountListUpdate,
        this.store
      );
    } catch (error) {
      console.error(error);
      this.store.error = error instanceof Error ? error.message : "Failed to add account";
      await this.core.effects.emit(
        import_types.AccountListHooks.OnAccountListError,
        this.store.error
      );
    } finally {
      this.store.isLoading = false;
      return currentAccountModule;
    }
  }
  async updateAccount(id, updates) {
    try {
      this.store.isLoading = true;
      this.store.error = null;
      const account = this.getAccount(id);
      if (!account) {
        throw new Error(`Account with id ${id} not found`);
      }
      account.setAccountInfo(updates);
      const index = this.store.accountList.findIndex(
        (account2) => account2.id === id
      );
      if (index !== -1) {
        this.store.accountList[index] = updates;
      }
      await this.core.effects.emit(
        import_types.AccountListHooks.OnAccountListUpdate,
        this.store
      );
    } catch (error) {
      this.store.error = error instanceof Error ? error.message : "Failed to update account";
      await this.core.effects.emit(
        import_types.AccountListHooks.OnAccountListError,
        this.store.error
      );
    } finally {
      this.store.isLoading = false;
    }
  }
  async updateAccountListById(id, updates) {
    this.store.accountList = this.store.accountList.map((account) => {
      if (account.id === id) {
        return updates;
      }
      return account;
    });
    this.core.effects.emit(`${this.name}:changed`, {
      path: "accounts",
      value: this.store.accountList
    });
  }
  async removeAccount(id) {
    var _a;
    try {
      this.store.isLoading = true;
      this.store.error = null;
      const index = this.store.accounts.findIndex((a) => a.getId() === id);
      if (index === -1) {
        throw new Error(`Account with id ${id} not found`);
      }
      this.store.accounts[index].destroy();
      this.store.accounts = [
        ...(this.store.accounts || []).slice(0, index),
        ...(this.store.accounts || []).slice(index + 1)
      ];
      this.store.accountList = this.store.accountList.filter(
        (account) => account.id !== id
      );
      if (!this.getActiveAccount() || ((_a = this.getActiveAccount()) == null ? void 0 : _a.getId()) === id || this.store.accounts.length === 1) {
        this.setActiveAccount(this.store.accounts[0].getId());
      }
      await this.core.effects.emit(
        import_types.AccountListHooks.OnAccountListUpdate,
        this.store
      );
    } catch (error) {
      this.store.error = error instanceof Error ? error.message : "Failed to remove account";
      await this.core.effects.emit(
        import_types.AccountListHooks.OnAccountListError,
        this.store.error
      );
    } finally {
      this.store.isLoading = false;
    }
  }
  getAccounts() {
    return [...this.store.accounts || []];
  }
  getAccount(id) {
    return this.store.accounts.find((account) => account.getId() === id) || null;
  }
  async clearAccounts() {
    try {
      this.store.isLoading = true;
      this.store.error = null;
      this.store.accounts = [];
      await this.core.effects.emit(
        import_types.AccountListHooks.OnAccountListUpdate,
        this.store
      );
    } catch (error) {
      this.store.error = error instanceof Error ? error.message : "Failed to clear accounts";
      await this.core.effects.emit(
        import_types.AccountListHooks.OnAccountListError,
        this.store.error
      );
    } finally {
      this.store.isLoading = false;
    }
  }
  setActiveAccount(id) {
    this.store.accounts.forEach((account) => {
      if (account.getId() === id) {
        account.setActive(true);
      } else {
        account.setActive(false);
      }
    });
  }
  getActiveAccount() {
    return this.store.accounts.find((account) => account.isActive()) || null;
  }
  storeChange() {
    if (this.openCache) {
      const store = (0, import_lodash_es.cloneDeep)(this.store);
      store.accountList = store.accountList.filter(
        (account, index, self) => index === self.findIndex((t) => t.id === account.id)
      );
      this.checkSaveCache({
        cacheId: this.cacheId,
        fatherModule: this.fatherModule,
        store,
        cacheKey: ["accountList"]
      });
    }
  }
  /**
   * 批量添加holder类型账号
   */
  async addHolderAccounts(params) {
    const { holders, customerId, type = "push" } = params;
    const accountModules = [];
    for (const holder of holders) {
      const account = (0, import_utils.createHolderAccount)(holder, customerId);
      const accountModule = await this.createAccountAndAdd(
        account,
        false,
        type
      );
      if (type === "unshift") {
        accountModules.unshift(accountModule);
      } else {
        accountModules.push(accountModule);
      }
    }
    await this.core.effects.emit(
      import_types.AccountListHooks.OnAccountListUpdate,
      this.store
    );
    return accountModules;
  }
  /**
   * 获取客户列表
   * @param params 查询参数
   * @returns 客户列表
   */
  async getCustomerList(params = {}) {
    const url = "/customer/es/data";
    const { page = 1, pageSize = 20, keyword, ...otherParams } = params;
    try {
      this.store.isLoading = true;
      this.store.error = null;
      const queryParams = {
        page,
        pageSize,
        ...keyword && { keyword },
        ...otherParams
      };
      const res = await this.request.get(url, queryParams);
      return (res == null ? void 0 : res.data) || [];
    } catch (error) {
      console.error("Failed to fetch customer list:", error);
      this.store.error = error instanceof Error ? error.message : "Failed to fetch customer list";
      throw error;
    } finally {
      this.store.isLoading = false;
    }
  }
  /**
   * 获取holder类型账户列表
   * @param params
   */
  async fetchHolderAccounts(params) {
    var _a, _b;
    const url = params.url || "/account/holder";
    const { form_id, shop_id, num, skip, customer_id } = (params == null ? void 0 : params.query) || {};
    try {
      const res = await this.request.get(url, {
        customer_id,
        form_id,
        shop_id,
        num: num || 100,
        skip: skip || 1
      });
      this.store.accountList = [];
      this.store.accounts = [];
      if ((_b = (_a = res == null ? void 0 : res.data) == null ? void 0 : _a.list) == null ? void 0 : _b.length) {
        await this.addHolderAccounts({
          holders: res.data.list,
          customerId: customer_id
        });
      }
    } catch (error) {
      console.error(error);
    }
  }
  getLoginAccount() {
    return this.store.accounts.find((n) => n.isLogin());
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  AccountListModule
});
