/**
 * 车辆管理API接口系统
 * 支持车辆型号、车牌号码、司机信息管理
 */

class VehicleApiService {
  constructor() {
    this.listeners = []; // 数据变化监听器
    this.initVehicleData();
  }

  // 初始化车辆数据
  initVehicleData() {
    const vehicles = this.getAllVehicles();
    if (vehicles.length === 0) {
      const sampleVehicles = [
        {
          id: 'vehicle_001',
          activityId: 'activity_001',
          activityName: '北京春季音乐节',
          vehicleModel: '宇通ZK6127H',
          licensePlate: '京A12345',
          capacity: 50,
          type: 'bus', // bus, business, charter
          status: 'active', // active, inactive, maintenance, retired
          driver: {
            id: 'driver_001',
            name: '张师傅',
            phone: '13800138001',
            licenseNumber: 'A123456789',
            licenseType: 'A1',
            experience: '5年',
            rating: 4.8,
            status: 'active'
          },
          features: ['空调', 'WiFi', '充电插座', '安全带'],
          insurance: {
            company: '中国人民保险公司',
            policyNumber: 'PIC2024001',
            expiryDate: '2025-01-15'
          },
          maintenance: {
            lastService: '2024-01-10',
            nextService: '2024-04-10',
            mileage: 150000
          },
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        {
          id: 'vehicle_002',
          activityId: 'activity_001',
          activityName: '北京春季音乐节',
          vehicleModel: '奔驰V级',
          licensePlate: '京B67890',
          capacity: 20,
          type: 'business',
          status: 'active',
          driver: {
            id: 'driver_002',
            name: '李师傅',
            phone: '13800138002',
            licenseNumber: 'A987654321',
            licenseType: 'A2',
            experience: '8年',
            rating: 4.9,
            status: 'active'
          },
          features: ['真皮座椅', '独立空调', 'WiFi', '充电插座', '小冰箱'],
          insurance: {
            company: '太平洋保险公司',
            policyNumber: 'TPI2024002',
            expiryDate: '2025-02-20'
          },
          maintenance: {
            lastService: '2024-01-05',
            nextService: '2024-04-05',
            mileage: 80000
          },
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        {
          id: 'vehicle_003',
          activityId: 'activity_001',
          activityName: '北京春季音乐节',
          vehicleModel: '奔驰V级豪华版',
          licensePlate: '京C11111',
          capacity: 6,
          type: 'charter',
          status: 'active',
          driver: {
            id: 'driver_003',
            name: '王师傅',
            phone: '13800138003',
            licenseNumber: 'A555666777',
            licenseType: 'A1',
            experience: '10年',
            rating: 5.0,
            status: 'active'
          },
          features: ['豪华真皮座椅', '独立空调', 'WiFi', '充电插座', '小冰箱', '娱乐系统'],
          insurance: {
            company: '中国平安保险公司',
            policyNumber: 'PAI2024003',
            expiryDate: '2025-03-10'
          },
          maintenance: {
            lastService: '2024-01-01',
            nextService: '2024-04-01',
            mileage: 50000
          },
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        }
      ];
      this.saveVehicles(sampleVehicles);
    }
  }

  // 获取所有车辆
  getAllVehicles() {
    try {
      return wx.getStorageSync('vehicles') || [];
    } catch (error) {
      console.error('获取车辆数据失败:', error);
      return [];
    }
  }

  // 保存车辆数据
  saveVehicles(vehicles) {
    try {
      wx.setStorageSync('vehicles', vehicles);
      this.notifyListeners(vehicles);
      return true;
    } catch (error) {
      console.error('保存车辆数据失败:', error);
      return false;
    }
  }

  // 根据ID获取车辆
  getVehicleById(vehicleId) {
    const vehicles = this.getAllVehicles();
    return vehicles.find(vehicle => vehicle.id === vehicleId);
  }

  // 根据活动ID获取车辆
  getVehiclesByActivityId(activityId) {
    const vehicles = this.getAllVehicles();
    return vehicles.filter(vehicle => vehicle.activityId === activityId);
  }

  // 根据车牌号获取车辆
  getVehicleByLicensePlate(licensePlate) {
    const vehicles = this.getAllVehicles();
    return vehicles.find(vehicle => vehicle.licensePlate === licensePlate);
  }

  // 创建车辆
  createVehicle(vehicleData) {
    const vehicles = this.getAllVehicles();
    const newVehicle = {
      ...vehicleData,
      id: this.generateVehicleId(),
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      status: vehicleData.status || 'active'
    };
    
    vehicles.push(newVehicle);
    this.saveVehicles(vehicles);
    return newVehicle;
  }

  // 更新车辆
  updateVehicle(vehicleId, updateData) {
    const vehicles = this.getAllVehicles();
    const vehicleIndex = vehicles.findIndex(vehicle => vehicle.id === vehicleId);
    
    if (vehicleIndex === -1) {
      throw new Error('车辆不存在');
    }

    vehicles[vehicleIndex] = {
      ...vehicles[vehicleIndex],
      ...updateData,
      updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
    };

    this.saveVehicles(vehicles);
    return vehicles[vehicleIndex];
  }

  // 删除车辆
  deleteVehicle(vehicleId) {
    const vehicles = this.getAllVehicles();
    const filteredVehicles = vehicles.filter(vehicle => vehicle.id !== vehicleId);
    
    if (filteredVehicles.length === vehicles.length) {
      throw new Error('车辆不存在');
    }

    this.saveVehicles(filteredVehicles);
    return true;
  }

  // 更新车辆司机信息
  updateVehicleDriver(vehicleId, driverData) {
    const vehicles = this.getAllVehicles();
    const vehicleIndex = vehicles.findIndex(vehicle => vehicle.id === vehicleId);
    
    if (vehicleIndex === -1) {
      throw new Error('车辆不存在');
    }

    vehicles[vehicleIndex].driver = {
      ...vehicles[vehicleIndex].driver,
      ...driverData
    };
    vehicles[vehicleIndex].updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19);

    this.saveVehicles(vehicles);
    return vehicles[vehicleIndex];
  }

  // 搜索车辆
  searchVehicles(searchParams) {
    const vehicles = this.getAllVehicles();
    let filteredVehicles = [...vehicles];

    // 按活动ID搜索
    if (searchParams.activityId) {
      filteredVehicles = filteredVehicles.filter(vehicle => 
        vehicle.activityId === searchParams.activityId
      );
    }

    // 按车辆型号搜索
    if (searchParams.vehicleModel) {
      filteredVehicles = filteredVehicles.filter(vehicle => 
        vehicle.vehicleModel.toLowerCase().includes(searchParams.vehicleModel.toLowerCase())
      );
    }

    // 按车牌号搜索
    if (searchParams.licensePlate) {
      filteredVehicles = filteredVehicles.filter(vehicle => 
        vehicle.licensePlate.includes(searchParams.licensePlate)
      );
    }

    // 按车辆类型搜索
    if (searchParams.type) {
      filteredVehicles = filteredVehicles.filter(vehicle => 
        vehicle.type === searchParams.type
      );
    }

    // 按状态搜索
    if (searchParams.status) {
      filteredVehicles = filteredVehicles.filter(vehicle => 
        vehicle.status === searchParams.status
      );
    }

    // 按司机姓名搜索
    if (searchParams.driverName) {
      filteredVehicles = filteredVehicles.filter(vehicle => 
        vehicle.driver.name.toLowerCase().includes(searchParams.driverName.toLowerCase())
      );
    }

    // 按司机电话搜索
    if (searchParams.driverPhone) {
      filteredVehicles = filteredVehicles.filter(vehicle => 
        vehicle.driver.phone.includes(searchParams.driverPhone)
      );
    }

    // 排序
    const sortBy = searchParams.sortBy || 'createTime';
    const sortOrder = searchParams.sortOrder || 'desc';
    
    filteredVehicles.sort((a, b) => {
      let aValue = a[sortBy];
      let bValue = b[sortBy];
      
      if (sortBy === 'createTime' || sortBy === 'updateTime') {
        aValue = new Date(aValue);
        bValue = new Date(bValue);
      }
      
      if (sortOrder === 'asc') {
        return aValue > bValue ? 1 : -1;
      } else {
        return aValue < bValue ? 1 : -1;
      }
    });

    return {
      vehicles: filteredVehicles,
      total: filteredVehicles.length,
      page: searchParams.page || 1,
      pageSize: searchParams.pageSize || 20
    };
  }

  // 获取车辆统计信息
  getVehicleStatistics() {
    const vehicles = this.getAllVehicles();
    
    const stats = {
      total: vehicles.length,
      byType: {},
      byStatus: {},
      byActivity: {},
      totalCapacity: 0,
      activeDrivers: 0
    };

    vehicles.forEach(vehicle => {
      // 按类型统计
      stats.byType[vehicle.type] = (stats.byType[vehicle.type] || 0) + 1;
      
      // 按状态统计
      stats.byStatus[vehicle.status] = (stats.byStatus[vehicle.status] || 0) + 1;
      
      // 按活动统计
      stats.byActivity[vehicle.activityId] = (stats.byActivity[vehicle.activityId] || 0) + 1;
      
      // 总容量统计
      stats.totalCapacity += vehicle.capacity;
      
      // 活跃司机统计
      if (vehicle.driver.status === 'active') {
        stats.activeDrivers++;
      }
    });

    return stats;
  }

  // 批量更新车辆状态
  batchUpdateVehicleStatus(vehicleIds, status) {
    const vehicles = this.getAllVehicles();
    const updatedVehicles = vehicles.map(vehicle => {
      if (vehicleIds.includes(vehicle.id)) {
        return {
          ...vehicle,
          status,
          updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
        };
      }
      return vehicle;
    });

    this.saveVehicles(updatedVehicles);
    return true;
  }

  // 获取可用车辆（用于订单分配）
  getAvailableVehicles(activityId, type = null, capacity = null) {
    const vehicles = this.getVehiclesByActivityId(activityId);
    
    return vehicles.filter(vehicle => {
      // 状态检查
      if (vehicle.status !== 'active') return false;
      if (vehicle.driver.status !== 'active') return false;
      
      // 类型检查
      if (type && vehicle.type !== type) return false;
      
      // 容量检查
      if (capacity && vehicle.capacity < capacity) return false;
      
      return true;
    });
  }

  // 分配车辆到订单
  assignVehicleToOrder(orderId, vehicleId) {
    const vehicles = this.getAllVehicles();
    const vehicleIndex = vehicles.findIndex(vehicle => vehicle.id === vehicleId);
    
    if (vehicleIndex === -1) {
      throw new Error('车辆不存在');
    }

    // 更新车辆状态为已分配
    vehicles[vehicleIndex].currentOrder = orderId;
    vehicles[vehicleIndex].updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19);

    this.saveVehicles(vehicles);
    return vehicles[vehicleIndex];
  }

