/**
 * 订单管理API接口系统
 * 为后台管理系统提供订单查询、管理功能
 * 确保数据一致性和完整性
 */

class OrderApiService {
  constructor() {
    this.listeners = []; // 订单数据变化监听器
    this.initOrderData();
  }

  // 初始化订单数据
  initOrderData() {
    const orders = this.getAllOrders();
    if (orders.length === 0) {
      // 初始化示例订单数据
      const sampleOrders = [
        {
          id: 'ORDER_1705123456789_001',
          orderNo: 'ORD20240115001',
          status: '待出发',
          statusCode: 1,
          activity: '北京到上海商务出行',
          schedule: {
            date: '2024-03-15',
            time: '09:00',
            fromLoc: '北京东直门地铁站A口',
            toLoc: '上海体育馆',
            model: '宇通大巴',
            type: 'bus',
            price: 88,
            duration: '约5小时',
            left: 12
          },
          passengers: [
            {
              name: '张三',
              idtype: '身份证',
              idcard: '110101199001011234',
              phone: '13800138001'
            }
          ],
          totalPrice: 88,
          createTime: '2024-01-15 10:30:00',
          updateTime: '2024-01-15 10:30:00',
          paymentTime: '2024-01-15 10:32:00',
          driver: {
            id: 'driver_001',
            name: '张师傅',
            phone: '13800138001',
            carNumber: '京A12345',
            carModel: '宇通大巴',
            location: {
              lng: 116.404,
              lat: 39.915,
              address: '北京市东城区东直门'
            }
          },
          contactInfo: {
            phone: '138****8001',
            email: 'user@example.com'
          },
          notes: '请准时到达上车点',
          tags: ['商务出行', '热门路线']
        },
        {
          id: 'ORDER_1705123456790_002',
          orderNo: 'ORD20240115002',
          status: '行程中',
          statusCode: 2,
          activity: '北京到天津短途游',
          schedule: {
            date: '2024-01-16',
            time: '14:00',
            fromLoc: '北京朝阳区',
            toLoc: '天津滨海新区',
            model: '奔驰V级商务车',
            type: 'business-charter',
            price: 1200,
            duration: '约1.5小时',
            left: 6
          },
          passengers: [
            {
              name: '李四',
              idtype: '身份证',
              idcard: '110101199002021234',
              phone: '13800138002'
            },
            {
              name: '王五',
              idtype: '身份证',
              idcard: '110101199003031234',
              phone: '13800138003'
            }
          ],
          totalPrice: 1200,
          createTime: '2024-01-15 14:20:00',
          updateTime: '2024-01-16 14:05:00',
          paymentTime: '2024-01-15 14:25:00',
          driver: {
            id: 'driver_002',
            name: '李师傅',
            phone: '13800138002',
            carNumber: '京B67890',
            carModel: '奔驰V级商务车',
            location: {
              lng: 121.473,
              lat: 31.230,
              address: '天津市滨海新区'
            }
          },
          contactInfo: {
            phone: '138****8002',
            email: 'user2@example.com'
          },
          notes: '包车服务，已确认上车',
          tags: ['包车', '商务']
        }
      ];
      this.saveOrders(sampleOrders);
    }
  }

  // 获取所有订单
  getAllOrders() {
    try {
      return wx.getStorageSync('orders') || [];
    } catch (error) {
      console.error('获取订单数据失败:', error);
      return [];
    }
  }

  // 保存订单数据
  saveOrders(orders) {
    try {
      wx.setStorageSync('orders', orders);
      this.notifyListeners(orders);
      return true;
    } catch (error) {
      console.error('保存订单数据失败:', error);
      return false;
    }
  }

  // 根据ID获取订单
  getOrderById(orderId) {
    const orders = this.getAllOrders();
    return orders.find(order => order.id === orderId);
  }

  // 根据订单号获取订单
  getOrderByOrderNo(orderNo) {
    const orders = this.getAllOrders();
    return orders.find(order => order.orderNo === orderNo);
  }

  // 创建新订单
  createOrder(orderData) {
    const orders = this.getAllOrders();
    const newOrder = {
      ...orderData,
      id: this.generateOrderId(),
      orderNo: this.generateOrderNo(),
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      status: '待出发',
      statusCode: 1
    };
    
    orders.push(newOrder);
    this.saveOrders(orders);
    return newOrder;
  }

  // 更新订单
  updateOrder(orderId, updateData) {
    const orders = this.getAllOrders();
    const orderIndex = orders.findIndex(order => order.id === orderId);
    
    if (orderIndex === -1) {
      throw new Error('订单不存在');
    }

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

    this.saveOrders(orders);
    return orders[orderIndex];
  }

  // 删除订单
  deleteOrder(orderId) {
    const orders = this.getAllOrders();
    const filteredOrders = orders.filter(order => order.id !== orderId);
    
    if (filteredOrders.length === orders.length) {
      throw new Error('订单不存在');
    }

    this.saveOrders(filteredOrders);
    return true;
  }

