/**
 * 数据导出API接口系统
 * 支持活动、路线、班次等数据的表格导出功能
 */

import activityApiService from './activity-api.js';
import routeApiService from './route-api.js';
import locationApiService from './location-api.js';
import orderApiService from './order-api.js';

class ExportApiService {
  constructor() {
    this.exportFormats = {
      excel: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      csv: 'text/csv',
      json: 'application/json'
    };
  }

  // 导出活动数据
  exportActivities(searchParams = {}, format = 'excel') {
    const activityData = activityApiService.exportActivities(searchParams);
    
    const exportData = {
      title: '活动数据导出',
      headers: [
        '活动ID', '活动名称', '活动描述', '开始日期', '结束日期',
        '城市', '场馆', '地址', '状态', '组织方', '联系电话', '邮箱', '创建时间'
      ],
      rows: activityData.activities.map(activity => [
        activity.id,
        activity.name,
        activity.description,
        activity.startDate,
        activity.endDate,
        activity.city,
        activity.venue,
        activity.address,
        activity.status,
        activity.organizer,
        activity.contact.phone,
        activity.contact.email,
        activity.createTime
      ]),
      metadata: {
        exportTime: activityData.exportTime,
        total: activityData.total,
        searchParams: activityData.searchParams
      }
    };

    return this.formatExportData(exportData, format);
  }

  // 导出路线数据
  exportRoutes(searchParams = {}, format = 'excel') {
    const routeData = routeApiService.exportRoutes(searchParams);
    
    const exportData = {
      title: '路线数据导出',
      headers: [
        '路线ID', '活动名称', '出发城市', '到达城市', '出发地点', '到达地点',
        '距离', '时长', '路线类型', '状态', '班次数量', '创建时间'
      ],
      rows: routeData.routes.map(route => [
        route.id,
        route.activityName,
        route.fromCity,
        route.toCity,
        route.fromLocation,
        route.toLocation,
        route.distance,
        route.duration,
        this.getRouteTypeName(route.type),
        route.status,
        route.schedules.length,
        route.createTime
      ]),
      metadata: {
        exportTime: routeData.exportTime,
        total: routeData.total,
        searchParams: routeData.searchParams
      }
    };

    return this.formatExportData(exportData, format);
  }

  // 导出班次数据
  exportSchedules(activityId = null, format = 'excel') {
    const routes = routeApiService.getAllRoutes();
    let schedules = [];
    
    if (activityId) {
      const activityRoutes = routes.filter(route => route.activityId === activityId);
      schedules = activityRoutes.flatMap(route => 
        route.schedules.map(schedule => ({
          ...schedule,
          routeId: route.id,
          activityName: route.activityName,
          fromLocation: route.fromLocation,
          toLocation: route.toLocation,
          routeType: route.type
        }))
      );
    } else {
      schedules = routes.flatMap(route => 
        route.schedules.map(schedule => ({
          ...schedule,
          routeId: route.id,
          activityName: route.activityName,
          fromLocation: route.fromLocation,
          toLocation: route.toLocation,
          routeType: route.type
        }))
      );
    }
    
    const exportData = {
      title: '班次数据导出',
      headers: [
        '班次ID', '路线ID', '活动名称', '出发地点', '到达地点', '出发时间',
        '到达时间', '总票数', '已售票数', '剩余票数', '票价', '车型',
        '司机姓名', '司机电话', '路线类型', '状态', '创建时间'
      ],
      rows: schedules.map(schedule => [
        schedule.id,
        schedule.routeId,
        schedule.activityName,
        schedule.fromLocation,
        schedule.toLocation,
        schedule.departureTime,
        schedule.arrivalTime,
        schedule.totalTickets,
        schedule.soldTickets,
        schedule.remainingTickets,
        schedule.price,
        schedule.vehicleModel,
        schedule.driver.name,
        schedule.driver.phone,
        this.getRouteTypeName(schedule.routeType),
        schedule.status,
        schedule.createTime
      ]),
      metadata: {
        exportTime: new Date().toISOString(),
        total: schedules.length,
        activityId
      }
    };

    return this.formatExportData(exportData, format);
  }

  // 导出订单数据
  exportOrders(searchParams = {}, format = 'excel') {
    const orderData = orderApiService.exportOrders(searchParams);
    
    const exportData = {
      title: '订单数据导出',
      headers: [
        '订单号', '活动名称', '出发地', '目的地', '出发时间', '乘客数量',
        '总金额', '订单状态', '创建时间', '支付时间', '联系人', '联系电话'
      ],
      rows: orderData.orders.map(order => [
        order.orderNo,
        order.activity,
        order.schedule.fromLoc,
        order.schedule.toLoc,
        `${order.schedule.date} ${order.schedule.time}`,
        order.passengers.length,
        order.totalPrice,
        order.status,
        order.createTime,
        order.paymentTime || '',
        order.contactInfo.name,
        order.contactInfo.phone
      ]),
      metadata: {
        exportTime: orderData.exportTime,
        total: orderData.total,
        searchParams: orderData.searchParams
      }
    };

    return this.formatExportData(exportData, format);
  }

  // 导出地区数据
  exportLocations(searchParams = {}, format = 'excel') {
    const locationData = locationApiService.exportLocations(searchParams);
    
    const exportData = {
      title: '地区数据导出',
      headers: [
        '地区ID', '地区名称', '地区代码', '层级', '父级ID', '排序', '状态', '创建时间'
      ],
      rows: locationData.locations.map(location => [
        location.id,
        location.name,
        location.code,
        this.getLevelName(location.level),
        location.parentId || '',
        location.sort,
        location.status,
        location.createTime
      ]),
      metadata: {
        exportTime: locationData.exportTime,
        total: locationData.total,
        searchParams: locationData.searchParams
      }
    };

    return this.formatExportData(exportData, format);
  }

