import memberService from '../../utils/member.js';
import passengerService from '../../utils/passenger.js';

Page({
  data:{
    schedule: {
      price: 88,
      left: 12,
      time: '09:00',
      model: '宇通大巴',
      fromLoc: '东直门地铁站A口',
      toLoc: '上海体育馆',
      type: 'bus',
      duration: '约5小时',
      refundPolicy: '行程前72小时之前退票无手续费'
    },
    passengers: [],
    phoneNumber: '',
    hasPhoneNumber: false,
    activityName: '',
    totalPrice: 0,
    isCharter: false,
    memberInfo: {},
    memberLevel: {},
    originalPrice: 0,
    memberDiscount: 0,
    availableCoupons: [],
    selectedCoupon: null,
    couponDiscount: 0,
    savedPassengers: [],
    showPassengerSelector: false
  },
  
  onLoad(options){
    const { scheduleId, activityName, type } = options;
    const isCharter = type === 'business-charter';
    
    // 模拟根据scheduleId获取班次详情
    let schedule = {
      price: isCharter ? 1200 : 88,
      left: isCharter ? 6 : 12,
      time: isCharter ? '任意时间' : '09:00',
      model: isCharter ? '奔驰V级商务车' : '宇通大巴',
      fromLoc: isCharter ? '指定地点接送' : '东直门地铁站A口',
      toLoc: isCharter ? '活动现场' : '上海体育馆',
      type: type,
      duration: isCharter ? '约4小时' : '约5小时',
      refundPolicy: isCharter ? '预约后可协商退改' : '行程前72小时之前退票无手续费'
    };
    
    this.setData({
      schedule,
      activityName: activityName || '活动',
      isCharter
    });
    
    this.loadMemberInfo();
    this.loadSavedPassengers();
    this.calculateTotalPrice();
  },
  
  onShow() {
    this.loadMemberInfo();
    this.loadSavedPassengers();
    this.calculateTotalPrice();
  },

  // 加载会员信息
  loadMemberInfo() {
    const memberInfo = memberService.getUserMemberInfo();
    const memberLevel = memberService.getMemberLevelInfo(memberInfo.level);
    const availableCoupons = memberService.getAvailableCoupons();
    
    this.setData({
      memberInfo,
      memberLevel,
      availableCoupons
    });
  },

  // 加载已保存的乘车人
  loadSavedPassengers() {
    const savedPassengers = passengerService.getAllPassengers();
    this.setData({ savedPassengers });
  },

  // 选择优惠券
  selectCoupon() {
    const { availableCoupons } = this.data;
    
    if (availableCoupons.length === 0) {
      wx.showToast({
        title: '暂无可用优惠券',
        icon: 'none'
      });
      return;
    }
    
    const items = ['不使用优惠券', ...availableCoupons.map(c => `${c.name} (¥${c.value})`)];
    
    wx.showActionSheet({
      itemList: items,
      success: (res) => {
        if (res.tapIndex === 0) {
          // 不使用优惠券
          this.setData({
            selectedCoupon: null,
            couponDiscount: 0
          });
        } else {
          // 选择优惠券
          const coupon = availableCoupons[res.tapIndex - 1];
          this.setData({
            selectedCoupon: coupon,
            couponDiscount: coupon.value
          });
        }
        this.calculateTotalPrice();
      }
    });
  },
  
  calculateTotalPrice() {
    const { schedule, passengers, isCharter, memberLevel, couponDiscount } = this.data;
    let originalPrice = 0;
    
    if (isCharter) {
      // 包车按车计费
      originalPrice = schedule.price;
    } else {
      // 拼车按人计费
      originalPrice = passengers.length * schedule.price;
    }
    
    // 应用会员折扣
    const memberDiscount = memberLevel.discount || 1.0;
    let totalPrice = originalPrice * memberDiscount;
    
    // 应用优惠券折扣
    totalPrice = Math.max(0, totalPrice - (couponDiscount || 0));
    
    // 保留两位小数
    totalPrice = Math.round(totalPrice * 100) / 100;
    
    const memberDiscountAmount = originalPrice - (originalPrice * memberDiscount);
    
    this.setData({ 
      originalPrice,
      totalPrice,
      memberDiscount: memberDiscountAmount
    });
  },
  
  onGetPhoneNumber(e){
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      // 实际项目中需要发送code到后端获取手机号
      this.setData({
        phoneNumber: '138****8888', // 模拟获取到的手机号
        hasPhoneNumber: true
      });
      wx.showToast({title:'获取手机号成功',icon:'success'});
    } else {
      wx.showToast({title:'获取手机号失败',icon:'none'});
    }
  },
  
  addPassenger(){
    if (!this.data.hasPhoneNumber) {
      wx.showToast({title:'请先获取手机号',icon:'none'});
      return;
    }

    const { savedPassengers } = this.data;
    
    if (savedPassengers.length > 0) {
      // 如果有已保存的乘车人，显示选择器
      this.setData({ showPassengerSelector: true });
    } else {
      // 没有已保存的乘车人，直接跳转到添加页面
      wx.navigateTo({
        url:'/pages/add-passenger/add-passenger'
      });
    }
  },

  // 显示乘车人选择器
  showPassengerSelector() {
    this.setData({ showPassengerSelector: true });
  },

  // 关闭乘车人选择器
  closePassengerSelector() {
    this.setData({ showPassengerSelector: false });
  },

  // 选择已有乘车人
  selectSavedPassenger(e) {
    const { id } = e.currentTarget.dataset;
    const passenger = passengerService.getPassengerById(id);
    
    if (passenger) {
      // 检查是否已经添加过这个乘车人
      const existingPassenger = this.data.passengers.find(p => p.idcard === passenger.idcard);
      if (existingPassenger) {
        wx.showToast({title:'该乘车人已添加',icon:'none'});
        return;
      }

      // 添加到当前订单的乘车人列表
      const passengers = [...this.data.passengers, passenger];
      this.setData({ 
        passengers,
        showPassengerSelector: false
      });
      this.calculateTotalPrice();
      
      wx.showToast({title:'添加成功',icon:'success'});
    }
  },

  // 添加新乘车人
  addNewPassenger() {
    this.setData({ showPassengerSelector: false });
    wx.navigateTo({
      url:'/pages/add-passenger/add-passenger'
    });
  },

  // 管理乘车人
  managePassengers() {
    this.setData({ showPassengerSelector: false });
    wx.navigateTo({
      url:'/pages/passenger-management/passenger-management'
    });
  },
  
  deletePassenger(e) {
    const index = e.currentTarget.dataset.index;
    const passengers = this.data.passengers;
    passengers.splice(index, 1);
    this.setData({ passengers });
    this.calculateTotalPrice();
  },
  
  pay(){
    if (!this.data.hasPhoneNumber) {
      wx.showToast({title:'请先获取手机号',icon:'none'});
      return;
    }
    
    if (this.data.passengers.length === 0) {
      wx.showToast({title:'请添加乘车人信息',icon:'none'});
      return;
    }
    
    if (!this.data.isCharter && this.data.passengers.length > this.data.schedule.left) {
      wx.showToast({title:`最多只能购买${this.data.schedule.left}张票`,icon:'none'});
      return;
    }
    
    // 发起微信支付
    this.requestPayment();
  },
  
  requestPayment() {
    // 模拟微信支付
    wx.showLoading({title: '发起支付...'});
    
    setTimeout(() => {
      wx.hideLoading();
      wx.requestPayment({
        timeStamp: String(Date.now()),
        nonceStr: 'randomstring',
        package: 'prepay_id=mock_prepay_id',
        signType: 'MD5',
        paySign: 'mock_pay_sign',
        success: (res) => {
          // 支付成功，添加会员值和积分
          const { totalPrice, selectedCoupon, schedule } = this.data;
          
          // 使用优惠券
          if (selectedCoupon) {
            memberService.useCoupon(selectedCoupon.id);
          }
          
          // 添加会员值和积分
          const result = memberService.addMemberValueAndPoints(totalPrice);
          
          // 生成订单ID
          const orderId = this.generateOrderId();
          const orderType = schedule.type || 'bus';
          
          let successUrl = `/pages/pay-success/pay-success?totalPrice=${totalPrice}&passengerCount=${this.data.passengers.length}&orderId=${orderId}&orderType=${orderType}`;
          
          // 如果有等级升级，添加升级信息
          if (result.levelUpgraded) {
            successUrl += `&levelUpgraded=true&newLevel=${result.newLevel}&addedPoints=${result.addedPoints}&addedValue=${result.addedValue}`;
          } else {
            successUrl += `&addedPoints=${result.addedPoints}&addedValue=${result.addedValue}`;
          }
          
          wx.navigateTo({
            url: successUrl
          });
        },
        fail: (res) => {
          wx.showToast({title:'支付失败',icon:'none'});
        }
      });
    }, 1000);
  },

  // 生成订单ID
  generateOrderId() {
    const now = new Date();
    const timestamp = now.getTime();
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `ORDER_${timestamp}_${random}`;
  }
});