import memberService from '../../utils/member.js';
import driverApiService from '../../utils/driver-api.js';

Page({
  data: {
    totalPrice: 0,
    passengerCount: 0,
    addedPoints: 0,
    addedValue: 0,
    levelUpgraded: false,
    newLevel: '',
    newLevelInfo: {},
    orderId: '',
    orderType: 'bus',
    assigningDriver: false,
    driverAssigned: false,
    driverInfo: null
  },

  onLoad(options) {
    const { 
      totalPrice = 0, 
      passengerCount = 0, 
      addedPoints = 0, 
      addedValue = 0, 
      levelUpgraded = false, 
      newLevel = '',
      orderId = '',
      orderType = 'bus'
    } = options;

    let newLevelInfo = {};
    if (levelUpgraded === 'true' && newLevel) {
      newLevelInfo = memberService.getMemberLevelInfo(newLevel);
    }

    this.setData({
      totalPrice: parseFloat(totalPrice),
      passengerCount: parseInt(passengerCount),
      addedPoints: parseInt(addedPoints),
      addedValue: parseInt(addedValue),
      levelUpgraded: levelUpgraded === 'true',
      newLevel,
      newLevelInfo,
      orderId,
      orderType
    });

    // 支付成功后自动分配司机
    this.assignDriver();
  },

  gotoOrder(){
    wx.redirectTo({url:'/pages/orders/orders'});
  },

  gotoPointsMall() {
    wx.navigateTo({
      url: '/pages/points-mall/points-mall'
    });
  },

  // 分配司机
  async assignDriver() {
    const { orderId, orderType } = this.data;
    
    if (!orderId) {
      console.warn('订单ID为空，跳过司机分配');
      return;
    }

    this.setData({ assigningDriver: true });

    try {
      const result = await driverApiService.assignDriverToOrder(orderId, orderType);
      
      this.setData({
        assigningDriver: false,
        driverAssigned: true,
        driverInfo: result.data
      });

      wx.showToast({
        title: '司机分配成功',
        icon: 'success'
      });

      // 开始模拟司机操作流程（仅用于演示）
      driverApiService.simulateDriverActions(orderId, result.data.driverId);

    } catch (error) {
      this.setData({ assigningDriver: false });
      console.error('司机分配失败:', error);
      
      wx.showModal({
        title: '司机分配失败',
        content: error.message || '暂时无法分配司机，请稍后重试',
        showCancel: false,
        confirmText: '知道了'
      });
    }
  }
});