/**
 * 路线和班次管理API接口系统
 * 支持路线、班次的增删改查、票价管理、班次发布
 */

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

  // 初始化路线数据
  initRouteData() {
    const routes = this.getAllRoutes();
    if (routes.length === 0) {
      const sampleRoutes = [
        {
          id: 'route_001',
          activityId: 'activity_001',
          activityName: '北京春季音乐节',
          fromCity: '北京',
          toCity: '北京',
          fromLocation: '北京东直门地铁站A口',
          toLocation: '北京国家体育场（鸟巢）',
          distance: '15公里',
          duration: '约1小时',
          type: 'bus', // bus, business, charter
          status: 'active', // active, inactive, draft
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00',
          schedules: [
            {
              id: 'schedule_001',
              departureTime: '08:00',
              arrivalTime: '09:00',
              totalTickets: 50,
              soldTickets: 12,
              remainingTickets: 38,
              price: 15,
              vehicleModel: '宇通大巴',
              driver: {
                id: 'driver_001',
                name: '张师傅',
                phone: '13800138001'
              },
              status: 'active',
              createTime: '2024-01-15 10:00:00'
            },
            {
              id: 'schedule_002',
              departureTime: '09:30',
              arrivalTime: '10:30',
              totalTickets: 50,
              soldTickets: 8,
              remainingTickets: 42,
              price: 15,
              vehicleModel: '宇通大巴',
              driver: {
                id: 'driver_002',
                name: '李师傅',
                phone: '13800138002'
              },
              status: 'active',
              createTime: '2024-01-15 10:00:00'
            }
          ]
        },
        {
          id: 'route_002',
          activityId: 'activity_001',
          activityName: '北京春季音乐节',
          fromCity: '北京',
          toCity: '北京',
          fromLocation: '北京朝阳区',
          toLocation: '北京国家体育场（鸟巢）',
          distance: '20公里',
          duration: '约1.5小时',
          type: 'business',
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00',
          schedules: [
            {
              id: 'schedule_003',
              departureTime: '08:00',
              arrivalTime: '09:30',
              totalTickets: 20,
              soldTickets: 5,
              remainingTickets: 15,
              price: 35,
              vehicleModel: '奔驰V级商务车',
              driver: {
                id: 'driver_003',
                name: '王师傅',
                phone: '13800138003'
              },
              status: 'active',
              createTime: '2024-01-15 10:00:00'
            }
          ]
        },
        {
          id: 'route_003',
          activityId: 'activity_001',
          activityName: '北京春季音乐节',
          fromCity: '北京',
          toCity: '北京',
          fromLocation: '指定地点接送',
          toLocation: '北京国家体育场（鸟巢）',
          distance: '25公里',
          duration: '约2小时',
          type: 'charter',
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00',
          schedules: [
            {
              id: 'schedule_004',
              departureTime: '任意时间',
              arrivalTime: '根据需求',
              totalTickets: 6,
              soldTickets: 1,
              remainingTickets: 5,
              price: 800,
              vehicleModel: '奔驰V级商务车',
              driver: {
                id: 'driver_004',
                name: '赵师傅',
                phone: '13800138004'
              },
              status: 'active',
              createTime: '2024-01-15 10:00:00'
            }
          ]
        }
      ];
      this.saveRoutes(sampleRoutes);
    }
  }

  // 获取所有路线
  getAllRoutes() {
    try {
      return wx.getStorageSync('routes') || [];
    } catch (error) {
      console.error('获取路线数据失败:', error);
      return [];
    }
  }

  // 保存路线数据
  saveRoutes(routes) {
    try {
      wx.setStorageSync('routes', routes);
      this.notifyListeners(routes);
      return true;
    } catch (error) {
      console.error('保存路线数据失败:', error);
      return false;
    }
  }

  // 根据ID获取路线
  getRouteById(routeId) {
    const routes = this.getAllRoutes();
    return routes.find(route => route.id === routeId);
  }

  // 根据活动ID获取路线
  getRoutesByActivityId(activityId) {
    const routes = this.getAllRoutes();
    return routes.filter(route => route.activityId === activityId);
  }

  // 创建路线
  createRoute(routeData) {
    const routes = this.getAllRoutes();
    const newRoute = {
      ...routeData,
      id: this.generateRouteId(),
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      status: routeData.status || 'active',
      schedules: routeData.schedules || []
    };
    
    routes.push(newRoute);
    this.saveRoutes(routes);
    return newRoute;
  }

  // 更新路线
  updateRoute(routeId, updateData) {
    const routes = this.getAllRoutes();
    const routeIndex = routes.findIndex(route => route.id === routeId);
    
    if (routeIndex === -1) {
      throw new Error('路线不存在');
    }

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

    this.saveRoutes(routes);
    return routes[routeIndex];
  }

  // 删除路线
  deleteRoute(routeId) {
    const routes = this.getAllRoutes();
    const filteredRoutes = routes.filter(route => route.id !== routeId);
    
    if (filteredRoutes.length === routes.length) {
      throw new Error('路线不存在');
    }

    this.saveRoutes(filteredRoutes);
    return true;
  }

  // 添加班次
  addSchedule(routeId, scheduleData) {
    const routes = this.getAllRoutes();
    const routeIndex = routes.findIndex(route => route.id === routeId);
    
    if (routeIndex === -1) {
      throw new Error('路线不存在');
    }

    const newSchedule = {
      ...scheduleData,
      id: this.generateScheduleId(),
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      status: scheduleData.status || 'active'
    };

    routes[routeIndex].schedules.push(newSchedule);
    routes[routeIndex].updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19);
    
    this.saveRoutes(routes);
    return newSchedule;
  }

  // 更新班次
  updateSchedule(routeId, scheduleId, updateData) {
    const routes = this.getAllRoutes();
    const routeIndex = routes.findIndex(route => route.id === routeId);
    
    if (routeIndex === -1) {
      throw new Error('路线不存在');
    }

    const scheduleIndex = routes[routeIndex].schedules.findIndex(schedule => schedule.id === scheduleId);
    if (scheduleIndex === -1) {
      throw new Error('班次不存在');
    }

    routes[routeIndex].schedules[scheduleIndex] = {
      ...routes[routeIndex].schedules[scheduleIndex],
      ...updateData
    };
    routes[routeIndex].updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19);
    
    this.saveRoutes(routes);
    return routes[routeIndex].schedules[scheduleIndex];
  }

  // 删除班次
  deleteSchedule(routeId, scheduleId) {
    const routes = this.getAllRoutes();
    const routeIndex = routes.findIndex(route => route.id === routeId);
    
    if (routeIndex === -1) {
      throw new Error('路线不存在');
    }

    const scheduleIndex = routes[routeIndex].schedules.findIndex(schedule => schedule.id === scheduleId);
    if (scheduleIndex === -1) {
      throw new Error('班次不存在');
    }

    routes[routeIndex].schedules.splice(scheduleIndex, 1);
    routes[routeIndex].updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19);
    
    this.saveRoutes(routes);
    return true;
  }

  // 搜索路线
  searchRoutes(searchParams) {
    const routes = this.getAllRoutes();
    let filteredRoutes = [...routes];

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

    // 按路线类型搜索
    if (searchParams.type) {
      filteredRoutes = filteredRoutes.filter(route => 
        route.type === searchParams.type
      );
    }

    // 按出发城市搜索
    if (searchParams.fromCity) {
      filteredRoutes = filteredRoutes.filter(route => 
        route.fromCity.includes(searchParams.fromCity)
      );
    }

    // 按到达城市搜索
    if (searchParams.toCity) {
      filteredRoutes = filteredRoutes.filter(route => 
        route.toCity.includes(searchParams.toCity)
      );
    }

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

    // 排序
    const sortBy = searchParams.sortBy || 'createTime';
    const sortOrder = searchParams.sortOrder || 'desc';
    
    filteredRoutes.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 {
      routes: filteredRoutes,
      total: filteredRoutes.length,
      page: searchParams.page || 1,
      pageSize: searchParams.pageSize || 20
    };
  }

  // 获取路线统计信息
  getRouteStatistics() {
    const routes = this.getAllRoutes();
    
    const stats = {
      total: routes.length,
      byType: {},
      byStatus: {},
      byActivity: {},
      totalSchedules: 0,
      totalTickets: 0,
      soldTickets: 0
    };

    routes.forEach(route => {
      // 按类型统计
      stats.byType[route.type] = (stats.byType[route.type] || 0) + 1;
      
      // 按状态统计
      stats.byStatus[route.status] = (stats.byStatus[route.status] || 0) + 1;
      
      // 按活动统计
      stats.byActivity[route.activityId] = (stats.byActivity[route.activityId] || 0) + 1;
      
      // 班次统计
      stats.totalSchedules += route.schedules.length;
      
      route.schedules.forEach(schedule => {
        stats.totalTickets += schedule.totalTickets;
        stats.soldTickets += schedule.soldTickets;
      });
    });

    return stats;
  }

  // 批量更新路线状态
  batchUpdateRouteStatus(routeIds, status) {
    const routes = this.getAllRoutes();
    const updatedRoutes = routes.map(route => {
      if (routeIds.includes(route.id)) {
        return {
          ...route,
          status,
          updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
        };
      }
      return route;
    });

    this.saveRoutes(updatedRoutes);
    return true;
  }

  // 导出路线数据
  exportRoutes(searchParams = {}) {
    const result = this.searchRoutes(searchParams);
    return {
      routes: result.routes,
      exportTime: new Date().toISOString(),
      total: result.total,
      searchParams
    };
  }

  // 生成路线ID
  generateRouteId() {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `route_${timestamp}_${random}`;
  }

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

  // 同步路线数据
  syncRouteData() {
    const routes = this.getAllRoutes();
    this.notifyListeners(routes);
    return routes;
  }
}

// 创建单例实例
const routeApiService = new RouteApiService();

export default routeApiService;