  // 导出综合报表
  exportComprehensiveReport(activityId = null, format = 'excel') {
    const activities = activityId ? 
      [activityApiService.getActivityById(activityId)] : 
      activityApiService.getAllActivities();
    
    const reportData = {
      title: '综合数据报表',
      sections: []
    };

    activities.forEach(activity => {
      if (!activity) return;
      
      const routes = routeApiService.getRoutesByActivityId(activity.id);
      const orders = orderApiService.getAllOrders().filter(order => 
        order.activity === activity.name
      );

      // 活动基本信息
      reportData.sections.push({
        sectionTitle: `活动：${activity.name}`,
        headers: ['项目', '数值'],
        rows: [
          ['活动ID', activity.id],
          ['活动名称', activity.name],
          ['开始日期', activity.startDate],
          ['结束日期', activity.endDate],
          ['城市', activity.city],
          ['场馆', activity.venue],
          ['状态', activity.status]
        ]
      });

      // 路线统计
      reportData.sections.push({
        sectionTitle: '路线统计',
        headers: ['路线类型', '路线数量', '班次数量', '总票数', '已售票数', '总收入'],
        rows: this.getRouteStatistics(routes)
      });

      // 订单统计
      reportData.sections.push({
        sectionTitle: '订单统计',
        headers: ['订单号', '乘客数量', '金额', '状态', '创建时间'],
        rows: orders.map(order => [
          order.orderNo,
          order.passengers.length,
          order.totalPrice,
          order.status,
          order.createTime
        ])
      });
    });

    return this.formatComprehensiveData(reportData, format);
  }

  // 格式化导出数据
  formatExportData(data, format) {
    switch (format) {
      case 'csv':
        return this.formatAsCSV(data);
      case 'json':
        return this.formatAsJSON(data);
      case 'excel':
      default:
        return this.formatAsExcel(data);
    }
  }

  // 格式化为CSV
  formatAsCSV(data) {
    const csvContent = [
      data.headers.join(','),
      ...data.rows.map(row => row.map(cell => `"${cell}"`).join(','))
    ].join('\n');
    
    return {
      content: csvContent,
      mimeType: this.exportFormats.csv,
      filename: `${data.title}_${new Date().toISOString().split('T')[0]}.csv`
    };
  }

  // 格式化为JSON
  formatAsJSON(data) {
    const jsonData = {
      title: data.title,
      headers: data.headers,
      data: data.rows.map(row => {
        const obj = {};
        data.headers.forEach((header, index) => {
          obj[header] = row[index];
        });
        return obj;
      }),
      metadata: data.metadata
    };
    
    return {
      content: JSON.stringify(jsonData, null, 2),
      mimeType: this.exportFormats.json,
      filename: `${data.title}_${new Date().toISOString().split('T')[0]}.json`
    };
  }

  // 格式化为Excel（模拟）
  formatAsExcel(data) {
    // 在实际应用中，这里会使用专门的Excel库
    // 这里返回一个模拟的Excel数据结构
    return {
      content: {
        title: data.title,
        headers: data.headers,
        rows: data.rows,
        metadata: data.metadata
      },
      mimeType: this.exportFormats.excel,
      filename: `${data.title}_${new Date().toISOString().split('T')[0]}.xlsx`
    };
  }

  // 格式化综合数据
  formatComprehensiveData(data, format) {
    return {
      content: data,
      mimeType: this.exportFormats[format],
      filename: `${data.title}_${new Date().toISOString().split('T')[0]}.${format}`
    };
  }

  // 获取路线类型名称
  getRouteTypeName(type) {
    const typeMap = {
      'bus': '大巴拼车',
      'business': '商务车',
      'charter': '包车'
    };
    return typeMap[type] || type;
  }

  // 获取层级名称
  getLevelName(level) {
    const levelMap = {
      'province': '省份',
      'city': '城市',
      'district': '区县'
    };
    return levelMap[level] || level;
  }

  // 获取路线统计
  getRouteStatistics(routes) {
    const stats = {};
    
    routes.forEach(route => {
      if (!stats[route.type]) {
        stats[route.type] = {
          routeCount: 0,
          scheduleCount: 0,
          totalTickets: 0,
          soldTickets: 0,
          totalRevenue: 0
        };
      }
      
      stats[route.type].routeCount++;
      stats[route.type].scheduleCount += route.schedules.length;
      
      route.schedules.forEach(schedule => {
        stats[route.type].totalTickets += schedule.totalTickets;
        stats[route.type].soldTickets += schedule.soldTickets;
        stats[route.type].totalRevenue += schedule.soldTickets * schedule.price;
      });
    });

    return Object.keys(stats).map(type => [
      this.getRouteTypeName(type),
      stats[type].routeCount,
      stats[type].scheduleCount,
      stats[type].totalTickets,
      stats[type].soldTickets,
      stats[type].totalRevenue
    ]);
  }

  // 下载文件
  downloadFile(exportData) {
    // 在实际应用中，这里会触发文件下载
    console.log('下载文件:', exportData.filename);
    console.log('文件内容:', exportData.content);
    
    // 模拟下载成功
    return {
      success: true,
      filename: exportData.filename,
      size: JSON.stringify(exportData.content).length
    };
  }
}

// 创建单例实例
const exportApiService = new ExportApiService();

export default exportApiService;

