/**
 * 司机端API接口模拟系统
 * 模拟后台司机管理、订单状态更新和位置共享功能
 */

class DriverApiService {
  constructor() {
    this.listeners = []; // 订单状态变化监听器
    this.locationListeners = []; // 位置更新监听器
    this.initDriverData();
    
    // 模拟司机位置更新
    this.startLocationSimulation();
  }

  // 初始化司机数据
  initDriverData() {
    const drivers = this.getAllDrivers();
    if (drivers.length === 0) {
      // 初始化示例司机数据
      const sampleDrivers = [
        {
          id: 'driver_001',
          name: '张师傅',
          phone: '13800138001',
          carNumber: '京A12345',
          carModel: '宇通大巴',
          avatar: '/images/avatar-default.png',
          rating: 4.8,
          completedOrders: 1250,
          status: 'available', // available, busy, offline
          currentLocation: {
            lng: 116.404,
            lat: 39.915,
            address: '北京市东城区东直门',
            updateTime: new Date().toISOString()
          },
          certification: {
            driverLicense: '11010119800101****',
            vehicleLicense: '京A12345',
            verified: true
          }
        },
        {
          id: 'driver_002', 
          name: '李师傅',
          phone: '13800138002',
          carNumber: '京B67890',
          carModel: '奔驰V级商务车',
          avatar: '/images/avatar-default.png',
          rating: 4.9,
          completedOrders: 890,
          status: 'available',
          currentLocation: {
            lng: 121.473,
            lat: 31.230,
            address: '上海市黄浦区人民广场',
            updateTime: new Date().toISOString()
          },
          certification: {
            driverLicense: '31010219850301****',
            vehicleLicense: '京B67890',
            verified: true
          }
        }
      ];
      this.saveDrivers(sampleDrivers);
    }
  }

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

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

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