  // 释放车辆（订单完成后）
  releaseVehicle(vehicleId) {
    const vehicles = this.getAllVehicles();
    const vehicleIndex = vehicles.findIndex(vehicle => vehicle.id === vehicleId);
    
    if (vehicleIndex === -1) {
      throw new Error('车辆不存在');
    }

    // 清除当前订单
    delete vehicles[vehicleIndex].currentOrder;
    vehicles[vehicleIndex].updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19);

    this.saveVehicles(vehicles);
    return vehicles[vehicleIndex];
  }

  // 导出车辆数据
  exportVehicles(searchParams = {}) {
    const result = this.searchVehicles(searchParams);
    return {
      vehicles: result.vehicles,
      exportTime: new Date().toISOString(),
      total: result.total,
      searchParams
    };
  }

  // 生成车辆ID
  generateVehicleId() {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `vehicle_${timestamp}_${random}`;
  }

  // 监听器管理
  addListener(callback) {
    this.listeners.push(callback);
  }

  removeListener(callback) {
    const index = this.listeners.indexOf(callback);
    if (index > -1) {
      this.listeners.splice(index, 1);
    }
  }

  notifyListeners(vehicles) {
    this.listeners.forEach(callback => {
      try {
        callback(vehicles);
      } catch (error) {
        console.error('车辆数据监听器回调执行失败:', error);
      }
    });
  }

  // 同步车辆数据
  syncVehicleData() {
    const vehicles = this.getAllVehicles();
    this.notifyListeners(vehicles);
    return vehicles;
  }
}

// 创建单例实例
const vehicleApiService = new VehicleApiService();

export default vehicleApiService;

