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

Page({
  data: {
    passengers: [],
    searchKeyword: '',
    showSearchBar: false,
    filteredPassengers: [],
    showAddModal: false,
    editingPassenger: null,
    formData: {
      name: '',
      idtype: '身份证',
      idcard: '',
      phone: ''
    },
    idTypes: ['身份证', '回乡证', '护照', '台胞证'],
    idTypeIndex: 0
  },

  onLoad() {
    this.loadPassengers();
    
    // 添加数据变化监听器
    this.passengerDataListener = () => {
      this.loadPassengers();
    };
    passengerService.addListener(this.passengerDataListener);
  },

  onUnload() {
    // 移除监听器
    if (this.passengerDataListener) {
      passengerService.removeListener(this.passengerDataListener);
    }
  },

  onShow() {
    this.loadPassengers();
  },

  // 加载乘车人数据
  loadPassengers() {
    const passengers = passengerService.getAllPassengers();
    this.setData({ 
      passengers,
      filteredPassengers: passengers
    });
  },

  // 搜索功能
  toggleSearchBar() {
    const showSearchBar = !this.data.showSearchBar;
    this.setData({ 
      showSearchBar,
      searchKeyword: showSearchBar ? this.data.searchKeyword : ''
    });
    
    if (!showSearchBar) {
      this.setData({ filteredPassengers: this.data.passengers });
    }
  },

  onSearchInput(e) {
    const keyword = e.detail.value;
    const filteredPassengers = passengerService.searchPassengers(keyword);
    this.setData({ 
      searchKeyword: keyword,
      filteredPassengers 
    });
  },

  // 显示添加乘车人模态框
  showAddPassenger() {
    this.setData({
      showAddModal: true,
      editingPassenger: null,
      formData: {
        name: '',
        idtype: '身份证',
        idcard: '',
        phone: ''
      },
      idTypeIndex: 0
    });
  },

  // 编辑乘车人
  editPassenger(e) {
    const { id } = e.currentTarget.dataset;
    const passenger = passengerService.getPassengerById(id);
    
    if (passenger) {
      const idTypeIndex = this.data.idTypes.findIndex(type => type === passenger.idtype);
      this.setData({
        showAddModal: true,
        editingPassenger: passenger,
        formData: {
          name: passenger.name,
          idtype: passenger.idtype,
          idcard: passenger.idcard,
          phone: passenger.phone
        },
        idTypeIndex: idTypeIndex >= 0 ? idTypeIndex : 0
      });
    }
  },

  // 删除乘车人
  deletePassenger(e) {
    const { id } = e.currentTarget.dataset;
    const passenger = passengerService.getPassengerById(id);
    
    if (!passenger) {
      wx.showToast({ title: '乘车人不存在', icon: 'none' });
      return;
    }

    wx.showModal({
      title: '确认删除',
      content: `确定要删除乘车人"${passenger.name}"吗？`,
      confirmText: '删除',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          try {
            passengerService.deletePassenger(id);
            wx.showToast({ title: '删除成功', icon: 'success' });
          } catch (error) {
            wx.showToast({ title: error.message || '删除失败', icon: 'none' });
          }
        }
      }
    });
  },

  // 关闭模态框
  closeAddModal() {
    this.setData({ showAddModal: false });
  },

  // 表单输入处理
  onNameInput(e) {
    this.setData({ 'formData.name': e.detail.value });
  },

  onIdTypeChange(e) {
    const index = e.detail.value;
    this.setData({ 
      idTypeIndex: index,
      'formData.idtype': this.data.idTypes[index]
    });
  },

  onIdCardInput(e) {
    this.setData({ 'formData.idcard': e.detail.value });
  },

  onPhoneInput(e) {
    this.setData({ 'formData.phone': e.detail.value });
  },

  // 保存乘车人
  savePassenger() {
    const { formData, editingPassenger } = this.data;
    
    // 基本验证
    if (!formData.name.trim()) {
      wx.showToast({ title: '请输入姓名', icon: 'none' });
      return;
    }
    
    if (!formData.idcard.trim()) {
      wx.showToast({ title: '请输入证件号码', icon: 'none' });
      return;
    }
    
    if (!formData.phone.trim()) {
      wx.showToast({ title: '请输入手机号', icon: 'none' });
      return;
    }

    wx.showLoading({ title: editingPassenger ? '更新中...' : '保存中...' });

    try {
      if (editingPassenger) {
        // 更新现有乘车人
        passengerService.updatePassenger(editingPassenger.id, formData);
        wx.showToast({ title: '更新成功', icon: 'success' });
      } else {
        // 添加新乘车人
        passengerService.addPassenger(formData);
        wx.showToast({ title: '添加成功', icon: 'success' });
      }
      
      this.setData({ showAddModal: false });
    } catch (error) {
      wx.showToast({ title: error.message || '操作失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },

  // 快速添加（跳转到添加页面）
  quickAdd() {
    wx.navigateTo({
      url: '/pages/add-passenger/add-passenger?from=management'
    });
  },

  // 查看乘车人详情
  viewPassengerDetail(e) {
    const { id } = e.currentTarget.dataset;
    const passenger = passengerService.getPassengerById(id);
    
    if (passenger) {
      wx.showModal({
        title: '乘车人详情',
        content: `姓名：${passenger.name}\n证件类型：${passenger.idtype}\n证件号码：${passenger.idcard}\n手机号：${passenger.phone}\n创建时间：${new Date(passenger.createTime).toLocaleString()}`,
        showCancel: false,
        confirmText: '知道了'
      });
    }
  }
});

