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

Page({
  data:{
    name:'',
    idTypes:['身份证','回乡证','护照','台胞证'],
    idTypeIndex:0,
    idcard:'',
    phone:'',
    from: '' // 来源页面：order（订单页面）或 management（管理页面）
  },

  onLoad(options) {
    // 获取来源页面参数
    this.setData({ from: options.from || 'order' });
  },

  onNameInput(e){this.setData({name:e.detail.value})},
  onIdTypeChange(e){this.setData({idTypeIndex:e.detail.value})},
  onIdCardInput(e){this.setData({idcard:e.detail.value})},
  onPhoneInput(e){this.setData({phone:e.detail.value})},
  savePassenger(){
    const { name, idcard, phone, idTypes, idTypeIndex, from } = this.data;
    
    if(!name || !idcard || !phone){
      wx.showToast({title:'请填写完整',icon:'none'});
      return;
    }

    const passengerData = {
      name: name.trim(),
      idtype: idTypes[idTypeIndex],
      idcard: idcard.trim(),
      phone: phone.trim()
    };

    wx.showLoading({ title: '保存中...' });

    try {
      // 保存到乘车人管理系统
      const savedPassenger = passengerService.addPassenger(passengerData);
      
      // 如果来自订单页面，同时添加到订单的乘车人列表
      if (from === 'order') {
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];
        
        if (prevPage && prevPage.route === 'pages/order/order') {
          let passengers = prevPage.data.passengers || [];
          passengers.push(savedPassenger);
          prevPage.setData({ passengers });
        }
      }

      wx.hideLoading();
      wx.showToast({ title: '保存成功', icon: 'success' });
      
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      
    } catch (error) {
      wx.hideLoading();
      wx.showToast({ 
        title: error.message || '保存失败', 
        icon: 'none' 
      });
    }
  }
})