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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/modules/Customer/index.ts
var Customer_exports = {};
__export(Customer_exports, {
  CustomerModule: () => CustomerModule
});
module.exports = __toCommonJS(Customer_exports);
var import_lodash_es = require("lodash-es");
var import_BaseModule = require("../BaseModule");
var import_plugins = require("../../plugins");
var import_constants = require("./constants");
__reExport(Customer_exports, require("./types"), module.exports);
var CustomerModule = class extends import_BaseModule.BaseModule {
  constructor(name, version) {
    super(name, version);
    this.defaultName = "customer";
    this.defaultVersion = "1.0.0";
    this.store = {
      customerList: [],
      selectedCustomer: null,
      total: 0,
      currentPage: 1,
      pageSize: import_constants.DEFAULT_PAGE_SIZE,
      loading: false,
      error: null,
      hasMore: true,
      loadingMore: false,
      searchParams: {}
    };
    this.openCache = false;
    this.otherParams = {};
  }
  async initialize(core, options) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
    this.core = core;
    this.store = options == null ? void 0 : options.store;
    this.request = this.core.getPlugin("request");
    this.otherParams = (options == null ? void 0 : options.otherParams) || {};
    if (Array.isArray((_a = options == null ? void 0 : options.initialState) == null ? void 0 : _a.customerList)) {
      const customerList = (0, import_lodash_es.cloneDeep)(options.initialState.customerList || []);
      this.store.customerList = customerList;
    } else {
      this.store.customerList = [];
    }
    if ((_b = options == null ? void 0 : options.initialState) == null ? void 0 : _b.selectedCustomer) {
      this.store.selectedCustomer = (0, import_lodash_es.cloneDeep)(options.initialState.selectedCustomer);
    } else {
      this.store.selectedCustomer = null;
    }
    if (typeof ((_c = options == null ? void 0 : options.initialState) == null ? void 0 : _c.total) === "number") {
      this.store.total = options.initialState.total;
    } else {
      this.store.total = 0;
    }
    if (typeof ((_d = options == null ? void 0 : options.initialState) == null ? void 0 : _d.currentPage) === "number") {
      this.store.currentPage = options.initialState.currentPage;
    } else {
      this.store.currentPage = 1;
    }
    if (typeof ((_e = options == null ? void 0 : options.initialState) == null ? void 0 : _e.pageSize) === "number" && options.initialState.pageSize > 1) {
      this.store.pageSize = options.initialState.pageSize;
    } else {
      this.store.pageSize = import_constants.DEFAULT_PAGE_SIZE;
    }
    this.store.hasMore = ((_f = options == null ? void 0 : options.initialState) == null ? void 0 : _f.hasMore) ?? true;
    this.store.loadingMore = ((_g = options == null ? void 0 : options.initialState) == null ? void 0 : _g.loadingMore) ?? false;
    this.store.searchParams = ((_h = options == null ? void 0 : options.initialState) == null ? void 0 : _h.searchParams) ?? {};
    if ((_i = options == null ? void 0 : options.otherParams) == null ? void 0 : _i.cacheId) {
      this.openCache = options.otherParams.openCache;
      this.cacheId = options.otherParams.cacheId;
    }
    if ((_j = options == null ? void 0 : options.otherParams) == null ? void 0 : _j.fatherModule) {
      this.fatherModule = options.otherParams.fatherModule;
    }
  }
  /**
   * 获取客户列表数据（内部方法）
   * @param params 查询参数
   * @returns API响应数据
   */
  async fetchCustomerListData(params = {}) {
    var _a, _b, _c, _d;
    let url = "/customer/select-list";
    if ((_a = this.otherParams) == null ? void 0 : _a.isFranchisee) {
      url = "/franchisee/customer/select-list";
    }
    const { skip = 1, num = import_constants.DEFAULT_PAGE_SIZE, search, ..._otherParams } = params;
    const queryParams = {
      skip,
      num,
      sort_by: import_constants.SORT_BY,
      with: ["latestWalletDetail.wallet", "contactsInfo", "formRecord"],
      search_wallet_flag: 1,
      search_wallet_pass_flag: 1,
      ...search && { search },
      ..._otherParams
    };
    const res = await this.request.get(url, queryParams, {
      cache: {
        mode: import_plugins.RequestModeENUM.REMOTE_LOCAL,
        type: "memory"
      }
    });
    if ((res == null ? void 0 : res.code) !== 200) {
      throw new Error(res == null ? void 0 : res.message);
    }
    let _customerList = ((_b = res == null ? void 0 : res.data) == null ? void 0 : _b.list) || [];
    if (((_c = this.otherParams) == null ? void 0 : _c.isFranchisee) && (_customerList == null ? void 0 : _customerList.length) > 0) {
      _customerList = _customerList == null ? void 0 : _customerList.map((item) => {
        return {
          ...item || {},
          is_franchisor_customer: 1
          // 标识是总店的客户
        };
      });
    }
    return {
      customerList: _customerList,
      total: ((_d = res == null ? void 0 : res.data) == null ? void 0 : _d.count) || 0,
      page: skip,
      pageSize: num
    };
  }
  /**
   * 处理客户列表操作的错误（内部方法）
   * @param error 错误对象
   * @param operation 操作名称
   */
  async handleCustomerListError(error, operation) {
    console.error(`Failed to ${operation}:`, error);
    this.store.error = error instanceof Error ? error.message : `Failed to ${operation}`;
    await this.core.effects.emit(
      `${this.name}:onCustomerListError`,
      this.store.error
    );
  }
  /**
   * 查询客户列表但不写入 customerList / pagination 状态。
   *
   * 用于按 ID 补齐客户等内部查询，避免把临时的 num/searchParams 污染到滚动列表。
   */
  async queryCustomerList(params = {}) {
    const { customerList, total, page, pageSize } = await this.fetchCustomerListData(params);
    return {
      list: customerList,
      total,
      page,
      pageSize
    };
  }
  /**
   * 获取客户列表
   * @param params 查询参数
   * @returns 客户列表响应
   */
  async getCustomerList(params = {}) {
    try {
      this.store.loading = true;
      this.store.error = null;
      const { customerList, total, page, pageSize } = await this.fetchCustomerListData(params);
      const { skip, num, ...searchParams } = params;
      this.store.searchParams = (0, import_lodash_es.cloneDeep)(searchParams);
      this.store.currentPage = page;
      this.store.pageSize = pageSize;
      this.store.total = total;
      this.store.hasMore = page * pageSize < total;
      this.store.customerList = (0, import_lodash_es.cloneDeep)(customerList);
      this.triggerPaginationChange({
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      });
      const response = {
        list: customerList,
        total,
        page,
        pageSize
      };
      return response;
    } catch (error) {
      await this.handleCustomerListError(error, "fetch customer list");
      throw error;
    } finally {
      this.store.loading = false;
      this.storeChange();
      await this.core.effects.emit(
        `${this.name}:onCustomerListUpdate`,
        this.store
      );
    }
  }
  /**
   * 设置客户列表
   * @param customers 客户列表
   * @param total 总数
   */
  setCustomerList(customers, total) {
    this.store.customerList = (0, import_lodash_es.cloneDeep)(customers);
    if (typeof total === "number") {
      this.store.total = total;
    }
    this.storeChange();
  }
  /**
   * 设置当前选择的客户
   * @param customer 选择的客户
   */
  setSelectedCustomer(customer) {
    this.store.selectedCustomer = !customer ? import_constants.DEFAULT_CUSTOMER : (0, import_lodash_es.cloneDeep)(customer);
    this.core.effects.emit(
      `${this.name}:onCustomerSelected`,
      this.store.selectedCustomer
    );
    this.storeChange();
  }
  /**
   * 获取当前选择的客户
   * @returns 当前选择的客户
   */
  getSelectedCustomer() {
    return this.store.selectedCustomer;
  }
  /**
   * 获取客户列表
   * @returns 客户列表
   */
  getCustomers() {
    return [...this.store.customerList];
  }
  /**
   * 根据ID查找客户
   * @param id 客户ID
   * @returns 客户信息
   */
  getCustomerById(id) {
    return this.store.customerList.find((customer) => customer.id === id) || null;
  }
  /**
   * 清空客户列表
   */
  clearCustomers() {
    this.store.customerList = [];
    this.store.selectedCustomer = null;
    this.store.total = 0;
    this.store.currentPage = 1;
    this.store.pageSize = import_constants.DEFAULT_PAGE_SIZE;
    this.store.hasMore = true;
    this.store.loadingMore = false;
    this.store.searchParams = {};
    this.core.effects.emit(
      `${this.name}:onCustomerListUpdate`,
      this.store
    );
    this.storeChange();
  }
  /**
   * 添加客户到列表第一位
   * @param customer 要添加的客户信息
   */
  addCustomerToFirst(customer) {
    const newCustomer = (0, import_lodash_es.cloneDeep)(customer);
    this.store.customerList = [newCustomer, ...this.store.customerList];
    this.store.total += 1;
    this.core.effects.emit(
      `${this.name}:onCustomerListUpdate`,
      this.store
    );
    this.storeChange();
  }
  /**
   * 获取当前状态
   * @returns 当前状态
   */
  getState() {
    return (0, import_lodash_es.cloneDeep)(this.store);
  }
  /**
   * 获取分页信息
   * @returns 分页信息
   */
  getPaginationInfo() {
    return {
      page: this.store.currentPage,
      pageSize: this.store.pageSize,
      total: this.store.total,
      totalPages: Math.ceil(this.store.total / this.store.pageSize)
    };
  }
  /**
   * 触发分页变化事件
   * @param pagination 分页信息
   */
  triggerPaginationChange(pagination) {
    this.core.effects.emit(
      `${this.name}:onPaginationChange`,
      pagination
    );
  }
  /**
   * 设置分页信息
   * @param page 页码
   * @param pageSize 每页数量
   */
  setPaginationInfo(page, pageSize) {
    this.store.currentPage = page;
    this.store.pageSize = pageSize;
    this.storeChange();
    this.triggerPaginationChange({
      page,
      pageSize,
      total: this.store.total,
      totalPages: Math.ceil(this.store.total / pageSize)
    });
  }
  /**
   * 便捷方法：切换分页并自动获取数据
   * @param page 页码
   * @param pageSize 每页数量（可选，不传则使用当前pageSize）
   * @returns 客户列表响应
   */
  async changeCustomerPage(page, pageSize) {
    const targetPageSize = pageSize || this.store.pageSize;
    this.setPaginationInfo(page, targetPageSize);
    const skip = page;
    const num = targetPageSize;
    return await this.getCustomerList({
      skip,
      num,
      ...this.store.searchParams
      // 使用存储的搜索条件
    });
  }
  /**
   * 滚动加载更多客户数据 - 数据会追加到现有列表中
   * @returns 客户列表响应
   */
  async loadMoreCustomers() {
    if (!this.store.hasMore || this.store.loadingMore) {
      return {
        list: [],
        total: this.store.total,
        page: this.store.currentPage,
        pageSize: this.store.pageSize
      };
    }
    const nextPage = this.store.currentPage + 1;
    try {
      this.store.loadingMore = true;
      this.store.error = null;
      const loadMoreParams = {
        skip: nextPage,
        num: this.store.pageSize,
        ...this.store.searchParams
        // 使用存储的搜索条件
      };
      const { customerList: newCustomers, total, page, pageSize } = await this.fetchCustomerListData(loadMoreParams);
      const updatedCustomerList = [...this.store.customerList, ...(0, import_lodash_es.cloneDeep)(newCustomers)];
      this.store.customerList = updatedCustomerList;
      this.store.currentPage = page;
      this.store.total = total;
      this.store.hasMore = page * pageSize < total;
      await this.core.effects.emit(
        `${this.name}:onScrollLoadMore`,
        {
          newCustomers,
          allCustomers: this.store.customerList,
          currentPage: page,
          hasMore: this.store.hasMore
        }
      );
      this.triggerPaginationChange({
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      });
      const response = {
        list: newCustomers,
        // 返回新加载的数据
        total,
        page,
        pageSize
      };
      return response;
    } catch (error) {
      await this.handleCustomerListError(error, "load more customers");
      throw error;
    } finally {
      this.store.loadingMore = false;
      this.storeChange();
      await this.core.effects.emit(
        `${this.name}:onCustomerListUpdate`,
        this.store
      );
    }
  }
  /**
   * 重置并重新开始滚动加载
   * @param params 查询参数
   * @returns 客户列表响应
   */
  async resetAndLoadCustomers(params = {}) {
    this.store.customerList = [];
    this.store.currentPage = 1;
    this.store.hasMore = true;
    this.store.loadingMore = false;
    const resetParams = {
      ...params,
      skip: 1,
      num: params.num || this.store.pageSize
    };
    const response = await this.getCustomerList(resetParams);
    await this.core.effects.emit(
      `${this.name}:onScrollLoadComplete`,
      {
        customers: this.store.customerList,
        total: this.store.total,
        hasMore: this.store.hasMore
      }
    );
    return response;
  }
  /**
   * 检查是否还有更多数据可以加载
   * @returns 是否还有更多数据
   */
  hasMoreCustomers() {
    return this.store.hasMore && !this.store.loadingMore;
  }
  /**
   * 获取当前的搜索条件
   * @returns 当前搜索条件
   */
  getCurrentSearchParams() {
    return (0, import_lodash_es.cloneDeep)(this.store.searchParams);
  }
  /**
   * 缓存状态变化
   */
  storeChange() {
    if (this.openCache) {
      const store = (0, import_lodash_es.cloneDeep)(this.store);
      this.checkSaveCache({
        cacheId: this.cacheId,
        fatherModule: this.fatherModule,
        store,
        cacheKey: ["customerList", "selectedCustomer", "total", "currentPage", "pageSize", "hasMore", "loadingMore", "searchParams"]
      });
    }
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CustomerModule,
  ...require("./types")
});
