import Taro from "@tarojs/taro";
import dayjs from "dayjs";
import { utils, write } from "xlsx";

// 利润表行数据接口
export interface ProfitTableRow {
  vehicleNo: string; // 车次
  shippingDate: string; // 发货日期
  originCost: number; // 产地成本
  quoteAmount: number; // 报价金额
  profit: number; // 利润
}

// 费用统计数据接口
interface ExpenseStatistics {
  totalVehicles: number;
  totalProvision: number;
  totalExpense: number;
  dailyProfit: number;
  dealerStatistics: Map<string, { vehicleCount: number; totalAmount: number }>;
  costCategoryStatistics: Map<string, number>;
}

interface ExpenseRecordVO {
  recordDate?: string;
  totalProvision?: number;
  totalExpense?: number;
  expenseProvisionList?: Array<{
    dealerName?: string;
    provisionAmount?: number;
  }>;
  expenseCostList?: Array<{ costName?: string; expenseAmount?: number }>;
}

interface ExportExcelOptions {
  title?: string;
  startDate?: string;
  endDate?: string;
  statistics?: ExpenseStatistics;
  recordList?: ExpenseRecordVO[];
  fileName?: string;
  sheetName?: string;
}

/**
 * 导出费用统计Excel文件
 * @param options 导出配置选项
 * @returns Promise<void>
 */
