import hocAuth from "@/hocs/auth";
import { CommonComponent } from "@/types/typings";
import { useEffect, useState } from "react";
import { business } from "@/services";
import { Image, Label, Text, View } from "@tarojs/components";
import { Button, SafeArea } from "@nutui/nutui-react-taro";
import Taro from "@tarojs/taro";
import { buildUrl } from "@/utils";
import dayjs from "dayjs";
import { Icon } from "@/components";

export default hocAuth(function Page(props: CommonComponent) {
  const { setLoading, router } = props;
  const supplierInvoiceId = router.params
    .supplierInvoiceId as BusinessAPI.SupplierInvoiceVO["supplierInvoiceId"];

  const [supplierInvoiceVO, setSupplierInvoiceVO] =
    useState<BusinessAPI.SupplierInvoiceVO>();

  const init = async (
    supplierInvoiceId: BusinessAPI.SupplierInvoiceVO["supplierInvoiceId"],
  ) => {
    setLoading(true);
    const {
      data: { data: supplierInvoiceVO, success },
    } = await business.supplierInvoice.showSupplierInvoice({
      supplierInvoiceShowQry: {
        supplierInvoiceId: supplierInvoiceId,
      },
    });

    if (success) {
      setSupplierInvoiceVO(supplierInvoiceVO);
    }

    setLoading(false);
  };

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

  if (!supplierInvoiceVO) {
    return;
  }

  // 计算总开票金额
  const totalAmount =
    supplierInvoiceVO.orderSupplierInvoiceList?.reduce(
      (sum, item) => sum + (item.invoiceAmount || 0),
      0,
    ) || 0;

  // 处理图片预览
  const handleImagePreview = (url: string, urls: string[]) => {
    Taro.previewImage({
      current: url,
      urls: urls,
    });
  };

  // 下载PDF文件
  const handleDownloadPDF = (url: string, _fileName: string) => {
    Taro.downloadFile({
      url: url,
      success: (res) => {
        if (res.statusCode === 200) {
          Taro.openDocument({
            filePath: res.tempFilePath,
            fileType: "pdf",
            showMenu: true,
            success: () => {
              console.log("文件打开成功");
            },
          });
        }
      },
    });
  };

  // 判断是否为图片文件
  const isImageFile = (fileName?: string) => {
    if (!fileName) return false;
    const ext = fileName.toLowerCase().split(".").pop();
    return ["jpg", "jpeg", "png", "gif", "webp", "bmp"].includes(ext || "");
  };

  // 判断是否为PDF文件
  const isPDFFile = (fileName?: string) => {
    if (!fileName) return false;
    const ext = fileName.toLowerCase().split(".").pop();
    return ext === "pdf";
  };

  return (
    <>
      <View className={"flex flex-1 flex-col gap-2.5 p-2.5"}>
        {/* 1. 基础信息卡片 */}
        <View className={"rounded-xl bg-white px-4 py-3 shadow-sm"}>
          <View className={"mb-3 flex items-center gap-2"}>
            <View className={"bg-primary h-1 w-1 rounded-full"} />
            <Text className={"text-base font-bold text-gray-800"}>
              基础信息
            </Text>
          </View>
          <View className={"flex flex-col gap-3"}>
            <View className={"flex flex-row items-center justify-between"}>
              <Label className={"text-neutral-dark text-xs"}>发票开具人</Label>
              <Text className={"text-neutral-darkest text-xs font-medium"}>
                {supplierInvoiceVO.supplierName || "-"}
              </Text>
            </View>
          </View>
        </View>

        {/* 2. 关联车次信息列表卡片 */}
        <View className={"rounded-xl bg-white px-4 py-3 shadow-sm"}>
          <View className={"mb-3 flex items-center gap-2"}>
            <View className={"bg-primary h-1 w-1 rounded-full"} />
            <Text className={"text-base font-bold text-gray-800"}>
              关联车次信息
            </Text>
          </View>
          <View className={"flex flex-col gap-2.5"}>
            {supplierInvoiceVO.orderSupplierInvoiceList?.map((item, index) => {
              // 判断开票类型：如果发票开具人与车次瓜农相同，则为"自己"，否则为"代开"
              const invoiceType =
                item.supplierId === supplierInvoiceVO.supplierId
                  ? "自己"
                  : "代开";

              return (
                <View key={index} className={"rounded-lg bg-gray-50 p-3"}>
                  <View className={"mb-2 flex items-center justify-between"}>
                    <Text className={"text-neutral-darkest text-sm font-bold"}>
                      {item.dealerName}{" "}
                      {item?.vehicleNo
                        ? `第${item?.vehicleNo}车`
                        : "暂未生成车次"}
                    </Text>
                    <Text
                      className={`rounded px-2 py-0.5 text-xs font-medium ${
                        invoiceType === "自己"
                          ? "bg-blue-100 text-blue-700"
                          : "bg-purple-100 text-purple-700"
                      }`}
                    >
                      {invoiceType}
                    </Text>
                  </View>
                  <View className={"flex flex-col gap-1.5"}>
                    <View
                      className={"flex flex-row items-center justify-between"}
                    >
                      <Label className={"text-neutral-dark text-xs"}>
                        瓜农名称
                      </Label>
                      <Text
                        className={"text-neutral-darkest text-xs font-medium"}
                      >
                        {item.name || "-"}
                      </Text>
                    </View>
                    <View
                      className={"flex flex-row items-center justify-between"}
                    >
                      <Label className={"text-neutral-dark text-xs"}>
                        开票金额
                      </Label>
                      <Text className={"text-primary text-xs font-bold"}>
                        ¥{item.invoiceAmount?.toFixed(2) || "0.00"}
                      </Text>
                    </View>
                  </View>
                </View>
              );
            }) || (
              <View className={"py-4 text-center"}>
                <Text className={"text-xs text-neutral-400"}>
                  暂无关联车次信息
                </Text>
              </View>
            )}
          </View>
        </View>

        {/* 3. 发票信息卡片 */}
        <View className={"rounded-xl bg-white px-4 py-3 shadow-sm"}>
          <View className={"mb-3 flex items-center gap-2"}>
            <View className={"bg-primary h-1 w-1 rounded-full"} />
            <Text className={"text-base font-bold text-gray-800"}>
              发票信息
            </Text>
          </View>
          <View className={"flex flex-col gap-3"}>
            <View className={"flex flex-row items-center justify-between"}>
              <Label className={"text-neutral-dark text-xs"}>发票金额</Label>
              <Text className={"text-primary text-sm font-bold"}>
                ¥{totalAmount.toFixed(2)}
              </Text>
            </View>
            <View className={"flex flex-row items-center justify-between"}>
              <Label className={"text-neutral-dark text-xs"}>登记时间</Label>
              <Text className={"text-neutral-darkest text-xs font-medium"}>
                {supplierInvoiceVO.registrationTime
                  ? dayjs(supplierInvoiceVO.registrationTime).format(
                      "YYYY-MM-DD HH:mm",
                    )
                  : "-"}
              </Text>
            </View>
            {/* 发票照片预览 */}
            {supplierInvoiceVO.invoiceImg &&
              supplierInvoiceVO.invoiceImg.length > 0 && (
                <View className={"flex flex-col gap-2"}>
                  <Label className={"text-neutral-dark text-xs"}>
                    发票照片
                  </Label>
                  <View className={"flex flex-wrap gap-2"}>
                    {supplierInvoiceVO.invoiceImg.map((file, index) => {
                      const isImage = isImageFile(file.fileName);
                      const isPDF = isPDFFile(file.fileName);

                      return (
                        <View
                          key={index}
                          className={
                            "relative h-20 w-20 flex-shrink-0 overflow-hidden rounded-lg bg-gray-100"
                          }
                        >
                          {isImage && file.filePath && (
                            <Image
                              src={file.filePath}
                              className={"h-full w-full"}
                              mode={"aspectFill"}
                              onClick={() => {
                                const imageUrls =
                                  supplierInvoiceVO.invoiceImg
                                    ?.filter((img) => isImageFile(img.fileName))
                                    .map((img) => img.filePath!)
                                    .filter(Boolean) || [];
                                handleImagePreview(file.filePath!, imageUrls);
                              }}
                            />
                          )}
                          {isPDF && (
                            <View
                              className={
                                "flex h-full w-full flex-col items-center justify-center gap-1"
                              }
                              onClick={() => {
                                if (file.filePath) {
                                  handleDownloadPDF(
                                    file.filePath,
                                    file.fileName || "发票.pdf",
                                  );
                                }
                              }}
                            >
                              <Icon
                                name={"file-pdf"}
                                size={24}
                                className={"text-red-500"}
                              />
                              <Text className={"text-neutral-dark text-[10px]"}>
                                PDF
                              </Text>
                            </View>
                          )}
                        </View>
                      );
                    })}
                  </View>
                </View>
              )}
          </View>
        </View>
      </View>

      {/* 4. 底部返回首页按钮 */}
      <View className={"sticky bottom-0 z-10 bg-white"}>
        <View className="flex justify-center gap-2 border-t border-gray-200 p-2.5">
          <View className={"flex-1"}>
            <Button
              block
              type={"default"}
              size={"large"}
              onClick={() => {
                Taro.switchTab({
                  url: buildUrl("/pages/main/index/index"),
                });
              }}
            >
              返回首页
            </Button>
          </View>
        </View>
        <SafeArea position={"bottom"} />
      </View>
    </>
  );
});
