import { defineStore } from 'pinia' import { getCustomerList } from '@/common/api/customer' /** * 客户管理 Store * 用于管理客户列表数据缓存,避免重复请求 */ export const useCustomerStore = defineStore('customer', { state: () => { return { // 全部客户列表缓存(不包含筛选条件) allCustomers: [], // 缓存时间戳 cacheTimestamp: null, // 缓存有效期(毫秒),默认5分钟 cacheExpireTime: 5 * 60 * 1000, // 加载状态 loading: false, // 最后请求的参数(用于判断是否需要刷新) lastParams: null } }, getters: { /** * 判断缓存是否有效 */ isCacheValid: (state) => { if (!state.cacheTimestamp || state.allCustomers.length === 0) { return false } const now = Date.now() return (now - state.cacheTimestamp) < state.cacheExpireTime }, /** * 根据状态筛选客户列表 * @param {string} status - 筛选状态:'1' 正在跟进, '2' 待跟进, '' 全部 */ getFilteredCustomers: (state) => { return (status = '') => { if (!status) { return state.allCustomers } return state.allCustomers.filter(customer => customer.status === status) } } }, actions: { /** * 获取客户列表(带缓存机制) * @param {Object} params - 请求参数 * @param {boolean} forceRefresh - 是否强制刷新(忽略缓存) * @returns {Promise} 返回客户列表 */ async fetchCustomerList(params = {}, forceRefresh = false) { // 如果强制刷新或缓存无效,则重新请求 if (forceRefresh || !this.isCacheValid) { this.loading = true try { // 请求全部数据(不传 statusList 参数) const res = await getCustomerList({}) // API返回格式: { total: number, rows: array } let customerList = [] if (res && res.rows && Array.isArray(res.rows)) { customerList = res.rows } else if (res && Array.isArray(res)) { customerList = res } // 更新缓存 this.allCustomers = customerList this.cacheTimestamp = Date.now() this.lastParams = params return customerList } catch (error) { console.error('获取客户列表失败:', error) throw error } finally { this.loading = false } } // 使用缓存数据 return this.allCustomers }, /** * 根据筛选条件获取客户列表(优先使用缓存) * @param {Object} params - 请求参数(包含 statusList 等筛选条件) * @param {boolean} forceRefresh - 是否强制刷新 * @returns {Promise} 返回筛选后的客户列表 */ async getCustomerListByFilter(params = {}, forceRefresh = false) { // 先确保有缓存数据 await this.fetchCustomerList({}, forceRefresh) // 如果有筛选条件,进行前端筛选 if (params.statusList && Array.isArray(params.statusList) && params.statusList.length > 0) { const status = params.statusList[0] // 取第一个状态 return this.getFilteredCustomers(status) } // 返回全部数据 return this.allCustomers }, /** * 清除缓存 */ clearCache() { this.allCustomers = [] this.cacheTimestamp = null this.lastParams = null }, /** * 更新单个客户信息(用于编辑后更新缓存) * @param {string} customerId - 客户ID * @param {Object} updatedData - 更新的数据 */ updateCustomer(customerId, updatedData) { const index = this.allCustomers.findIndex(c => c.id === customerId) if (index !== -1) { this.allCustomers[index] = { ...this.allCustomers[index], ...updatedData } } }, /** * 添加新客户到缓存(用于新增后更新缓存) * @param {Object} newCustomer - 新客户数据 */ addCustomer(newCustomer) { this.allCustomers.unshift(newCustomer) }, /** * 删除客户(用于删除后更新缓存) * @param {string} customerId - 客户ID */ removeCustomer(customerId) { const index = this.allCustomers.findIndex(c => c.id === customerId) if (index !== -1) { this.allCustomers.splice(index, 1) } } } })