  // 为订单分配司机（模拟后台API）
  async assignDriverToOrder(orderId, orderType = 'bus') {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        try {
          const drivers = this.getAllDrivers();
          const availableDrivers = drivers.filter(driver => 
            driver.status === 'available' && 
            this.isDriverSuitableForOrder(driver, orderType)
          );

          if (availableDrivers.length === 0) {
            reject(new Error('暂无可用司机'));
            return;
          }

          // 随机选择一个可用司机
          const selectedDriver = availableDrivers[Math.floor(Math.random() * availableDrivers.length)];
          
          // 更新司机状态为忙碌
          const updatedDrivers = drivers.map(driver => 
            driver.id === selectedDriver.id 
              ? { ...driver, status: 'busy', currentOrderId: orderId }
              : driver
          );
          this.saveDrivers(updatedDrivers);

          // 创建司机订单关联
          this.createDriverOrderRelation(selectedDriver.id, orderId);

          resolve({
            success: true,
            data: {
              driverId: selectedDriver.id,
              driverName: selectedDriver.name,
              driverPhone: selectedDriver.phone,
              carNumber: selectedDriver.carNumber,
              carModel: selectedDriver.carModel,
              rating: selectedDriver.rating,
              estimatedArrival: this.calculateEstimatedArrival(),
              assignTime: new Date().toISOString()
            }
          });
        } catch (error) {
          reject(error);
        }
      }, 2000); // 模拟API延迟
    });
  }

  // 判断司机是否适合订单类型
  isDriverSuitableForOrder(driver, orderType) {
    if (orderType === 'business-charter') {
      return driver.carModel.includes('商务车') || driver.carModel.includes('奔驰') || driver.carModel.includes('宝马');
    }
    return true; // 大巴司机可以接所有订单
  }

  // 计算预计到达时间
  calculateEstimatedArrival() {
    const now = new Date();
    const estimatedMinutes = Math.floor(Math.random() * 20) + 10; // 10-30分钟
    const estimatedTime = new Date(now.getTime() + estimatedMinutes * 60000);
    return {
      minutes: estimatedMinutes,
      time: estimatedTime.toISOString(),
      display: `约${estimatedMinutes}分钟后到达`
    };
  }

  // 创建司机订单关联
  createDriverOrderRelation(driverId, orderId) {
    try {
      const relations = wx.getStorageSync('driver_order_relations') || [];
      const newRelation = {
        id: `relation_${Date.now()}`,
        driverId,
        orderId,
        createTime: new Date().toISOString(),
        status: 'assigned', // assigned, picked_up, in_transit, completed
        events: [
          {
            type: 'assigned',
            time: new Date().toISOString(),
            description: '司机已分配'
          }
        ]
      };
      relations.push(newRelation);
      wx.setStorageSync('driver_order_relations', relations);
      return newRelation;
    } catch (error) {
      console.error('创建司机订单关联失败:', error);
      return null;
    }
  }

  // 获取订单的司机信息
  getOrderDriverInfo(orderId) {
    try {
      const relations = wx.getStorageSync('driver_order_relations') || [];
      const relation = relations.find(r => r.orderId === orderId);
      
      if (!relation) {
        return null;
      }

      const driver = this.getDriverById(relation.driverId);
      if (!driver) {
        return null;
      }

      return {
        relation,
        driver,
        status: relation.status,
        events: relation.events,
        currentLocation: driver.currentLocation
      };
    } catch (error) {
      console.error('获取订单司机信息失败:', error);
      return null;
    }
  }

  // 司机确认乘客上车（模拟司机端操作）
  async confirmPickup(orderId, driverId) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        try {
          const relations = wx.getStorageSync('driver_order_relations') || [];
          const relationIndex = relations.findIndex(r => r.orderId === orderId && r.driverId === driverId);
          
          if (relationIndex === -1) {
            reject(new Error('订单司机关联不存在'));
            return;
          }

          // 更新关联状态
          relations[relationIndex].status = 'picked_up';
          relations[relationIndex].events.push({
            type: 'picked_up',
            time: new Date().toISOString(),
            description: '乘客已上车',
            location: this.getDriverById(driverId)?.currentLocation
          });

          wx.setStorageSync('driver_order_relations', relations);

          // 通知监听器
          this.notifyOrderStatusChange(orderId, 'picked_up', '乘客已上车');

          resolve({
            success: true,
            message: '确认上车成功',
            status: 'picked_up',
            time: new Date().toISOString()
          });
        } catch (error) {
          reject(error);
        }
      }, 1000);
    });
  }

  // 司机开始行程（模拟司机端操作）
  async startTrip(orderId, driverId) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        try {
          const relations = wx.getStorageSync('driver_order_relations') || [];
          const relationIndex = relations.findIndex(r => r.orderId === orderId && r.driverId === driverId);
          
          if (relationIndex === -1) {
            reject(new Error('订单司机关联不存在'));
            return;
          }

          relations[relationIndex].status = 'in_transit';
          relations[relationIndex].events.push({
            type: 'in_transit',
            time: new Date().toISOString(),
            description: '行程已开始',
            location: this.getDriverById(driverId)?.currentLocation
          });

          wx.setStorageSync('driver_order_relations', relations);

          this.notifyOrderStatusChange(orderId, 'in_transit', '行程中');

          resolve({
            success: true,
            message: '行程开始',
            status: 'in_transit',
            time: new Date().toISOString()
          });
        } catch (error) {
          reject(error);
        }
      }, 1000);
    });
  }

  // 司机确认到达（模拟司机端操作）
  async confirmArrival(orderId, driverId) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        try {
          const relations = wx.getStorageSync('driver_order_relations') || [];
          const relationIndex = relations.findIndex(r => r.orderId === orderId && r.driverId === driverId);
          
          if (relationIndex === -1) {
            reject(new Error('订单司机关联不存在'));
            return;
          }

          relations[relationIndex].status = 'completed';
          relations[relationIndex].events.push({
            type: 'completed',
            time: new Date().toISOString(),
            description: '已到达目的地',
            location: this.getDriverById(driverId)?.currentLocation
          });

          wx.setStorageSync('driver_order_relations', relations);

          // 释放司机
          const drivers = this.getAllDrivers();
          const updatedDrivers = drivers.map(driver => 
            driver.id === driverId 
              ? { ...driver, status: 'available', currentOrderId: null }
              : driver
          );
          this.saveDrivers(updatedDrivers);

          this.notifyOrderStatusChange(orderId, 'completed', '已完成');

          resolve({
            success: true,
            message: '行程完成',
            status: 'completed',
            time: new Date().toISOString()
          });
        } catch (error) {
          reject(error);
        }
      }, 1000);
    });
  }

  // 更新司机位置（模拟司机端定位）
  updateDriverLocation(driverId, location) {
    try {
      const drivers = this.getAllDrivers();
      const updatedDrivers = drivers.map(driver => 
        driver.id === driverId 
          ? { 
              ...driver, 
              currentLocation: {
                ...location,
                updateTime: new Date().toISOString()
              }
            }
          : driver
      );
      
      this.saveDrivers(updatedDrivers);
      this.notifyLocationUpdate(driverId, location);
      
      return true;
    } catch (error) {
      console.error('更新司机位置失败:', error);
      return false;
    }
  }

  // 获取司机实时位置
  getDriverLocation(driverId) {
    const driver = this.getDriverById(driverId);
    return driver ? driver.currentLocation : null;
  }

  // 模拟司机位置移动
  startLocationSimulation() {
    // 清除之前的定时器
    if (this.locationTimer) {
      clearInterval(this.locationTimer);
    }
    
    this.locationTimer = setInterval(() => {
      const drivers = this.getAllDrivers();
      const busyDrivers = drivers.filter(driver => driver.status === 'busy');
      
      busyDrivers.forEach(driver => {
        // 模拟位置变化
        const currentLoc = driver.currentLocation;
        const newLocation = {
          lng: currentLoc.lng + (Math.random() - 0.5) * 0.01, // 随机移动
          lat: currentLoc.lat + (Math.random() - 0.5) * 0.01,
          address: this.generateRandomAddress(),
          updateTime: new Date().toISOString()
        };
        
        this.updateDriverLocation(driver.id, newLocation);
      });
    }, 10000); // 每10秒更新一次位置
  }
  
  // 停止位置模拟
  stopLocationSimulation() {
    if (this.locationTimer) {
      clearInterval(this.locationTimer);
      this.locationTimer = null;
    }
  }

  // 生成随机地址（模拟）
  generateRandomAddress() {
    const addresses = [
      '北京市朝阳区建国门外大街',
      '北京市海淀区中关村大街', 
      '北京市东城区王府井大街',
      '北京市西城区金融街',
      '上海市黄浦区南京东路',
      '上海市浦东新区陆家嘴'
    ];
    return addresses[Math.floor(Math.random() * addresses.length)];
  }

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

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

  notifyOrderStatusChange(orderId, status, statusText) {
    this.listeners.forEach(callback => {
      try {
        callback({ orderId, status, statusText, time: new Date().toISOString() });
      } catch (error) {
        console.error('订单状态监听器回调执行失败:', error);
      }
    });
  }

  addLocationListener(callback) {
    this.locationListeners.push(callback);
  }

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

  notifyLocationUpdate(driverId, location) {
    this.locationListeners.forEach(callback => {
      try {
        callback({ driverId, location, time: new Date().toISOString() });
      } catch (error) {
        console.error('位置监听器回调执行失败:', error);
      }
    });
  }

  // 模拟司机端操作API（供测试使用）
  async simulateDriverActions(orderId, driverId) {
    try {
      console.log('开始模拟司机操作流程...');
      
      // 5秒后确认上车
      setTimeout(async () => {
        await this.confirmPickup(orderId, driverId);
        console.log('司机已确认乘客上车');
      }, 5000);

      // 10秒后开始行程
      setTimeout(async () => {
        await this.startTrip(orderId, driverId);
        console.log('司机已开始行程');
      }, 10000);

      // 60秒后确认到达（模拟1分钟行程）
      setTimeout(async () => {
        await this.confirmArrival(orderId, driverId);
        console.log('司机已确认到达');
      }, 60000);

    } catch (error) {
      console.error('模拟司机操作失败:', error);
    }
  }
}

// 创建单例实例
const driverApiService = new DriverApiService();

export default driverApiService;
