import { Image, View } from "@tarojs/components";
import { Icon } from "@/components";
import { Button, Toast } from "@nutui/nutui-react-taro";
import { OrderCalculator, uploadFile } from "@/utils";
import Taro from "@tarojs/taro";
import { globalStore } from "@/store/global-store";

interface ITicketUploadProps {
  index: number;
  value: BusinessAPI.OrderVO;
  onChange: (orderVO: BusinessAPI.OrderVO) => void;
}
export default function TicketUpload(props: ITicketUploadProps) {
  const { value, onChange, index } = props;

  const { setLoading } = globalStore((state: any) => state);
  const { orderSupplierList } = value;
  const supplierVO = orderSupplierList[index];

  const setSupplierVO = (supplierVO: BusinessAPI.OrderSupplier) => {
    const newOrderSupplierList = [...orderSupplierList];
    newOrderSupplierList[index] = supplierVO;
    onChange({
      ...value,
      orderSupplierList: newOrderSupplierList,
    });
  };

  if (!supplierVO) {
    return;
  }

  const calculator = new OrderCalculator(value).getSupplierCalculator(
    supplierVO,
  );

  return (
    <View className="flex flex-1 flex-col gap-2.5 bg-[#D1D5DB] p-2.5">
      <View className="border-primary rounded-lg border-4 bg-white p-2.5 shadow-sm">
        <View className="flex flex-col gap-2.5">
          <View className="text-primary text-base font-bold">
            {supplierVO.name}的应开票信息
          </View>

          {/* 应开票金额突出显示 */}
          <View className="rounded-xl bg-gradient-to-r from-green-500 to-green-600 p-4 text-white shadow-md">
            <View className="text-center">
              <View className="mb-1 text-sm font-medium opacity-90">
                应开票金额（元）
              </View>
              <View className="text-4xl font-bold">
                {supplierVO.invoiceAmount || 0}
              </View>
            </View>
          </View>

          {/* 计算公式区域 */}
          <View className="rounded-lg border border-gray-200 bg-gray-50 p-3">
            <View className="mb-2 flex items-center">
              <Icon name="calculator" className="mr-2 leading-4" size={20} />
              <View className="text-sm font-medium text-gray-700">
                计算明细
              </View>
            </View>
            <View className="space-y-1">
              <View className="flex justify-between text-sm">
                <View className="text-neutral-darker text-sm">
                  总重量（kg）
                </View>
                <View className="font-medium text-gray-800">
                  {supplierVO.totalWeight || 0}
                </View>
              </View>
              <View className="flex justify-between text-sm">
                <View className="text-neutral-darker text-sm">
                  空重量（kg）
                </View>
                <View className="font-medium text-gray-800">
                  {supplierVO.emptyWeight || 0}
                </View>
              </View>
              <View className="flex justify-between text-sm">
                <View className="text-neutral-darker text-sm">
                  箱重量（斤）
                </View>
                <View className="font-medium text-gray-800">
                  {calculator.calculateBoxesTotalWeight("USED") || 0}
                </View>
              </View>
              <View className="flex justify-between text-sm">
                <View className="text-neutral-darker text-sm">
                  净重量（斤）
                </View>
                <View className="font-medium text-gray-800">
                  {supplierVO.netWeight || 0}
                </View>
              </View>
              <View className="flex justify-between text-sm">
                <View className="text-neutral-darker text-sm">
                  毛重量（斤）
                </View>
                <View className="font-medium text-gray-800">
                  {supplierVO.grossWeight || 0}
                </View>
              </View>
              <View className="flex justify-between text-sm">
                <View className="text-neutral-darker text-sm">
                  采购单价（元/斤）
                </View>
                <View className="font-medium text-gray-800">
                  {supplierVO.purchasePrice || 0}
                </View>
              </View>
              <View className="flex justify-between text-sm">
                <View className="text-neutral-darker text-sm">报价方式</View>
                <View className="font-medium text-gray-800">
                  {supplierVO.pricingMethod === "BY_GROSS_WEIGHT"
                    ? "毛重"
                    : "净重"}
                </View>
              </View>
              <View className="my-2 h-px bg-gray-300"></View>
              <View className="text-neutral-darker text-center text-xs">
                计算公式：
                {supplierVO.pricingMethod === "BY_GROSS_WEIGHT"
                  ? "毛重"
                  : "净重"}
                量 × 采购单价
              </View>
            </View>
          </View>
        </View>
      </View>

      <View className="border-primary rounded-lg border-4 bg-white p-2.5 shadow-sm">
        <View className="flex flex-col gap-2.5">
          <View className="text-primary text-base font-bold">
            上传{supplierVO.name}的发票（可跳过）
          </View>

          {supplierVO.invoiceUpload ? (
            supplierVO.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 flex-shrink-0 overflow-hidden rounded-lg">
                    {uploadFileItem.fileType !== "pdf" ? (
                      <Image
                        className="h-full w-full object-cover"
                        src={uploadFileItem.filePath!}
                      />
                    ) : (
                      <Icon
                        className={
                          "bg-primary/10 flex h-16 w-16 items-center justify-center"
                        }
                        name="file-pdf"
                        size={32}
                      />
                    )}
                  </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={() => {
                        setSupplierVO({
                          ...supplierVO!,
                          invoiceImg: [],
                          invoiceUpload: false,
                          invoiceId: undefined,
                        });
                      }}
                    >
                      <View>重新上传</View>
                    </Button>
                  </View>
                  <View className={"flex-1"}>
                    <Button
                      type={"warning"}
                      size={"large"}
                      fill={"outline"}
                      block
                      onClick={() => {
                        setSupplierVO({
                          ...supplierVO!,
                          invoiceImg: [],
                          invoiceUpload: false,
                          invoiceId: undefined,
                        });
                        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 }) => {
                        if (!url) {
                          Toast.show("toast", {
                            title: "上传失败",
                            icon: "fail",
                            content: "上传失败",
                          });
                          return Promise.reject();
                        }
                        setSupplierVO({
                          ...supplierVO!,
                          invoiceImg: [
                            {
                              fileName: url.split("/").pop(),
                              filePath: url,
                              fileSize: file.size,
                              fileType: url.split(".").pop(),
                            },
                          ],
                          invoiceUpload: true,
                        });
                        setLoading(false);
                      });
                    },
                    fail: (err) => {
                      Toast.show("toast", {
                        title: "上传失败",
                        icon: "fail",
                        content: err.errMsg,
                      });
                    },
                  });
                }}
              >
                <Icon name={"camera"} size={24} />
                <View className="text-primary text-sm">添加文档</View>
                <View className="mt-1 text-xs text-gray-400">上传PDF文档</View>
              </View>
              <View className={"text-primary text-base"}>或</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 }) => {
                        if (!url) {
                          Toast.show("toast", {
                            title: "上传失败",
                            icon: "fail",
                            content: "上传失败",
                          });
                          return Promise.reject();
                        }
                        setSupplierVO({
                          ...supplierVO!,
                          invoiceImg: [
                            {
                              fileName: url.split("/").pop(),
                              filePath: url,
                              fileSize: file.size,
                              fileType: url.split(".").pop(),
                            },
                          ],
                          invoiceUpload: true,
                        });

                        setLoading(false);
                      });
                    },
                    fail: (err) => {
                      Toast.show("toast", {
                        title: "上传失败",
                        icon: "fail",
                        content: err.errMsg,
                      });
                    },
                  });
                }}
              >
                <Icon name={"camera"} size={24} />
                <View className="text-primary text-sm">添加照片</View>
                <View className="mt-1 text-xs text-gray-400">上传单张照片</View>
              </View>
            </View>
          )}
        </View>
      </View>

      <View className="border-primary rounded-lg border-4 bg-white p-2.5 shadow-sm">
        <View className="flex flex-col gap-2.5">
          <View className="text-primary text-base font-bold">
            上传{supplierVO.name}的合同（可跳过）
          </View>
          {supplierVO.contractUpload &&
            supplierVO.contractImg &&
            supplierVO.contractImg.length > 0 && (
              <View className="text-sm text-gray-500">
                已上传 {supplierVO.contractImg.length} 张
              </View>
            )}

          {supplierVO.contractUpload ? (
            <View className="flex flex-col gap-2.5">
              {supplierVO.contractImg?.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 flex-shrink-0 overflow-hidden rounded-lg">
                      <Image
                        className="h-full w-full object-cover"
                        src={uploadFileItem.filePath!}
                      />
                    </View>
                    <View className="flex-1">
                      <View className="font-medium">
                        {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={"warning"}
                        size={"large"}
                        fill={"outline"}
                        block
                        onClick={() => {
                          const newContractImg = supplierVO.contractImg?.filter(
                            (_, imgIndex) => imgIndex !== index,
                          );
                          setSupplierVO({
                            ...supplierVO!,
                            contractImg: newContractImg || [],
                            contractUpload:
                              (newContractImg && newContractImg.length > 0) ||
                              false,
                          });
                          Toast.show("toast", {
                            title: "删除成功",
                            icon: "success",
                            content: "合同已删除",
                          });
                        }}
                      >
                        <View>删除</View>
                      </Button>
                    </View>
                  </View>
                </View>
              ))}

              {/* 添加更多照片按钮 */}
              <View className="flex w-full flex-row 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.chooseImage({
                      count: 10, // 支持多选
                      success: (res) => {
                        setLoading(true);
                        const uploadPromises = res.tempFiles.map((file) =>
                          uploadFile(file.path).then(({ url }) => {
                            if (!url) {
                              Toast.show("toast", {
                                title: "上传失败",
                                icon: "fail",
                                content: "上传失败",
                              });
                              return Promise.reject();
                            }
                            return {
                              fileName: url.split("/").pop(),
                              filePath: url,
                              fileSize: file.size,
                              fileType: url.split(".").pop(),
                            };
                          }),
                        );

                        Promise.all(uploadPromises)
                          .then((newFiles) => {
                            const existingFiles = supplierVO.contractImg || [];
                            setSupplierVO({
                              ...supplierVO!,
                              contractImg: [...existingFiles, ...newFiles],
                              contractUpload: true,
                            });
                            setLoading(false);
                            Toast.show("toast", {
                              title: "上传成功",
                              icon: "success",
                              content: `已添加 ${newFiles.length} 张照片`,
                            });
                          })
                          .catch((err) => {
                            Toast.show("toast", {
                              title: "上传失败",
                              icon: "fail",
                              content: err.message || "上传过程中发生错误",
                            });
                            setLoading(false);
                          });
                      },
                      fail: (err) => {
                        Toast.show("toast", {
                          title: "选择图片失败",
                          icon: "fail",
                          content: err.errMsg,
                        });
                      },
                    });
                  }}
                >
                  <Icon name={"camera"} size={24} />
                  <View className="text-primary text-sm font-medium">
                    添加照片
                  </View>
                  <View className="mt-1 text-xs text-gray-400">最多10张</View>
                </View>
              </View>
            </View>
          ) : (
            <View className={`flex w-full flex-row 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.chooseImage({
                    count: 10, // 支持多选
                    success: (res) => {
                      setLoading(true);
                      const uploadPromises = res.tempFiles.map((file) =>
                        uploadFile(file.path).then(({ url }) => {
                          if (!url) {
                            Toast.show("toast", {
                              title: "上传失败",
                              icon: "fail",
                              content: "上传失败",
                            });
                            return Promise.reject();
                          }
                          return {
                            fileName: url.split("/").pop(),
                            filePath: url,
                            fileSize: file.size,
                            fileType: url.split(".").pop(),
                          };
                        }),
                      );

                      Promise.all(uploadPromises)
                        .then((newFiles) => {
                          setSupplierVO({
                            ...supplierVO!,
                            contractImg: newFiles,
                            contractUpload: true,
                          });
                          setLoading(false);
                          Toast.show("toast", {
                            title: "上传成功",
                            icon: "success",
                            content: `已上传 ${newFiles.length} 张照片`,
                          });
                        })
                        .catch((err) => {
                          Toast.show("toast", {
                            title: "上传失败",
                            icon: "fail",
                            content: err.message || "上传过程中发生错误",
                          });
                          setLoading(false);
                        });
                    },
                    fail: (err) => {
                      Toast.show("toast", {
                        title: "选择图片失败",
                        icon: "fail",
                        content: err.errMsg,
                      });
                    },
                  });
                }}
              >
                <Icon name={"camera"} size={24} />
                <View className="text-primary text-sm font-medium">
                  拍照上传
                </View>
                <View className="mt-1 text-xs text-gray-400">支持多张照片</View>
              </View>
            </View>
          )}

          <View className="text-center text-sm text-gray-500">
            支持 jpg、png 等格式，大小不超过 10M
          </View>
        </View>
      </View>
    </View>
  );
}
