import { useEffect, useState } from "react";
import { Image, Text, View } from "@tarojs/components";
import { Button, TabPane, Tabs } from "@nutui/nutui-react-taro";
import Taro from "@tarojs/taro";
import { Icon } from "@/components";
import { business, poster } from "@/services";
import {
  exportProfitTableExcel,
  ProfitTableRow,
  ProfitTableTemplate,
} from "@/utils";
import dayjs from "dayjs";
import { ProfitCalculationService } from "@/utils/classes/calculators";

interface Step3SuccessProps {
  pdfUrl: string;
  picUrl?: string;
  orderVO: BusinessAPI.OrderVO;
}

export default function Step3Success(props: Step3SuccessProps) {
  const { pdfUrl, picUrl, orderVO } = props!;
  const [tempFilePath, setTempFilePath] = useState<string>();
  const [tabValue, setTabValue] = useState<string>("0"); // 默认选中发货单
  const [excelTempFilePath, setExcelTempFilePath] = useState<string>();

  // 利润表相关状态
  const [profitPicUrl, setProfitPicUrl] = useState<string>();

  // 获取当前月份
  const currentMonth = dayjs(orderVO.orderVehicle.deliveryTime).format(
    "YYYY-MM-01",
  );
  const [profitData, setProfitData] = useState<ProfitTableRow[]>([]);

  const init = async (currentMonth: string) => {
    // 查询本月的所有订单数据
    const {
      data: { data: orderVOList = [] },
    } = await business.order.listOrder({
      orderListQry: {
        month: currentMonth,
        state: "COMPLETED", // 只查询已完成的订单
      },
    });

    // 获取当前车次
    const currentVehicleNo = orderVO.orderVehicle.vehicleNo;

    // 筛选截止到当前车次之前的数据
    const profitData: ProfitTableRow[] = [];
    let includeNext = true;

    // orderVOList 根据车次正序
    orderVOList.sort((a, b) => {
      return (
        Number(a.orderVehicle.vehicleNo) - Number(b.orderVehicle?.vehicleNo)
      );
    });

    for (const order of orderVOList) {
      // 如果还没有到达当前车次，继续
      if (includeNext) {
        const profitRow = ProfitCalculationService.calculateOrderProfit(order);
        profitData.push(profitRow);

        // 如果是当前车次，停止添加
        if (order.orderVehicle.vehicleNo === currentVehicleNo) {
          includeNext = false;
        }
      }
    }

    setProfitData(profitData);
  };

  useEffect(() => {
    if (currentMonth) {
      init(currentMonth).then();
    }
  }, [currentMonth]);

  // 保存图片
  const handleSaveImage = async () => {
    if (!picUrl) {
      Taro.showToast({
        title: "没有可保存的预览图片",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    try {
      // 下载文件
      const downloadRes = await Taro.downloadFile({
        url: picUrl!,
      });
      // 保存图片到相册
      await Taro.saveImageToPhotosAlbum({
        filePath: downloadRes.tempFilePath,
      });

      Taro.showToast({
        title: "图片已保存到相册",
        icon: "success",
        duration: 2000,
      });
    } catch (error) {
      console.error("保存图片失败:", error);
      Taro.showToast({
        title: "保存图片失败，请检查相册权限",
        icon: "none",
        duration: 2000,
      });
    }
  };

  // 下载PDF
  const handleDownloadPDF = async () => {
    Taro.showToast({
      title: "正在下载PDF文件",
      icon: "loading",
      duration: 2000,
    });

    try {
      // 下载文件
      const downloadRes = await Taro.downloadFile({
        url: pdfUrl!,
      });

      if (downloadRes.tempFilePath) {
        setTempFilePath(downloadRes.tempFilePath);
        Taro.showToast({
          title: "PDF下载成功",
          icon: "success",
          duration: 2000,
        });
      }
    } catch (error) {
      console.error("下载PDF失败:", error);
      Taro.showToast({
        title: "下载PDF失败",
        icon: "none",
        duration: 2000,
      });
    }
  };

  // 查看PDF文档
  const handleViewPDF = async () => {
    if (!tempFilePath) {
      await handleDownloadPDF();
    }

    if (tempFilePath) {
      Taro.openDocument({
        filePath: tempFilePath,
        showMenu: true,
      });
    }
  };

  // 下载Excel
  const handleDownloadExcel = async () => {
    Taro.showToast({
      title: "正在下载Excel文件",
      icon: "loading",
      duration: 2000,
    });

    const profitExcelUrl = await exportProfitTableExcel(
      profitData,
      currentMonth,
    );

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

    if (processEnv === "h5") {
      const link = document.createElement("a");
      link.href = profitExcelUrl;
      link.download = `诚信志远利润明细_${currentMonth}.xlsx`;
      link.style.display = "none";

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

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

      await Taro.showToast({
        title: "导出成功",
        icon: "success",
      });
    } else {
      setExcelTempFilePath(profitExcelUrl);
      Taro.showToast({
        title: "Excel下载成功",
        icon: "success",
        duration: 2000,
      });
    }
  };

  // 查看Excel文档
  const handleViewExcel = async () => {
    if (!excelTempFilePath) {
      await handleDownloadExcel();
    }

    if (excelTempFilePath) {
      Taro.openDocument({
        filePath: excelTempFilePath,
        showMenu: true,
      });
    }
  };

  // 保存利润表图片
  const handleSaveProfitImage = async () => {
    if (!profitPicUrl) {
      Taro.showToast({
        title: "没有可保存的利润表图片",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    try {
      // 下载文件
      const downloadRes = await Taro.downloadFile({
        url: profitPicUrl!,
      });
      // 保存图片到相册
      await Taro.saveImageToPhotosAlbum({
        filePath: downloadRes.tempFilePath,
      });

      Taro.showToast({
        title: "图片已保存到相册",
        icon: "success",
        duration: 2000,
      });
    } catch (error) {
      console.error("保存图片失败:", error);
      Taro.showToast({
        title: "保存图片失败，请检查相册权限",
        icon: "none",
        duration: 2000,
      });
    }
  };

  // 生成利润表
  const generateProfitTable = async () => {
    try {
      if (!profitData || profitData.length === 0) {
        Taro.showToast({
          title: "本月暂无订单数据",
          icon: "none",
        });
        return;
      }

      // 生成预览图片
      const template = new ProfitTableTemplate(profitData, currentMonth);
      const {
        data: { data: picData },
      } = await poster.poster.postApiV1Poster({
        html: template.generateHtmlString(),
        //@ts-ignore
        format: "a4",
      });

      setProfitPicUrl(picData?.path);
    } catch (error) {
      console.error("生成利润表失败:", error);
      Taro.showToast({
        title: "生成利润表失败",
        icon: "none",
      });
    }
  };

  return (
    <View className="flex flex-1 flex-col overflow-hidden rounded-md bg-gray-100 shadow-md">
      {/* Tab 切换 */}
      <View className="bg-white px-2.5 pt-2.5">
        <Tabs
          style={{
            // @ts-ignore
            "--nutui-tabs-tabpane-padding": 0,
          }}
          value={tabValue}
          onChange={async (value) => {
            if (value === 1 && !profitPicUrl) {
              await generateProfitTable();
            }
            setTabValue(value.toString());
          }}
        >
          <TabPane title="发货单" value={0}>
            {/* 预览区域 */}
            <View className="p-2.5">
              <View className="rounded-lg bg-white shadow-sm">
                {picUrl ? (
                  <View
                    className="overflow-hidden rounded-lg border border-gray-200"
                    style={{ maxHeight: Taro.pxTransform(400) }}
                  >
                    <Image
                      src={picUrl}
                      mode="widthFix"
                      className="w-full"
                      onClick={() => {
                        Taro.previewImage({
                          urls: [picUrl],
                          current: picUrl,
                        });
                      }}
                    />
                  </View>
                ) : (
                  <View className="flex h-48 items-center justify-center rounded-lg border-2 border-dashed border-gray-300 bg-gray-50">
                    <Text className="text-gray-500">暂无预览图片</Text>
                  </View>
                )}
              </View>
            </View>

            {/* 底部按钮区域 */}
            <View className="border-t border-gray-100 bg-white p-2.5">
              <View className="flex flex-col gap-2.5">
                {/* 保存图片按钮 */}
                {picUrl && (
                  <Button
                    icon={<Icon name="download" size={16} color={"white"} />}
                    type="primary"
                    size={"large"}
                    block
                    onClick={handleSaveImage}
                    className="flex items-center justify-center"
                  >
                    <Text className="font-medium">保存图片</Text>
                  </Button>
                )}

                {/* PDF操作按钮 */}
                <View className="flex gap-3">
                  <View className="flex-1">
                    <Button
                      icon={<Icon name="file-pdf" size={16} color={"white"} />}
                      type="primary"
                      size={"large"}
                      color="orange"
                      block
                      onClick={handleDownloadPDF}
                    >
                      <Text className="font-medium">下载PDF</Text>
                    </Button>
                  </View>
                  {tempFilePath && (
                    <View className="flex-1">
                      <Button
                        icon={<Icon name="eye" size={16} color={"orange"} />}
                        type="default"
                        color="orange"
                        fill={"outline"}
                        size={"large"}
                        block
                        onClick={handleViewPDF}
                      >
                        <Text className="text-orange font-medium">查看PDF</Text>
                      </Button>
                    </View>
                  )}
                </View>

                {/* 提示信息 */}
                <View className="text-center">
                  <Text className="text-xs text-gray-500">
                    点击预览图片可放大查看
                  </Text>
                </View>
              </View>
            </View>
          </TabPane>

          {orderVO.orderDealer.shareAdjusted && (
            <TabPane title="利润表" value={1}>
              {/* 预览区域 */}
              <View className="p-2.5">
                <View className="rounded-lg bg-white shadow-sm">
                  {profitPicUrl ? (
                    <View
                      className="overflow-hidden rounded-lg border border-gray-200"
                      style={{ maxHeight: Taro.pxTransform(400) }}
                    >
                      <Image
                        src={profitPicUrl}
                        mode="widthFix"
                        className="w-full"
                        onClick={() => {
                          Taro.previewImage({
                            urls: [profitPicUrl],
                            current: profitPicUrl,
                          });
                        }}
                      />
                    </View>
                  ) : (
                    <View className="flex h-48 items-center justify-center rounded-lg border-2 border-dashed border-gray-300 bg-gray-50">
                      <Text className="text-gray-500">暂无利润表预览图片</Text>
                    </View>
                  )}
                </View>
              </View>

              {/* 底部按钮区域 */}
              <View className="border-t border-gray-100 bg-white p-2.5">
                <View className="flex flex-col gap-2.5">
                  {/* 保存利润表图片按钮 */}
                  {profitPicUrl && (
                    <Button
                      icon={<Icon name="download" size={16} color={"white"} />}
                      type="primary"
                      size={"large"}
                      block
                      onClick={handleSaveProfitImage}
                      className="flex items-center justify-center"
                    >
                      <Text className="font-medium">保存图片</Text>
                    </Button>
                  )}

                  {/* Excel操作按钮 */}
                  <View className="flex gap-3">
                    <View className="flex-1">
                      <Button
                        icon={
                          <Icon name="file-excel" size={16} color={"white"} />
                        }
                        type="primary"
                        size={"large"}
                        color="orange"
                        block
                        onClick={handleDownloadExcel}
                      >
                        <Text className="font-medium">下载Excel</Text>
                      </Button>
                    </View>
                    {excelTempFilePath && (
                      <View className="flex-1">
                        <Button
                          icon={<Icon name="eye" size={16} color={"orange"} />}
                          type="default"
                          color="orange"
                          fill={"outline"}
                          size={"large"}
                          block
                          onClick={handleViewExcel}
                        >
                          <Text className="font-medium">查看Excel</Text>
                        </Button>
                      </View>
                    )}
                  </View>

                  {/* 提示信息 */}
                  <View className="text-center">
                    <Text className="text-xs text-gray-500">
                      点击预览图片可放大查看
                    </Text>
                  </View>
                </View>
              </View>
            </TabPane>
          )}
        </Tabs>
      </View>
    </View>
  );
}
