import { Image, Text, View } from "@tarojs/components";
import { Button, Popup, SafeArea, Toast } from "@nutui/nutui-react-taro";
import Taro from "@tarojs/taro";
import { uploadFile } from "@/utils";
import { Icon } from "@/components";
import { useState } from "react";
import { business } from "@/services";
import { globalStore } from "@/store/global-store";
import { DecimalUtils } from "@/utils/classes/calculators/core/DecimalUtils";

interface IInvoiceBatchUploadProps {
  visible: boolean;
  setVisible: (visible: boolean) => void;
  onFinish: () => void;
  orderSupplierList: BusinessAPI.OrderSupplierVO[];
  invoiceIssuer: BusinessAPI.SupplierVO; // 发票开具人
}

export default function InvoiceCreate(props: IInvoiceBatchUploadProps) {
  const { visible, setVisible, onFinish, orderSupplierList, invoiceIssuer } =
    props;

  const [submitLoading, setSubmitLoading] = useState<boolean>(false);
  const { setLoading } = globalStore((state: any) => state);
  const [invoiceImg, setInvoiceImg] = useState<
    BusinessAPI.OrderSupplier["invoiceImg"]
  >([]);
  // 提交申请
  const handleSubmit = async () => {
    // 这里添加提交申请的逻辑
    setSubmitLoading(true);
    setLoading(true);
    const {
      data: { success },
    } = await business.supplierInvoice.createSupplierInvoice({
      type: "FARMER",
      supplierId: invoiceIssuer.supplierId,
      supplierName: invoiceIssuer.name,
      orderSupplierInvoiceList: orderSupplierList.map(
        (orderSupplierVO: BusinessAPI.OrderSupplierVO) => {
          return {
            orderSupplierId: orderSupplierVO.orderSupplierId,
            orderId: orderSupplierVO.orderId,
            supplierId: orderSupplierVO.supplierId,
            name: orderSupplierVO.name,
            type: orderSupplierVO.type,
            invoiceAmount: orderSupplierVO.invoiceAmount,
            dealerId: orderSupplierVO.orderVO.orderVehicle.dealerId!,
            dealerName: orderSupplierVO.orderVO.orderVehicle.dealerName!,
            vehicleNo: orderSupplierVO.orderVO.orderVehicle.vehicleNo!,
          };
        },
      ),
      invoiceImg: invoiceImg,
    });

    if (success) {
      Toast.show("toast", {
        icon: "success",
        title: "提交成功",
        content: "发票已批量上传",
      });
      onFinish?.();
      setVisible(false);
      setSubmitLoading(false);
      setLoading(false);
      setInvoiceImg([]);
    }
  };

  // 计算选中车次的总重量和总金额
  const calculateTotals = () => {
    return orderSupplierList.reduce(
      (totals, order) => {
        totals.totalWeight = DecimalUtils.add(
          totals.totalWeight,
          order.netWeight || 0,
        );
        totals.totalAmount = DecimalUtils.add(
          totals.totalAmount,
          order.invoiceAmount || 0,
        );
        return totals;
      },
      { totalWeight: 0, totalAmount: 0 },
    );
  };

  const { totalWeight, totalAmount } = calculateTotals();

  return (
    <Popup
      duration={150}
      style={{
        minHeight: "auto",
      }}
      closeable
      destroyOnClose
      visible={visible}
      title={"批量上传发票"}
      position="bottom"
      onClose={() => setVisible(false)}
      onOverlayClick={() => setVisible(false)}
      lockScroll
      round
    >
      <View className="flex flex-col">
        {/* 发票开具人信息 */}
        {invoiceIssuer && (
          <View className="mb-2 flex items-center justify-between border-b border-gray-200 bg-blue-50 p-2.5">
            <View className="text-sm font-medium text-gray-800">
              发票开具人：
              <View className="text-primary inline">{invoiceIssuer.name}</View>
            </View>
          </View>
        )}

        {/* 统计信息 */}
        <View className="mb-2 flex items-center justify-between p-2.5">
          <View className="text-sm font-medium text-gray-800">
            已选{" "}
            <View className="text-primary inline">
              {orderSupplierList.length}
            </View>{" "}
            车次
          </View>
          <View className="text-sm font-medium text-gray-800">
            总重量：
            <View className="text-primary inline">{totalWeight}</View> 斤
          </View>
          <View className="text-sm font-medium text-gray-800">
            总金额：{" "}
            <View className="text-primary inline">
              {totalAmount.toFixed(2)}
            </View>
          </View>
        </View>

        {/* 上传发票 */}
        <View className="rounded-lg bg-white p-2.5">
          <View className="flex flex-col gap-2.5">
            {invoiceImg && invoiceImg?.length > 0 ? (
              invoiceImg?.map((uploadFileItem, index) => (
                <View
                  key={uploadFileItem.fileName || index}
                  className="bg-primary/10 flex flex-col gap-2.5 rounded-lg p-2.5"
                >
                  <View className="flex items-center">
                    <View className="relative mr-3 h-16 w-16 overflow-hidden rounded-lg">
                      <Image
                        className="h-full w-full object-cover"
                        src={uploadFileItem.filePath!}
                      />
                    </View>
                    <View className="flex-1">
                      <View className="font-medium" id="invoice-filename">
                        {uploadFileItem.fileName}
                      </View>
                      <View className="text-sm text-gray-500">
                        {Number(uploadFileItem.fileSize! / 1024 / 1024).toFixed(
                          2,
                        )}{" "}
                        MB
                      </View>
                    </View>
                  </View>
                  <View className="flex flex-row gap-2.5">
                    <View className={"flex-1"}>
                      <Button
                        type={"primary"}
                        size={"large"}
                        fill={"outline"}
                        block
                        onClick={() => {
                          setInvoiceImg([]);
                        }}
                      >
                        <View>重新上传</View>
                      </Button>
                    </View>
                    <View className={"flex-1"}>
                      <Button
                        type={"warning"}
                        size={"large"}
                        fill={"outline"}
                        block
                        onClick={() => {
                          setInvoiceImg([]);
                          Toast.show("toast", {
                            title: "删除成功",
                            icon: "success",
                            content: "发票已删除",
                          });
                        }}
                      >
                        <View>删除</View>
                      </Button>
                    </View>
                  </View>
                </View>
              ))
            ) : (
              <View className={`flex w-full flex-row items-center gap-2.5`}>
                <View
                  className={
                    "border-primary bg-primary/5 flex h-24 flex-1 flex-col items-center justify-center rounded-md border-2 border-dashed p-2.5"
                  }
                  onClick={async () => {
                    await Taro.chooseMessageFile({
                      type: "file",
                      count: 1,
                      success: (res) => {
                        setLoading(true);
                        const file = res.tempFiles[0];
                        uploadFile(file.path).then(({ url }) => {
                          setInvoiceImg([
                            {
                              fileName: url.split("/").pop(),
                              filePath: url,
                              fileSize: file.size,
                              fileType: url.split(".").pop(),
                            },
                          ]);
                          setLoading(false);
                          Toast.show("toast", {
                            title: "上传成功",
                            icon: "success",
                            content: "发票已添加",
                          });
                        });
                      },
                      fail: (err) => {
                        Toast.show("toast", {
                          title: "上传失败",
                          icon: "fail",
                          content: err.errMsg,
                        });
                      },
                    });
                  }}
                >
                  <Icon name={"file-pdf"} size={28} className="text-primary" />
                  <Text className="text-primary text-sm font-medium">
                    PDF文档
                  </Text>
                  <Text className="mt-1 text-xs text-gray-400">
                    点击上传PDF
                  </Text>
                </View>
                <View className={"text-primary text-sm font-medium"}>或</View>
                <View
                  className={
                    "border-primary bg-primary/5 flex h-24 flex-1 flex-col items-center justify-center rounded-md border-2 border-dashed p-2.5"
                  }
                  onClick={async () => {
                    await Taro.chooseImage({
                      count: 1,
                      success: (res) => {
                        setLoading(true);
                        const file = res.tempFiles[0];
                        uploadFile(file.path).then(({ url }) => {
                          setInvoiceImg([
                            {
                              fileName: url.split("/").pop(),
                              filePath: url,
                              fileSize: file.size,
                              fileType: url.split(".").pop(),
                            },
                          ]);
                          setLoading(false);
                          Toast.show("toast", {
                            title: "上传成功",
                            icon: "success",
                            content: "发票已添加",
                          });
                        });
                      },
                      fail: (err) => {
                        Toast.show("toast", {
                          title: "上传失败",
                          icon: "fail",
                          content: err.errMsg,
                        });
                      },
                    });
                  }}
                >
                  <Icon name={"camera"} size={28} className="text-primary" />
                  <Text className="text-primary text-sm font-medium">
                    拍照/相册
                  </Text>
                  <Text className="mt-1 text-xs text-gray-400">
                    点击上传照片
                  </Text>
                </View>
              </View>
            )}
          </View>
        </View>

        {/* 操作按钮 */}
        <View className={"flex flex-row gap-2 p-2.5"}>
          <View className={"flex-1"}>
            <Button
              size={"large"}
              block
              type="default"
              onClick={() => {
                setVisible(false);
                setInvoiceImg([]);
              }}
            >
              取消
            </Button>
          </View>
          {/* 提交按钮 */}
          <View className={"flex-1"}>
            <Button
              size={"large"}
              loading={submitLoading}
              block
              type="primary"
              disabled={invoiceImg?.length === 0}
              onClick={handleSubmit}
            >
              确认上传
            </Button>
          </View>
        </View>
      </View>
      <SafeArea position={"bottom"} />
    </Popup>
  );
}
