// 会员体系管理工具类
class MemberService {
  constructor() {
    this.listeners = []; // 数据变化监听器
    this.MEMBER_LEVELS = {
      NORMAL: { 
        name: '普通会员', 
        threshold: 0, 
        discount: 1.0, 
        color: '#999999',
        icon: '👤'
      },
      SILVER: { 
        name: '白银会员', 
        threshold: 1000, 
        discount: 0.98, 
        color: '#C0C0C0',
        icon: '🥈'
      },
      GOLD: { 
        name: '黄金会员', 
        threshold: 2000, 
        discount: 0.96, 
        color: '#FFD700',
        icon: '🥇'
      }
    };

    this.POINTS_PRODUCTS = [
      {
        id: 'coupon_3',
        name: '3元优惠券',
        points: 288,
        value: 3,
        description: '购票时可直接抵扣3元',
        validDays: 30,
        icon: '🎫'
      },
      {
        id: 'coupon_6',
        name: '6元优惠券',
        points: 529,
        value: 6,
        description: '购票时可直接抵扣6元',
        validDays: 30,
        icon: '🎟️'
      }
    ];
  }

  // 获取用户会员信息
  getUserMemberInfo() {
    const memberInfo = wx.getStorageSync('memberInfo') || {
      memberValue: 0,
      points: 0,
      level: 'NORMAL',
      joinDate: new Date().toISOString(),
      totalSpent: 0,
      pointsHistory: [],
      coupons: []
    };
    
    // 更新会员等级
    memberInfo.level = this.calculateMemberLevel(memberInfo.memberValue);
    
    return memberInfo;
  }

  // 保存用户会员信息
  saveMemberInfo(memberInfo) {
    wx.setStorageSync('memberInfo', memberInfo);
    
    // 通知所有监听器数据已更新
    this.notifyListeners(memberInfo);
  }

  // 添加数据变化监听器
  addListener(callback) {
    this.listeners.push(callback);
  }

  // 移除监听器
  removeListener(callback) {
    const index = this.listeners.indexOf(callback);
    if (index > -1) {
      this.listeners.splice(index, 1);
    }
  }

  // 通知所有监听器
  notifyListeners(memberInfo) {
    this.listeners.forEach(callback => {
      try {
        callback(memberInfo);
      } catch (error) {
        console.error('监听器回调执行失败:', error);
      }
    });
  }

  // 计算会员等级
  calculateMemberLevel(memberValue) {
    if (memberValue >= this.MEMBER_LEVELS.GOLD.threshold) {
      return 'GOLD';
    } else if (memberValue >= this.MEMBER_LEVELS.SILVER.threshold) {
      return 'SILVER';
    } else {
      return 'NORMAL';
    }
  }

  // 获取会员等级信息
  getMemberLevelInfo(level) {
    return this.MEMBER_LEVELS[level] || this.MEMBER_LEVELS.NORMAL;
  }

  // 消费时增加会员值和积分
  addMemberValueAndPoints(amount) {
    const memberInfo = this.getUserMemberInfo();
    const oldLevel = memberInfo.level;
    
    // 消费一元累计会员值一点和积分一分
    const addedValue = Math.floor(amount);
    const addedPoints = Math.floor(amount);
    
    memberInfo.memberValue += addedValue;
    memberInfo.points += addedPoints;
    memberInfo.totalSpent += amount;
    
    // 添加积分历史记录
    memberInfo.pointsHistory.unshift({
      type: 'earn',
      amount: addedPoints,
      description: `消费获得积分`,
      date: new Date().toISOString(),
      orderId: Date.now().toString()
    });
    
    // 检查等级变化
    const newLevel = this.calculateMemberLevel(memberInfo.memberValue);
    let levelUpgraded = false;
    
    if (oldLevel !== newLevel) {
      levelUpgraded = true;
      memberInfo.level = newLevel;
      
      // 添加升级记录
      memberInfo.pointsHistory.unshift({
        type: 'upgrade',
        amount: 0,
        description: `恭喜升级为${this.MEMBER_LEVELS[newLevel].name}`,
        date: new Date().toISOString()
      });
    }
    
    this.saveMemberInfo(memberInfo);
    
    return {
      memberInfo,
      addedValue,
      addedPoints,
      levelUpgraded,
      newLevel: levelUpgraded ? newLevel : null
    };
  }

