/**
 * 司机管理API接口系统
 * 支持司机信息的增删改查、状态管理、车辆分配
 */

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

  // 初始化司机数据
  initDriverData() {
    const drivers = this.getAllDrivers();
    if (drivers.length === 0) {
      const sampleDrivers = [
        {
          id: 'driver_001',
          name: '张师傅',
          phone: '13800138001',
          idCard: '110101199001011234',
          licenseNumber: 'A123456789',
          licenseType: 'A1',
          licenseExpiry: '2026-01-15',
          experience: '5年',
          rating: 4.8,
          totalTrips: 1250,
          totalDistance: 150000,
          status: 'active', // active, inactive, busy, vacation
          vehicleId: 'vehicle_001',
          vehicleModel: '宇通ZK6127H',
          licensePlate: '京A12345',
          emergencyContact: {
            name: '张太太',
            phone: '13900139001',
            relationship: '配偶'
          },
          address: '北京市朝阳区某某街道123号',
          joinDate: '2019-03-15',
          lastLogin: '2024-01-15 08:30:00',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00',
          skills: ['安全驾驶', '客户服务', '路线熟悉'],
          certifications: ['驾驶证', '从业资格证', '健康证']
        },
        {
          id: 'driver_002',
          name: '李师傅',
          phone: '13800138002',
          idCard: '110101198501011234',
          licenseNumber: 'A987654321',
          licenseType: 'A2',
          licenseExpiry: '2027-02-20',
          experience: '8年',
          rating: 4.9,
          totalTrips: 2100,
          totalDistance: 280000,
          status: 'active',
          vehicleId: 'vehicle_002',
          vehicleModel: '奔驰V级',
          licensePlate: '京B67890',
          emergencyContact: {
            name: '李太太',
            phone: '13900139002',
            relationship: '配偶'
          },
          address: '北京市海淀区某某街道456号',
          joinDate: '2018-06-20',
          lastLogin: '2024-01-15 09:15:00',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00',
          skills: ['安全驾驶', '客户服务', '路线熟悉', '商务接待'],
          certifications: ['驾驶证', '从业资格证', '健康证', '商务礼仪证']
        },
        {
          id: 'driver_003',
          name: '王师傅',
          phone: '13800138003',
          idCard: '110101198001011234',
          licenseNumber: 'A555666777',
          licenseType: 'A1',
          licenseExpiry: '2028-03-10',
          experience: '10年',
          rating: 5.0,
          totalTrips: 3200,
          totalDistance: 450000,
          status: 'active',
          vehicleId: 'vehicle_003',
          vehicleModel: '奔驰V级豪华版',
          licensePlate: '京C11111',
          emergencyContact: {
            name: '王太太',
            phone: '13900139003',
            relationship: '配偶'
          },
          address: '北京市西城区某某街道789号',
          joinDate: '2017-01-10',
          lastLogin: '2024-01-15 10:00:00',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00',
          skills: ['安全驾驶', '客户服务', '路线熟悉', '商务接待', 'VIP服务'],
          certifications: ['驾驶证', '从业资格证', '健康证', '商务礼仪证', 'VIP服务证']
        }
      ];
      this.saveDrivers(sampleDrivers);
    }
  }

  // 获取所有司机
  getAllDrivers() {
    try {
      return wx.getStorageSync('drivers') || [];
    } catch (error) {
      console.error('获取司机数据失败:', error);
      return [];
    }
  }

  // 保存司机数据
  saveDrivers(drivers) {
    try {
      wx.setStorageSync('drivers', drivers);
      this.notifyListeners(drivers);
      return true;
    } catch (error) {
      console.error('保存司机数据失败:', error);
      return false;
    }
  }

  // 根据ID获取司机
  getDriverById(driverId) {
    const drivers = this.getAllDrivers();
    return drivers.find(driver => driver.id === driverId);
  }

  // 根据电话获取司机
  getDriverByPhone(phone) {
    const drivers = this.getAllDrivers();
    return drivers.find(driver => driver.phone === phone);
  }

  // 根据车辆ID获取司机
  getDriverByVehicleId(vehicleId) {
    const drivers = this.getAllDrivers();
    return drivers.find(driver => driver.vehicleId === vehicleId);
  }

  // 创建司机
  createDriver(driverData) {
    const drivers = this.getAllDrivers();
    const newDriver = {
      ...driverData,
      id: this.generateDriverId(),
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      status: driverData.status || 'active',
      rating: driverData.rating || 5.0,
      totalTrips: driverData.totalTrips || 0,
      totalDistance: driverData.totalDistance || 0
    };
    
    drivers.push(newDriver);
    this.saveDrivers(drivers);
    return newDriver;
  }

  // 更新司机
  updateDriver(driverId, updateData) {
    const drivers = this.getAllDrivers();
    const driverIndex = drivers.findIndex(driver => driver.id === driverId);
    
    if (driverIndex === -1) {
      throw new Error('司机不存在');
    }

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

    this.saveDrivers(drivers);
    return drivers[driverIndex];
  }

  // 删除司机
  deleteDriver(driverId) {
    const drivers = this.getAllDrivers();
    const filteredDrivers = drivers.filter(driver => driver.id !== driverId);
    
    if (filteredDrivers.length === drivers.length) {
      throw new Error('司机不存在');
    }

    this.saveDrivers(filteredDrivers);
    return true;
  }

  // 分配司机到车辆
  assignDriverToVehicle(driverId, vehicleId) {
    const drivers = this.getAllDrivers();
    const driverIndex = drivers.findIndex(driver => driver.id === driverId);
    
    if (driverIndex === -1) {
      throw new Error('司机不存在');
    }

    drivers[driverIndex].vehicleId = vehicleId;
    drivers[driverIndex].updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19);

    this.saveDrivers(drivers);
    return drivers[driverIndex];
  }

  // 更新司机状态
  updateDriverStatus(driverId, status) {
    const drivers = this.getAllDrivers();
    const driverIndex = drivers.findIndex(driver => driver.id === driverId);
    
    if (driverIndex === -1) {
      throw new Error('司机不存在');
    }

    drivers[driverIndex].status = status;
    drivers[driverIndex].updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19);

    this.saveDrivers(drivers);
    return drivers[driverIndex];
  }

  // 更新司机评分
  updateDriverRating(driverId, newRating) {
    const drivers = this.getAllDrivers();
    const driverIndex = drivers.findIndex(driver => driver.id === driverId);
    
    if (driverIndex === -1) {
      throw new Error('司机不存在');
    }

    // 计算新的平均评分
    const currentRating = drivers[driverIndex].rating;
    const totalTrips = drivers[driverIndex].totalTrips;
    const newAverageRating = ((currentRating * totalTrips) + newRating) / (totalTrips + 1);
    
    drivers[driverIndex].rating = Math.round(newAverageRating * 10) / 10;
    drivers[driverIndex].totalTrips += 1;
    drivers[driverIndex].updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19);

    this.saveDrivers(drivers);
    return drivers[driverIndex];
  }

  // 搜索司机
  searchDrivers(searchParams) {
    const drivers = this.getAllDrivers();
    let filteredDrivers = [...drivers];

    // 按姓名搜索
    if (searchParams.name) {
      filteredDrivers = filteredDrivers.filter(driver => 
        driver.name.toLowerCase().includes(searchParams.name.toLowerCase())
      );
    }

    // 按电话搜索
    if (searchParams.phone) {
      filteredDrivers = filteredDrivers.filter(driver => 
        driver.phone.includes(searchParams.phone)
      );
    }

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

    // 按驾驶证类型搜索
    if (searchParams.licenseType) {
      filteredDrivers = filteredDrivers.filter(driver => 
        driver.licenseType === searchParams.licenseType
      );
    }

    // 按车辆ID搜索
    if (searchParams.vehicleId) {
      filteredDrivers = filteredDrivers.filter(driver => 
        driver.vehicleId === searchParams.vehicleId
      );
    }

    // 按评分范围搜索
    if (searchParams.minRating) {
      filteredDrivers = filteredDrivers.filter(driver => 
        driver.rating >= searchParams.minRating
      );
    }

    if (searchParams.maxRating) {
      filteredDrivers = filteredDrivers.filter(driver => 
        driver.rating <= searchParams.maxRating
      );
    }

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

    return {
      drivers: filteredDrivers,
      total: filteredDrivers.length,
      page: searchParams.page || 1,
      pageSize: searchParams.pageSize || 20
    };
  }

  // 获取司机统计信息
  getDriverStatistics() {
    const drivers = this.getAllDrivers();
    
    const stats = {
      total: drivers.length,
      byStatus: {},
      byLicenseType: {},
      byRating: {},
      totalTrips: 0,
      totalDistance: 0,
      averageRating: 0
    };

    let totalRating = 0;
    let ratedDrivers = 0;

    drivers.forEach(driver => {
      // 按状态统计
      stats.byStatus[driver.status] = (stats.byStatus[driver.status] || 0) + 1;
      
      // 按驾驶证类型统计
      stats.byLicenseType[driver.licenseType] = (stats.byLicenseType[driver.licenseType] || 0) + 1;
      
      // 按评分统计
      const ratingRange = Math.floor(driver.rating);
      stats.byRating[ratingRange] = (stats.byRating[ratingRange] || 0) + 1;
      
      // 累计数据
      stats.totalTrips += driver.totalTrips;
      stats.totalDistance += driver.totalDistance;
      
      if (driver.rating > 0) {
        totalRating += driver.rating;
        ratedDrivers++;
      }
    });

    // 计算平均评分
    if (ratedDrivers > 0) {
      stats.averageRating = Math.round((totalRating / ratedDrivers) * 10) / 10;
    }

    return stats;
  }

  // 批量更新司机状态
  batchUpdateDriverStatus(driverIds, status) {
    const drivers = this.getAllDrivers();
    const updatedDrivers = drivers.map(driver => {
      if (driverIds.includes(driver.id)) {
        return {
          ...driver,
          status,
          updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
        };
      }
      return driver;
    });

    this.saveDrivers(updatedDrivers);
    return true;
  }

  // 获取可用司机（用于订单分配）
  getAvailableDrivers(vehicleType = null, minRating = 0) {
    const drivers = this.getAllDrivers();
    
    return drivers.filter(driver => {
      // 状态检查
      if (driver.status !== 'active') return false;
      
      // 评分检查
      if (driver.rating < minRating) return false;
      
      // 车辆类型检查
      if (vehicleType) {
        // 这里可以根据车辆类型匹配司机
        // 例如：A1驾照可以开大巴，A2驾照可以开商务车等
        const licenseTypeMap = {
          'bus': ['A1'],
          'business': ['A1', 'A2'],
          'charter': ['A1', 'A2']
        };
        
        if (licenseTypeMap[vehicleType] && !licenseTypeMap[vehicleType].includes(driver.licenseType)) {
          return false;
        }
      }
      
      return true;
    });
  }

  // 导出司机数据
  exportDrivers(searchParams = {}) {
    const result = this.searchDrivers(searchParams);
    return {
      drivers: result.drivers,
      exportTime: new Date().toISOString(),
      total: result.total,
      searchParams
    };
  }

  // 生成司机ID
  generateDriverId() {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `driver_${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(drivers) {
    this.listeners.forEach(callback => {
      try {
        callback(drivers);
      } catch (error) {
        console.error('司机数据监听器回调执行失败:', error);
      }
    });
  }

  // 同步司机数据
  syncDriverData() {
    const drivers = this.getAllDrivers();
    this.notifyListeners(drivers);
    return drivers;
  }
}

// 创建单例实例
const driverManagementApiService = new DriverManagementApiService();

export default driverManagementApiService;