export const exportExpenseStatisticsExcel = async (
  options: ExportExcelOptions,
): Promise<void> => {
  const {
    title = "费用统计报表",
    startDate,
    endDate,
    statistics,
    recordList,
    fileName,
    sheetName = "费用统计",
  } = options;

  if (!recordList || recordList.length === 0) {
    Taro.showToast({
      title: "暂无数据可导出",
      icon: "none",
    });
    return;
  }

  if (!startDate || !endDate || !statistics) {
    Taro.showToast({
      title: "导出参数不完整",
      icon: "none",
    });
    return;
  }

  try {
    // 创建工作簿
    const wb = utils.book_new();

    // 创建工作表数据
    const wsData: string[][] = [];

    // 添加标题信息
    wsData.push([title]);
    wsData.push([
      `统计时间：${dayjs(startDate).format("YYYY年MM月DD日")} ~ ${dayjs(endDate).format("YYYY年MM月DD日")}`,
    ]);
    wsData.push([]); // 空行

    // 汇总概览
    wsData.push(["汇总概览"]);
    wsData.push(["总车次", statistics.totalVehicles + "车"]);
    wsData.push(["计提总额", statistics.totalProvision.toLocaleString()]);
    wsData.push(["费用总额", statistics.totalExpense.toLocaleString()]);
    wsData.push(["日常利润", statistics.dailyProfit.toLocaleString()]);
    wsData.push([]); // 空行

    // 计提方统计
    if (statistics.dealerStatistics.size > 0) {
      wsData.push(["计提方统计"]);
      wsData.push(["计提方", "车次", "计提金额"]);
      statistics.dealerStatistics.forEach((stat, dealerName) => {
        wsData.push([
          dealerName,
          stat.vehicleCount + "车",
          stat.totalAmount.toLocaleString(),
        ]);
      });
      wsData.push([]); // 空行
    }

    // 费用分类汇总
    if (statistics.costCategoryStatistics.size > 0) {
      wsData.push(["费用分类汇总"]);
      wsData.push(["费用类型", "金额"]);
      statistics.costCategoryStatistics.forEach((amount, costName) => {
        wsData.push([costName, amount.toLocaleString()]);
      });
      wsData.push([]); // 空行
    }

    // 每日明细
    wsData.push(["每日花销明细"]);
    wsData.push(["日期", "车次", "计提金额", "费用金额", "当日利润"]);
    recordList.forEach((record) => {
      const vehicleCount = record.expenseProvisionList?.length || 0;
      const dayProfit =
        (record.totalProvision || 0) - (record.totalExpense || 0);
      wsData.push([
        record.recordDate
          ? dayjs(record.recordDate).format("YYYY年MM月DD日")
          : "",
        vehicleCount + "车",
        (record.totalProvision || 0).toLocaleString(),
        (record.totalExpense || 0).toLocaleString(),
        dayProfit.toLocaleString(),
      ]);
    });

    // 创建工作表
    const ws = utils.aoa_to_sheet(wsData);

    // 设置列宽
    const wscols = [
      { wch: 20 }, // A列宽度
      { wch: 15 }, // B列宽度
      { wch: 15 }, // C列宽度
      { wch: 15 }, // D列宽度
      { wch: 15 }, // E列宽度
    ];
    ws["!cols"] = wscols;

    // 设置标题行样式（加粗）
    wsData.forEach((row, index) => {
      if (
        row.length > 0 &&
        typeof row[0] === "string" &&
        (row[0].includes("统计") ||
          row[0].includes("汇总") ||
          row[0].includes("明细"))
      ) {
        const cellAddress = utils.encode_cell({ r: index, c: 0 });
        if (!ws[cellAddress]) ws[cellAddress] = {};
        ws[cellAddress].s = { font: { bold: true } };
      }
    });

    // 将工作表添加到工作簿
    utils.book_append_sheet(wb, ws, sheetName);

    // 生成默认文件名
    const finalFileName =
      fileName ||
      `费用统计_${dayjs(startDate).format("YYYYMMDD")}_${dayjs(endDate).format("YYYYMMDD")}.xlsx`;

    // 根据环境选择不同的导出方式
    const processEnv = process.env.TARO_ENV;

    if (processEnv === "h5") {
      // H5环境：创建下载链接
      const excelBuffer = write(wb, { type: "array", bookType: "xlsx" });
      const blob = new Blob([excelBuffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = finalFileName;
      link.style.display = "none";

      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      // 清理URL对象
      window.URL.revokeObjectURL(url);

      await Taro.showToast({
        title: "导出成功",
        icon: "success",
      });
    } else {
      // 小程序环境：使用文件系统API
      const excelBuffer = write(wb, { type: "array", bookType: "xlsx" });

      // 将文件保存到本地
      const filePath = `${Taro.env.USER_DATA_PATH}/${finalFileName}`;
      Taro.getFileSystemManager().writeFile({
        filePath,
        data: excelBuffer,
        encoding: "binary",
        success() {
          console.log("文件保存成功");
          // 分享文件
          Taro.shareFileMessage({
            filePath,
          });
          Taro.showToast({
            title: "导出成功",
            icon: "success",
          });
        },
        fail(error) {
          console.error("文件保存失败:", error);
          Taro.showToast({
            title: "导出失败1",
            icon: "error",
          });
        },
      });
    }
  } catch (error) {
    console.error("导出失败:", error);
    Taro.showToast({
      title: "导出失败2",
      icon: "error",
    });
  }
};

/**
 * 通用Excel导出函数
 * @param data 工作表数据
 * @param fileName 文件名
 * @param sheetName 工作表名称
 * @param colWidths 列宽配置（可选）
 */
export const exportExcel = async (
  data: any[][],
  fileName: string,
  sheetName: string = "Sheet1",
  colWidths?: Array<{ wch: number }>,
): Promise<void> => {
  try {
    // 创建工作簿
    const wb = utils.book_new();

    // 创建工作表
    const ws = utils.aoa_to_sheet(data);

    // 设置列宽（如果提供）
    if (colWidths) {
      ws["!cols"] = colWidths;
    }

    // 将工作表添加到工作簿
    utils.book_append_sheet(wb, ws, sheetName);

    // 根据环境选择不同的导出方式
    const processEnv = process.env.TARO_ENV;

    if (processEnv === "h5") {
      // H5环境：创建下载链接
      const excelBuffer = write(wb, { type: "array", bookType: "xlsx" });
      const blob = new Blob([excelBuffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = fileName.endsWith(".xlsx")
        ? fileName
        : `${fileName}.xlsx`;
      link.style.display = "none";

      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      // 清理URL对象
      window.URL.revokeObjectURL(url);

      await Taro.showToast({
        title: "导出成功",
        icon: "success",
      });
    } else {
      // 小程序环境：使用文件系统API
      const excelBuffer = write(wb, { type: "array", bookType: "xlsx" });

      // 确保文件名有.xlsx后缀
      const finalFileName = fileName.endsWith(".xlsx")
        ? fileName
        : `${fileName}.xlsx`;
      // 将文件保存到本地
      const filePath = `${Taro.env.USER_DATA_PATH}/${finalFileName}`;
      Taro.getFileSystemManager().writeFile({
        filePath,
        data: excelBuffer,
        encoding: "binary",
        success() {
          console.log("文件保存成功");
          // 分享文件
          Taro.shareFileMessage({
            filePath,
          });
          Taro.showToast({
            title: "导出成功",
            icon: "success",
          });
        },
        fail(error) {
          console.error("文件保存失败:", error);
          Taro.showToast({
            title: "导出失败3",
            icon: "error",
          });
        },
      });
    }
  } catch (error) {
    console.error("导出失败:", error);
    Taro.showToast({
      title: "导出失败4",
      icon: "error",
    });
  }
};

/**
 * 导出利润表Excel文件
 * @param data 利润表数据
 * @param month 月份（格式：YYYY-MM）
 * @returns Promise<string>
 */
export const exportProfitTableExcel = async (
  data: ProfitTableRow[],
  month: string,
): Promise<string> => {
  // 创建工作簿
  const wb = utils.book_new();

  // 创建工作表数据
  const wsData: (string | number)[][] = [];

  // 添加标题
  wsData.push([`诚信志远利润明细`]);
  wsData.push([]); // 空行

  // 添加表头
  wsData.push(["车次", "发货日期", "产地成本", "报价金额", "利润"]);

  // 添加数据行
  data.forEach((row) => {
    wsData.push([
      row.vehicleNo,
      row.shippingDate,
      row.originCost,
      row.quoteAmount,
      row.profit,
    ]);
  });

  // 添加合计行
  const totalOriginCost = data.reduce((sum, row) => sum + row.originCost, 0);
  const totalQuoteAmount = data.reduce((sum, row) => sum + row.quoteAmount, 0);
  const totalProfit = data.reduce((sum, row) => sum + row.profit, 0);

  wsData.push([]);
  wsData.push([
    dayjs(month).format("MMMM") + "合计",
    "-",
    totalOriginCost.toFixed(2),
    totalQuoteAmount.toFixed(2),
    totalProfit.toFixed(2),
  ]);

  // 创建工作表
  const ws = utils.aoa_to_sheet(wsData);

  // 设置列宽
  const wscols = [
    { wch: 15 }, // 车次
    { wch: 15 }, // 发货日期
    { wch: 15 }, // 产地成本
    { wch: 15 }, // 报价金额
    { wch: 15 }, // 利润
  ];
  ws["!cols"] = wscols;

  // 将工作表添加到工作簿
  utils.book_append_sheet(wb, ws, "诚信志远利润明细");

  // 生成文件名
  const fileName = `诚信志远利润明细_${month}_${dayjs().format("YYYYMMDDHHmmss")}.xlsx`;

  // 根据环境选择不同的导出方式
  const processEnv = process.env.TARO_ENV;

  if (processEnv === "h5") {
    // H5环境：创建下载链接
    const excelBuffer = write(wb, { type: "array", bookType: "xlsx" });
    const blob = new Blob([excelBuffer], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });

    // 创建下载链接
    return window.URL.createObjectURL(blob);
  } else {
    // 小程序环境：使用文件系统API
    const excelBuffer = write(wb, { type: "array", bookType: "xlsx" });

    // 将文件保存到本地
    const filePath = `${Taro.env.USER_DATA_PATH}/${fileName}`;
    console.log("filePath", filePath);
    Taro.getFileSystemManager().writeFile({
      filePath,
      data: excelBuffer,
      encoding: "binary",
    });

    return filePath;
  }
};