  // 使用积分兑换商品
  exchangePoints(productId) {
    const memberInfo = this.getUserMemberInfo();
    const product = this.POINTS_PRODUCTS.find(p => p.id === productId);
    
    if (!product) {
      return { success: false, message: '商品不存在' };
    }
    
    if (memberInfo.points < product.points) {
      return { success: false, message: '积分不足' };
    }
    
    // 扣除积分
    memberInfo.points -= product.points;
    
    // 添加优惠券
    const coupon = {
      id: Date.now().toString(),
      name: product.name,
      value: product.value,
      used: false,
      expireDate: new Date(Date.now() + product.validDays * 24 * 60 * 60 * 1000).toISOString(),
      createDate: new Date().toISOString()
    };
    
    memberInfo.coupons.push(coupon);
    
    // 添加积分使用记录
    memberInfo.pointsHistory.unshift({
      type: 'exchange',
      amount: -product.points,
      description: `兑换${product.name}`,
      date: new Date().toISOString(),
      couponId: coupon.id
    });
    
    this.saveMemberInfo(memberInfo);
    
    return { 
      success: true, 
      message: '兑换成功',
      coupon,
      memberInfo 
    };
  }

  // 获取可用优惠券
  getAvailableCoupons() {
    const memberInfo = this.getUserMemberInfo();
    const now = new Date();
    
    return memberInfo.coupons.filter(coupon => 
      !coupon.used && new Date(coupon.expireDate) > now
    );
  }

  // 使用优惠券
  useCoupon(couponId) {
    const memberInfo = this.getUserMemberInfo();
    const coupon = memberInfo.coupons.find(c => c.id === couponId);
    
    if (!coupon || coupon.used || new Date(coupon.expireDate) <= new Date()) {
      return { success: false, message: '优惠券无效或已过期' };
    }
    
    coupon.used = true;
    coupon.usedDate = new Date().toISOString();
    
    this.saveMemberInfo(memberInfo);
    
    return { success: true, coupon };
  }

  // 获取会员折扣
  getMemberDiscount(level = null) {
    const memberInfo = this.getUserMemberInfo();
    const currentLevel = level || memberInfo.level;
    return this.MEMBER_LEVELS[currentLevel].discount;
  }

  // 清理过期积分（每年过期）
  cleanExpiredPoints() {
    const memberInfo = this.getUserMemberInfo();
    const oneYearAgo = new Date(Date.now() - 365 * 24 * 60 * 60 * 1000);
    
    // 保留一年内的积分历史
    const validHistory = memberInfo.pointsHistory.filter(h => 
      new Date(h.date) > oneYearAgo
    );
    
    // 重新计算积分（只计算一年内的收入积分）
    const validPoints = validHistory.reduce((total, h) => {
      if (h.type === 'earn' && h.amount > 0) {
        return total + h.amount;
      } else if (h.type === 'exchange' && h.amount < 0) {
        return total + h.amount; // h.amount 已经是负数
      }
      return total;
    }, 0);
    
    memberInfo.points = Math.max(0, validPoints);
    memberInfo.pointsHistory = validHistory;
    
    this.saveMemberInfo(memberInfo);
    
    return memberInfo;
  }

  // 获取下一等级信息
  getNextLevelInfo(currentLevel) {
    switch (currentLevel) {
      case 'NORMAL':
        return {
          nextLevel: 'SILVER',
          nextLevelInfo: this.MEMBER_LEVELS.SILVER,
          needed: this.MEMBER_LEVELS.SILVER.threshold
        };
      case 'SILVER':
        return {
          nextLevel: 'GOLD',
          nextLevelInfo: this.MEMBER_LEVELS.GOLD,
          needed: this.MEMBER_LEVELS.GOLD.threshold
        };
      case 'GOLD':
        return {
          nextLevel: null,
          nextLevelInfo: null,
          needed: 0
        };
      default:
        return null;
    }
  }
}

// 导出单例
const memberService = new MemberService();
export default memberService;
