import driverApiService from '../../utils/driver-api.js';
import vehicleApiService from '../../utils/vehicle-api.js';
import driverManagementApiService from '../../utils/driver-management-api.js';
import orderApiService from '../../utils/order-api.js';

Page({
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      });
    }
  },

  data:{
    orders:[],
    statusTabs: ['待出发', '行程中', '已完成', '已取消'],
    currentTab: 0,
    driverInfoMap: {}, // 存储订单对应的司机信息
    locationUpdateListener: null,
    orderStatusListener: null,
    orderDataListener: null
  },
  
  onLoad() {
    // 添加订单状态监听器
    this.orderStatusListener = (statusData) => {
      this.updateOrderStatus(statusData);
    };
    driverApiService.addOrderStatusListener(this.orderStatusListener);

    // 添加位置更新监听器
    this.locationUpdateListener = (locationData) => {
      this.updateDriverLocation(locationData);
    };
    driverApiService.addLocationListener(this.locationUpdateListener);

    // 添加订单数据监听器
    this.orderDataListener = (orders) => {
      this.syncOrderData(orders);
    };
    orderApiService.addListener(this.orderDataListener);
  },

  onUnload() {
    // 移除监听器
    if (this.orderStatusListener) {
      driverApiService.removeOrderStatusListener(this.orderStatusListener);
    }
    if (this.locationUpdateListener) {
      driverApiService.removeLocationListener(this.locationUpdateListener);
    }
    if (this.orderDataListener) {
      orderApiService.removeListener(this.orderDataListener);
    }
    
    // 停止位置模拟
    driverApiService.stopLocationSimulation();
  },

  onShow(){
    this.loadOrders();
    this.loadDriverInfo();
    this.syncOrderData();
  },

  onTabChange(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentTab: index
    });
    this.filterOrders();
  },

  filterOrders() {
    const { currentTab } = this.data;
    const allOrders = this.getAllOrders();
    
    let filteredOrders = [];
    
    // 根据选项卡索引筛选订单
    // 0: 待出发, 1: 行程中, 2: 已完成, 3: 已取消
    switch(currentTab) {
      case 0: // 待出发
        filteredOrders = allOrders.filter(order => order.statusCode === 1);
        break;
      case 1: // 行程中
        filteredOrders = allOrders.filter(order => order.statusCode === 2);
        break;
      case 2: // 已完成
        filteredOrders = allOrders.filter(order => order.statusCode === 3);
        break;
      case 3: // 已取消
        filteredOrders = allOrders.filter(order => order.statusCode === 4);
        break;
      default:
        filteredOrders = allOrders;
    }
    
    this.setData({
      orders: filteredOrders
    });
  },

  getAllOrders() {
    // 返回所有订单数据
    return [
      {
        id:'1',
        orderNo: 'BUS202510020001',
        schedule:{
          fromLoc:'东直门地铁站A口',
          toLoc:'上海体育馆',
          time:'09:00',
          date: '2025-11-07',
          model:'宇通大巴',
          type: 'bus'
        },
        activity: '五月天演唱会',
        status: '待出发',
        statusCode: 1,
        totalPrice: 88,
        createTime: '2025-10-15 14:30',
        passengers: [
          {name: '张三', phone: '138****1234', idCard: '110***********1234'}
        ],
        driver: {
          name: '李师傅',
          phone: '139****5678',
          carNumber: '京A12345',
          avatar: '/images/avatar-default.png',
          location: {lat: 40.123, lng: 116.456}
        }
      },
      {
        id:'2',
        orderNo: 'BUS202510020002',
        schedule:{
          fromLoc:'虹桥机场T2',
          toLoc:'广州体育中心',
          time:'14:00',
          date: '2025-11-08',
          model:'金龙大巴',
          type: 'bus'
        },
        activity: '英雄联盟总决赛',
        status: '行程中',
        statusCode: 2,
        totalPrice: 120,
        createTime: '2025-10-16 09:15',
        passengers: [
          {name: '李四', phone: '159****9876', idCard: '310***********5678'}
        ],
        driver: {
          name: '王师傅',
          phone: '138****9999',
          carNumber: '沪B67890',
          avatar: '/images/avatar-default.png',
          location: {lat: 39.456, lng: 116.789}
        }
      },
      {
        id:'3',
        orderNo: 'CHT202510020003',
        schedule:{
          fromLoc:'指定地点接送',
          toLoc:'活动现场',
          time: '任意时间',
          date: '2025-11-05',
          model:'奔驰V级商务车',
          type: 'business-charter'
        },
        activity: '商务会议',
        status: '已完成',
        statusCode: 3,
        totalPrice: 1200,
        createTime: '2025-10-10 16:45',
        passengers: [
          {name: '王五', phone: '186****1111', idCard: '440***********9012'},
          {name: '赵六', phone: '177****2222', idCard: '440***********3456'}
        ],
        driver: {
          name: '陈师傅',
          phone: '150****7777',
          carNumber: '粤A88888',
          avatar: '/images/avatar-default.png'
        }
      },
      {
        id:'4',
        orderNo: 'BUS202510020004',
        schedule:{
          fromLoc:'西单地铁站',
          toLoc:'工人体育馆',
          time:'18:00',
          date: '2025-11-01',
          model:'宇通大巴',
          type: 'bus'
        },
        activity: '演唱会',
        status: '已取消',
        statusCode: 4,
        totalPrice: 68,
        createTime: '2025-10-05 11:20',
        passengers: [
          {name: '钱七', phone: '156****3333', idCard: '110***********7890'}
        ]
      }
    ];
  },
  
  loadOrders() {
    // 从订单API服务获取数据
    const allOrders = orderApiService.getAllOrders();
    this.setData({ orders: allOrders });
    this.filterOrders();
  },

  // 同步订单数据
  syncOrderData(orders = null) {
    if (orders) {
      this.setData({ orders });
      this.filterOrders();
    } else {
      const allOrders = orderApiService.getAllOrders();
      this.setData({ orders: allOrders });
      this.filterOrders();
    }
  },

  viewDetail(e){
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({url:`/pages/order-detail/order-detail?id=${id}`});
  },

  // 加载司机信息
  loadDriverInfo() {
    const { orders } = this.data;
    const driverInfoMap = {};

    orders.forEach(order => {
      const driverInfo = driverApiService.getOrderDriverInfo(order.id);
      if (driverInfo) {
        // 获取司机详细信息
        const driverDetails = driverManagementApiService.getDriverById(driverInfo.driverId);
        if (driverDetails) {
          // 获取车辆信息
          const vehicleInfo = vehicleApiService.getVehicleById(driverDetails.vehicleId);
          
          driverInfoMap[order.id] = {
            ...driverInfo,
            driver: driverDetails,
            vehicle: vehicleInfo
          };
        } else {
          driverInfoMap[order.id] = driverInfo;
        }
      }
    });

    this.setData({ driverInfoMap });
  },

  // 更新订单状态
  updateOrderStatus(statusData) {
    const { orderId, status, statusText } = statusData;
    const orders = this.data.orders.map(order => {
      if (order.id === orderId) {
        // 根据司机端状态映射到订单状态
        let orderStatus = order.status;
        let orderStatusCode = order.statusCode;

        switch (status) {
          case 'picked_up':
            orderStatus = '行程中';
            orderStatusCode = 2;
            break;
          case 'in_transit':
            orderStatus = '行程中';
            orderStatusCode = 2;
            break;
          case 'completed':
            orderStatus = '已完成';
            orderStatusCode = 3;
            break;
        }

        return {
          ...order,
          status: orderStatus,
          statusCode: orderStatusCode
        };
      }
      return order;
    });

    this.setData({ orders });
    
    // 显示状态更新提示
    wx.showToast({
      title: statusText,
      icon: 'success'
    });
  },

  // 更新司机位置
  updateDriverLocation(locationData) {
    const { driverId, location } = locationData;
    const { driverInfoMap } = this.data;
    
    // 更新对应司机的位置信息
    Object.keys(driverInfoMap).forEach(orderId => {
      const driverInfo = driverInfoMap[orderId];
      if (driverInfo.driver.id === driverId) {
        driverInfoMap[orderId] = {
          ...driverInfo,
          driver: {
            ...driverInfo.driver,
            currentLocation: location
          },
          currentLocation: location
        };
      }
    });

    this.setData({ driverInfoMap });
  },

  // 查看司机位置
  viewDriverLocation(e) {
    e.stopPropagation();
    const { id } = e.currentTarget.dataset;
    const driverInfo = this.data.driverInfoMap[id];
    
    if (!driverInfo || !driverInfo.currentLocation) {
      wx.showToast({
        title: '暂无司机位置信息',
        icon: 'none'
      });
      return;
    }

    const { lng, lat, address } = driverInfo.currentLocation;
    
    wx.openLocation({
      latitude: lat,
      longitude: lng,
      name: '司机当前位置',
      address: address || '未知地址',
      scale: 18
    });
  },
  
  callDriver(e) {
    e.stopPropagation();
    const { id } = e.currentTarget.dataset;
    const driverInfo = this.data.driverInfoMap[id];
    
    if (driverInfo && driverInfo.driver.phone) {
      wx.makePhoneCall({
        phoneNumber: driverInfo.driver.phone,
        fail: () => {
          wx.showToast({title: '拨打失败', icon: 'none'});
        }
      });
    } else {
      // 兼容旧数据
      const phone = e.currentTarget.dataset.phone;
      if (phone) {
        wx.makePhoneCall({
          phoneNumber: phone.replace(/\*/g, ''),
          fail: () => {
            wx.showToast({title: '拨打失败', icon: 'none'});
          }
        });
      } else {
        wx.showToast({title: '暂无司机联系方式', icon: 'none'});
      }
    }
  },
  
  viewLocation(e) {
    e.stopPropagation();
    const order = this.data.orders.find(o => o.id === e.currentTarget.dataset.id);
    if (order && order.driver && order.driver.location) {
      wx.openLocation({
        latitude: order.driver.location.latitude,
        longitude: order.driver.location.longitude,
        name: '司机位置',
        address: order.driver.location.address,
        fail: () => {
          wx.showToast({title: '无法打开地图', icon: 'none'});
        }
      });
    } else {
      wx.showToast({title: '司机位置暂不可用', icon: 'none'});
    }
  }
});