  // 订单查询功能
  searchOrders(searchParams) {
    const orders = this.getAllOrders();
    let filteredOrders = [...orders];

    // 按订单号查询
    if (searchParams.orderNo) {
      filteredOrders = filteredOrders.filter(order => 
        order.orderNo.toLowerCase().includes(searchParams.orderNo.toLowerCase())
      );
    }

    // 按日期查询
    if (searchParams.date) {
      filteredOrders = filteredOrders.filter(order => 
        order.schedule.date === searchParams.date
      );
    }

    // 按到达城市查询
    if (searchParams.toCity) {
      filteredOrders = filteredOrders.filter(order => 
        order.schedule.toLoc.includes(searchParams.toCity)
      );
    }

    // 按手机号查询
    if (searchParams.phone) {
      filteredOrders = filteredOrders.filter(order => 
        order.passengers.some(passenger => 
          passenger.phone.includes(searchParams.phone)
        ) || 
        order.contactInfo.phone.includes(searchParams.phone)
      );
    }

    // 按状态查询
    if (searchParams.status) {
      filteredOrders = filteredOrders.filter(order => 
        order.status === searchParams.status
      );
    }

    // 按创建时间范围查询
    if (searchParams.startDate && searchParams.endDate) {
      filteredOrders = filteredOrders.filter(order => {
        const orderDate = new Date(order.createTime);
        const startDate = new Date(searchParams.startDate);
        const endDate = new Date(searchParams.endDate);
        return orderDate >= startDate && orderDate <= endDate;
      });
    }

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

  // 获取订单统计信息
  getOrderStatistics() {
    const orders = this.getAllOrders();
    
    const stats = {
      total: orders.length,
      byStatus: {},
      byDate: {},
      revenue: 0,
      averageOrderValue: 0
    };

    orders.forEach(order => {
      // 按状态统计
      stats.byStatus[order.status] = (stats.byStatus[order.status] || 0) + 1;
      
      // 按日期统计
      const date = order.schedule.date;
      stats.byDate[date] = (stats.byDate[date] || 0) + 1;
      
      // 收入统计
      if (order.status !== '已取消') {
        stats.revenue += order.totalPrice;
      }
    });

    // 计算平均订单价值
    const paidOrders = orders.filter(order => order.status !== '已取消');
    stats.averageOrderValue = paidOrders.length > 0 ? 
      (stats.revenue / paidOrders.length).toFixed(2) : 0;

    return stats;
  }

  // 批量更新订单状态
  batchUpdateOrderStatus(orderIds, status, statusCode) {
    const orders = this.getAllOrders();
    const updatedOrders = orders.map(order => {
      if (orderIds.includes(order.id)) {
        return {
          ...order,
          status,
          statusCode,
          updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
        };
      }
      return order;
    });

    this.saveOrders(updatedOrders);
    return true;
  }

  // 导出订单数据
  exportOrders(searchParams = {}) {
    const result = this.searchOrders(searchParams);
    return {
      orders: result.orders,
      exportTime: new Date().toISOString(),
      total: result.total,
      searchParams
    };
  }

  // 生成订单ID
  generateOrderId() {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `ORDER_${timestamp}_${random}`;
  }

  // 生成订单号
  generateOrderNo() {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `ORD${year}${month}${day}${random}`;
  }

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

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

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

  // 同步订单数据（确保一致性）
  syncOrderData() {
    const orders = this.getAllOrders();
    this.notifyListeners(orders);
    return orders;
  }

  // 获取订单详情（包含完整信息）
  getOrderDetails(orderId) {
    const order = this.getOrderById(orderId);
    if (!order) {
      return null;
    }

    // 添加额外的详情信息
    return {
      ...order,
      timeline: this.getOrderTimeline(orderId),
      driverInfo: this.getDriverInfo(order.driver?.id),
      passengerCount: order.passengers.length,
      isCharter: order.schedule.type === 'business-charter'
    };
  }

  // 获取订单时间线
  getOrderTimeline(orderId) {
    const order = this.getOrderById(orderId);
    if (!order) return [];

    const timeline = [
      {
        time: order.createTime,
        event: '订单创建',
        description: '用户提交订单'
      },
      {
        time: order.paymentTime,
        event: '支付完成',
        description: '订单支付成功'
      }
    ];

    if (order.driver) {
      timeline.push({
        time: order.updateTime,
        event: '司机分配',
        description: `司机：${order.driver.name}`
      });
    }

    if (order.statusCode >= 2) {
      timeline.push({
        time: order.updateTime,
        event: '行程开始',
        description: '乘客已上车'
      });
    }

    if (order.statusCode >= 3) {
      timeline.push({
        time: order.updateTime,
        event: '行程完成',
        description: '已到达目的地'
      });
    }

    return timeline;
  }

  // 获取司机信息
  getDriverInfo(driverId) {
    if (!driverId) return null;
    
    // 这里可以集成司机API服务
    try {
      const driverApiService = require('./driver-api.js').default;
      return driverApiService.getDriverById(driverId);
    } catch (error) {
      console.error('获取司机信息失败:', error);
      return null;
    }
  }
}

// 创建单例实例
const orderApiService = new OrderApiService();

export default orderApiService;

